From 622748cb371ee3dad0f65347e76fbc8aba7824d9 Mon Sep 17 00:00:00 2001 From: htylight Date: Thu, 11 Apr 2024 00:36:29 +0800 Subject: [PATCH] Add forgetting password api --- src/crud/user_crud.py | 15 ++++++++++++++- src/routers/signin.py | 25 +++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/crud/user_crud.py b/src/crud/user_crud.py index e001878..d6f541c 100755 --- a/src/crud/user_crud.py +++ b/src/crud/user_crud.py @@ -54,7 +54,9 @@ async def select_account_by( async def update_account( - account: Literal["username", "email", "password"], id: str, value: str + account: Literal["username", "email", "password"], + id: str, + value: str, ): session = async_session() match account: @@ -74,6 +76,17 @@ async def update_account( await session.close() +async def update_password(email: str, new_password: str): + session = async_session() + await session.execute( + update(UserAccount) + .where(UserAccount.email == email) + .values(password=new_password) + ) + await session.commit() + await session.close() + + async def select_profile(id: str) -> UserProfile: session = async_session() res: ScalarResult[UserProfile] = await session.scalars( diff --git a/src/routers/signin.py b/src/routers/signin.py index 3f99770..a54f35a 100755 --- a/src/routers/signin.py +++ b/src/routers/signin.py @@ -5,9 +5,9 @@ from pydantic import BaseModel from jose import ExpiredSignatureError, JWTError -from ..crud.user_crud import select_account_by +from ..crud.user_crud import select_account_by, update_password from ..utils.email_code import verify_code -from ..utils.password import verify_password +from ..utils.password import verify_password, get_hashed_password from ..utils.token_handler import ( create_signin_token, oauth2_scheme, @@ -27,6 +27,12 @@ class TokenPayload(BaseModel): device_id: str +class ForgetPasswordBody(BaseModel): + email: str + password: str + code: str + + @router.post("/username", response_model=UserAccountResponse) async def signin_by_username(form_data: OAuth2PasswordRequestForm = Depends()): username = form_data.username @@ -98,3 +104,18 @@ async def signin_by_token(token: str = Depends(oauth2_scheme)): "code": 9998, "msg": "Token Is Not Right", } + + +@router.post("/forget_password", response_model=UserAccountResponse) +async def forget_password(body: ForgetPasswordBody): + is_correct = verify_code(body.email, body.code) + if not is_correct: + return {"code": 10201, "msg": "The Verification Code Is Not Correct"} + + hashed_password = get_hashed_password(body.password) + + try: + await update_password(body.email, hashed_password) + return {"code": 10200, "msg": "Update Password Successfully"} + except Exception: + return {"code": 9999, "msg": "Update Password Fail, Please Try Again Later"}