From 317c177df25db931a7ed3d7c0906b95aa7714a09 Mon Sep 17 00:00:00 2001 From: Emyr298 Date: Sat, 15 Jun 2024 10:19:05 +0700 Subject: [PATCH] feat: add old password verification --- cefies/models/profile.py | 3 ++- cefies/routes/profile.py | 11 ++++++++--- cefies/security.py | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/cefies/models/profile.py b/cefies/models/profile.py index 59e72ab..c221967 100644 --- a/cefies/models/profile.py +++ b/cefies/models/profile.py @@ -9,7 +9,8 @@ class ProfileData(BaseModel): class ChangePasswordData(BaseModel): - password: Annotated[str, StringConstraints(min_length=8)] + new_password: Annotated[str, StringConstraints(min_length=8)] + old_password: Annotated[str, StringConstraints(min_length=8)] class EditProfileData(BaseModel): diff --git a/cefies/routes/profile.py b/cefies/routes/profile.py index 04b29cf..1b97187 100644 --- a/cefies/routes/profile.py +++ b/cefies/routes/profile.py @@ -1,14 +1,13 @@ import asyncio from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, status -from fastapi.responses import JSONResponse from pydantic import ValidationError from cefies.models.db.user import User from cefies.models.forms.profile import EditProfileForm from cefies.models.profile import ProfileData, ChangePasswordData, EditProfileData from cefies.models.response import MessageResponse -from cefies.security import get_current_user, get_password_hash, get_hash_sha256 +from cefies.security import get_current_user, get_password_hash, get_hash_sha256, verify_password from cefies.internal import bucket router = APIRouter(prefix="/profile") @@ -58,6 +57,12 @@ def change_password( user: Annotated[User, Depends(get_current_user)], data: ChangePasswordData, ) -> MessageResponse: - user.password = get_password_hash(data.password) + if not verify_password(data.old_password, user.password): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid old password", + ) + + user.password = get_password_hash(data.new_password) user.save() return MessageResponse(error=False, message="Password changed") diff --git a/cefies/security.py b/cefies/security.py index 69ce00d..97b26f1 100644 --- a/cefies/security.py +++ b/cefies/security.py @@ -27,6 +27,10 @@ def authenticate_user(email: str, password: str): return cast(User, user) +def verify_password(password: str, hashed_password: str): + return bcrypt.checkpw(password.encode(), hashed_password.encode()) + + def create_access_token(user_id: str, expires_delta: timedelta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)): expire = datetime.now(timezone.utc) + expires_delta encoded_jwt = jwt.encode(