Spaces:
Sleeping
Sleeping
Rename routes to routes/auth.py
Browse files- routes +0 -0
- routes/auth.py +39 -0
routes
DELETED
|
File without changes
|
routes/auth.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint, request, jsonify
|
| 2 |
+
import bcrypt, jwt, os
|
| 3 |
+
from datetime import datetime, timedelta
|
| 4 |
+
|
| 5 |
+
auth_bp = Blueprint("auth", __name__)
|
| 6 |
+
JWT_SECRET = os.getenv("JWT_SECRET")
|
| 7 |
+
|
| 8 |
+
@auth_bp.route("/signup", methods=["POST"])
|
| 9 |
+
def signup():
|
| 10 |
+
from app import db
|
| 11 |
+
data = request.json
|
| 12 |
+
if db.users.find_one({"email": data["email"]}):
|
| 13 |
+
return jsonify({"error": "User exists"}), 400
|
| 14 |
+
|
| 15 |
+
hashed_pw = bcrypt.hashpw(data["password"].encode(), bcrypt.gensalt())
|
| 16 |
+
db.users.insert_one({
|
| 17 |
+
"name": data["name"],
|
| 18 |
+
"email": data["email"],
|
| 19 |
+
"password": hashed_pw,
|
| 20 |
+
"role": "student",
|
| 21 |
+
"created_at": datetime.utcnow()
|
| 22 |
+
})
|
| 23 |
+
return jsonify({"message": "Signup successful"}), 201
|
| 24 |
+
|
| 25 |
+
@auth_bp.route("/login", methods=["POST"])
|
| 26 |
+
def login():
|
| 27 |
+
from app import db
|
| 28 |
+
data = request.json
|
| 29 |
+
user = db.users.find_one({"email": data["email"]})
|
| 30 |
+
if not user or not bcrypt.checkpw(data["password"].encode(), user["password"]):
|
| 31 |
+
return jsonify({"error": "Invalid credentials"}), 401
|
| 32 |
+
|
| 33 |
+
token = jwt.encode({
|
| 34 |
+
"id": str(user["_id"]),
|
| 35 |
+
"role": user["role"],
|
| 36 |
+
"exp": datetime.utcnow() + timedelta(hours=2)
|
| 37 |
+
}, JWT_SECRET, algorithm="HS256")
|
| 38 |
+
|
| 39 |
+
return jsonify({"token": token, "role": user["role"], "name": user["name"]})
|