diff --git a/project_amber/app.py b/project_amber/app.py index c37db6a..4b311c8 100644 --- a/project_amber/app.py +++ b/project_amber/app.py @@ -12,7 +12,7 @@ handle_session_id_req from project_amber.handlers.task import handle_task_id_request, \ handle_task_request -from project_amber.handlers.users import signup +from project_amber.handlers.users import signup, update_user_data app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = config["database"] @@ -33,6 +33,7 @@ def middleware(): methods=["GET", "POST"]) app.add_url_rule("/api/task/", "task_id", handle_task_id_request, \ methods=["GET", "PATCH", "DELETE"]) +app.add_url_rule("/api/user", "user", update_user_data, methods=["PATCH"]) app.add_url_rule("/api/session", "session", handle_session_req, methods=["GET"]) app.add_url_rule("/api/session/", "session_id", \ handle_session_id_req, methods=["GET", "DELETE"]) diff --git a/project_amber/handlers/users.py b/project_amber/handlers/users.py index 5774c52..62f6226 100644 --- a/project_amber/handlers/users.py +++ b/project_amber/handlers/users.py @@ -2,7 +2,21 @@ from project_amber.const import EMPTY_RESP from project_amber.errors import BadRequest -from project_amber.helpers.auth import addUser +from project_amber.helpers.auth import addUser, updateUser + +def update_user_data(): + """ + User data PATCH request handler. Accepts JSON with these parameters: + ``` + { + "password": "my_new_password" + } + ``` + Returns HTTP 200 on success. + """ + if "password" in request.json: + updateUser(password=request.json.get("password")) + return EMPTY_RESP def signup(): """ diff --git a/project_amber/helpers/auth.py b/project_amber/helpers/auth.py index 92db48a..510a90f 100644 --- a/project_amber/helpers/auth.py +++ b/project_amber/helpers/auth.py @@ -6,7 +6,7 @@ from project_amber.const import MSG_USER_NOT_FOUND, MSG_USER_EXISTS from project_amber.db import db -from project_amber.helpers import time +from project_amber.helpers import time, LoginUser from project_amber.errors import Unauthorized, NotFound, Conflict from project_amber.logging import log from project_amber.models.auth import User, Session @@ -33,6 +33,21 @@ def addUser(name: str, password: str) -> int: db.session.commit() return user.id +def updateUser(**kwargs) -> int: + """ + Updates user data in the database. Returns their ID on success. + """ + user: LoginUser = request.user + user_record = db.session.query(User).filter_by(id=user.id).one() + for attribute in kwargs: + if attribute == "password": + user_record.password = hashpw( + prehash(kwargs["password"]), + gensalt() + ).decode() + db.session.commit() + return user.id + def removeUser(uid: int) -> int: """ Removes a user given their ID. Returns their ID on success.