diff --git a/routes/auth.py b/routes/auth.py index 82c6aab..06ece83 100644 --- a/routes/auth.py +++ b/routes/auth.py @@ -1,3 +1,4 @@ +# routes/auth.py from flask import Blueprint, request, jsonify from services.user import UserService @@ -7,17 +8,8 @@ user_service = UserService() @auth_bp.route('/signup', methods=['POST']) def signup(): data = request.get_json() - username = data.get('username') - password = data.get('password') - - if not username or not password: - return jsonify({"error": "Username and password are required"}), 400 - - if len(username) < 3 or len(password) < 8: - return jsonify({"error": "Username must be at least 3 characters and password must be at least 8 characters."}), 400 - try: - new_user = user_service.create_user(username, password) + new_user = user_service.create_user(data['username'], data['password']) return jsonify({"message": "User created successfully", "username": new_user.username}), 201 except ValueError as e: return jsonify({"message": str(e)}), 400 @@ -25,14 +17,8 @@ def signup(): @auth_bp.route('/login', methods=['POST']) def login(): data = request.get_json() - username = data.get('username') - password = data.get('password') - - if not username or not password: - return jsonify({"error": "Username and password are required"}), 400 - try: - user = user_service.verify_user(username, password) + user = user_service.verify_user(data['username'], data['password']) return jsonify({"message": "Login successful", "user_id": user.id}), 200 except ValueError as e: return jsonify({"error": str(e)}), 401 diff --git a/services/user.py b/services/user.py index 60754df..9c86d08 100644 --- a/services/user.py +++ b/services/user.py @@ -1,13 +1,21 @@ -from werkzeug.security import generate_password_hash, check_password_hash from models.user import User, db +from werkzeug.security import generate_password_hash, check_password_hash class UserService: def create_user(self, username, password): + if not username or not password: + return jsonify({"error": "Username and password are required"}), 400 + + if len(username) < 3 or len(password) < 8: + return jsonify({"error": "Username must be at least 3 characters and password must be at least 8 characters."}), 400 + + existing_user = User.query.filter_by(username=username).first() if existing_user: raise ValueError("User already exists") - new_user = User(username=username, password=password) + hashed_password = generate_password_hash(password) + new_user = User(username=username, password=hashed_password) db.session.add(new_user) db.session.commit() return new_user