File size: 3,144 Bytes
ebf88d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from flask import Blueprint, request, jsonify
from utils.auth import hash_password, check_password, generate_token, verify_token
import pymongo
from bson import ObjectId

# Define a Blueprint for authentication routes
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')

# MongoDB connection
client = pymongo.MongoClient("mongodb+srv://pmsankheb23:[email protected]/")
db = client["Eloquence"]
collections_user = db["user"]

# ROUTE 1: Create a user using POST: auth/create, no auth required
@auth_bp.route('/create', methods=['POST'])
def create_user():
    try:
        data = request.get_json()
        username = data['username']
        email = data['email']
        password = data['password']

        # Check if user already exists
        if collections_user.find_one({'email': email}):
            return jsonify({"error": "User with this email already exists"}), 400

        # Hash the password
        hashed_password = hash_password(password)

        # Insert the new user
        result = collections_user.insert_one({'username': username, 'password': hashed_password, 'email': email})
        user_id = str(result.inserted_id)

        # Generate JWT token
        token = generate_token(username) # Or email, depending on your token strategy

        return jsonify({
            "message": "User created",
            "authToken": token,
            "userId": user_id,
            "username": username
        }), 201

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ROUTE 2: Authenticate a user using POST: auth/login, no login required
@auth_bp.route('/login', methods=['POST'])
def login_user():
    try:
        data = request.get_json()
        email = data['email']
        password = data['password']

        user = collections_user.find_one({'email': email})
        if not user:
            return jsonify({"error": "User not found"}), 404

        if not check_password(user['password'], password):
            return jsonify({"error": "Invalid password"}), 401

        user_id = str(user['_id'])
        username = user['username']

        # Generate JWT token
        token = generate_token(username) # Or email, consistent with your token strategy

        return jsonify({
            "message": "Login successful",
            "token": token,
            "userId": user_id,
            "username": username
        }), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# ROUTE 3: Get logged-in user details using POST: auth/protected, login required
@auth_bp.route('/protected', methods=['POST'])
def protected():
    # Get token from the body as it's a post method
    token = request.json.get("token", None)

    if not token:
        return jsonify({"error": "Token missing"}), 401

    # Remove 'Bearer ' from the token string if it's present
    token = token.replace("Bearer ", "")
    username = verify_token(token)  # Verify the token

    if not username:
        return jsonify({"error": "Invalid or expired token"}), 401

    return jsonify({"message": f"Hello, {username}! This is a protected route."})