from flask import Blueprint, jsonify, request from services.UserService import UserService from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity from middlewares import validate_user_post_request, validate_user_login_request, authenticate_user userRoutes = Blueprint('userRoutes', __name__) @userRoutes.route('/', methods=['GET']) @userRoutes.route('', methods=['GET']) @authenticate_user def allUsers(): users = UserService.get_all_users() return jsonify(users), 200 @userRoutes.route('/', methods=['POST']) @userRoutes.route('', methods=['POST']) @validate_user_post_request def createNewUser(): try: data = request.json if UserService.get_user_by_email(data['email']): return jsonify({'error': 'User already exists'}), 400 new_user = UserService.create_user(data) if new_user: return jsonify(new_user), 201 else: return jsonify({'error': 'Failed to create user'}), 400 except Exception as e: return jsonify({'error': str(e)}), 500 @userRoutes.route('/login', methods=['POST']) @validate_user_login_request def loginUser(): try: data = request.json user = UserService.verify_user(data) if user: sessionToken = create_access_token(identity=user.id) response = jsonify(user.to_dict()) response.set_cookie('access_token_cookie', sessionToken, httponly=True, path='/') return response, 200 else: return jsonify({'error': 'Invalid credentials'}), 400 except Exception as e: return jsonify({'error': str(e)}), 500