File size: 2,080 Bytes
91ca409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Blueprint, request, jsonify
from app.models import db, User, Role
from flask_bcrypt import generate_password_hash
from app import db, bcrypt
from flask_jwt_extended import create_access_token
from datetime import timedelta
bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()

    email = data.get('email')
    password = data.get('password')
    first_name = data.get('first_name')
    last_name = data.get('last_name')

    if not email or not password:
        return jsonify({"error": "Missing email or password"}), 400

    if User.query.filter_by(email=email).first():
        return jsonify({"error": "User already exists"}), 409

    hashed_password = generate_password_hash(password).decode('utf-8')
    user = User(email=email, password=hashed_password, first_name=first_name, last_name=last_name)

    # ROLE LOGIC
    if email == '[email protected]':
        role = Role.query.filter_by(name='admin').first()
    elif email == '[email protected]':
        role = Role.query.filter_by(name='expert').first()
    else:
        role = Role.query.filter_by(name='client').first()

    if not role:
        return jsonify({"error": f"Role not found in DB"}), 500

    user.roles.append(role)
    db.session.add(user)
    db.session.commit()

    return jsonify({"message": "User registered successfully"}), 201
@bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    email = data.get('email')
    password = data.get('password')

    if not email or not password:
        return jsonify({"error": "Email and password are required"}), 400

    user = User.query.filter_by(email=email).first()
    if not user or not bcrypt.check_password_hash(user.password, password):
        return jsonify({"error": "Invalid credentials"}), 401

    access_token = create_access_token(identity=str(user.id), expires_delta=timedelta(days=1))
    return jsonify({"access_token": access_token}), 200