Skip to content

Commit

Permalink
feat: add old password verification
Browse files Browse the repository at this point in the history
  • Loading branch information
Emyr298 committed Jun 15, 2024
1 parent 876fd53 commit 317c177
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
3 changes: 2 additions & 1 deletion cefies/models/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
11 changes: 8 additions & 3 deletions cefies/routes/profile.py
Original file line number Diff line number Diff line change
@@ -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")
Expand Down Expand Up @@ -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")
4 changes: 4 additions & 0 deletions cefies/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 317c177

Please sign in to comment.