Skip to content

Commit c9c1f53

Browse files
committed
♻️ Refactor password verification logic to update hashed password when needed
1 parent 1205029 commit c9c1f53

File tree

3 files changed

+19
-7
lines changed

3 files changed

+19
-7
lines changed

backend/app/api/routes/users.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ def update_password_me(
104104
"""
105105
Update own password.
106106
"""
107-
if not verify_password(body.current_password, current_user.hashed_password):
107+
verified, _ = verify_password(body.current_password, current_user.hashed_password)
108+
if not verified:
108109
raise HTTPException(status_code=400, detail="Incorrect password")
109110
if body.current_password == body.new_password:
110111
raise HTTPException(

backend/app/core/security.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,16 @@
22
from typing import Any
33

44
import jwt
5-
from passlib.context import CryptContext
5+
from pwdlib import PasswordHash
6+
from pwdlib.hashers.argon2 import Argon2Hasher
7+
from pwdlib.hashers.bcrypt import BcryptHasher
68

79
from app.core.config import settings
810

9-
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
11+
password_hash = PasswordHash((
12+
Argon2Hasher(),
13+
BcryptHasher(),
14+
))
1015

1116

1217
ALGORITHM = "HS256"
@@ -19,9 +24,9 @@ def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
1924
return encoded_jwt
2025

2126

22-
def verify_password(plain_password: str, hashed_password: str) -> bool:
23-
return pwd_context.verify(plain_password, hashed_password)
27+
def verify_password(plain_password: str, hashed_password: str) -> tuple[bool, str | None]:
28+
return password_hash.verify_and_update(plain_password, hashed_password)
2429

2530

2631
def get_password_hash(password: str) -> str:
27-
return pwd_context.hash(password)
32+
return password_hash.hash(password)

backend/app/crud.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,14 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
4141
db_user = get_user_by_email(session=session, email=email)
4242
if not db_user:
4343
return None
44-
if not verify_password(password, db_user.hashed_password):
44+
verified, updated_password_hash = verify_password(password, db_user.hashed_password)
45+
if not verified:
4546
return None
47+
if updated_password_hash:
48+
db_user.hashed_password = updated_password_hash
49+
session.add(db_user)
50+
session.commit()
51+
session.refresh(db_user)
4652
return db_user
4753

4854

0 commit comments

Comments
 (0)