diff --git a/README.md b/README.md index c0f71b6..f141b23 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ update, delete, and be reminded of events with additional advanced features. - GET /user - returns all users - GET /user/{id} - returns a single user -- POST /user - create a new user (Auth) +- POST /user - create a new user - PUT /user/{id} - update an user (Auth + authorized) - DELETE /user/{id} - (Soft)delete an user (Auth + authorized) diff --git a/routes/userRoutes.py b/routes/userRoutes.py index a27f33e..e3aac1c 100644 --- a/routes/userRoutes.py +++ b/routes/userRoutes.py @@ -1,7 +1,7 @@ -from flask import Blueprint, jsonify, request +from flask import Blueprint, jsonify, request, g from services.UserService import UserService from flask_jwt_extended import JWTManager, jwt_required, create_access_token -from middlewares.userMiddlewares import validate_user_post_request, validate_user_login_request +from middlewares.userMiddlewares import validate_user_post_request, validate_user_login_request, authenticate_user userRoutes = Blueprint('userRoutes', __name__) @@ -19,7 +19,21 @@ def getUser(user_id): else: return jsonify({'error': 'User not found'}), 404 - +@userRoutes.route('/', methods=['PUT']) +@validate_user_post_request +@authenticate_user +def updateUser(user_id): + try: + if user_id != g.user_id: + return jsonify({'error': 'Unauthorized'}), 401 + data = request.json + updated_user = UserService.update_user(user_id, data) + if updated_user: + return jsonify(updated_user), 200 + else: + return jsonify({'error': 'User not found'}), 404 + except Exception as e: + return jsonify({'error': str(e)}), 500 @userRoutes.route('/', methods=['POST']) @userRoutes.route('', methods=['POST']) diff --git a/services/UserService.py b/services/UserService.py index 1f13767..981da84 100644 --- a/services/UserService.py +++ b/services/UserService.py @@ -47,3 +47,15 @@ class UserService: return [user.to_dict() for user in users] + @staticmethod + def update_user(user_id, data): + # update user + user = User.query.filter_by(id=user_id).first() + if user: + user.name = data['username'] + user.email = data['email'] + user.location = data['location'] + db.session.commit() + return user.to_dict() + return None + \ No newline at end of file