From 1a9365d96f40453022ebf818a664197050e176ae Mon Sep 17 00:00:00 2001 From: martsforever Date: Fri, 22 Aug 2025 16:21:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20refresh=20token=20=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/add_user_route.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/app/controller/add_user_route.py b/app/controller/add_user_route.py index fc240b4..041c3f3 100644 --- a/app/controller/add_user_route.py +++ b/app/controller/add_user_route.py @@ -10,7 +10,7 @@ from starlette import status from app.config.env import env from app.model.BasicModel import BasicModel -from app.utils.CrpyUtils import CryptUtils +from app.utils.CrpyUtils import CryptUtils, TokenInfo from app.utils.db_utils import AsyncSessionDep from app.utils.next_id import next_id @@ -161,6 +161,26 @@ def add_user_route(app: FastAPI): "refresh_expires": refresh_expires, } + @app.post("/refresh") + async def refresh_token(data: dict): + refresh_token: TokenInfo = data.get('refresh_token') + token_info = CryptUtils.get_token_info(refresh_token) + if token_info.get('type') != 'refresh': + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="token类型不正确", + ) + access_token = CryptUtils.create_token( + username=refresh_token.get("username"), + type="access", + expires_delta=timedelta(minutes=env.jwt_access_token_expire_minutes), + ) + access_expires = env.jwt_access_token_expire_minutes * 60 * 1000 + return { + "access_token": access_token, + "access_expires": access_expires, + } + # 获取用户信息接口 @app.get("/users/me") async def _me(current_user: PublicUser = Depends(get_current_user)): @@ -205,8 +225,9 @@ unauthorized_exception = HTTPException( # 获取当前用户信息,通过注入的token来获取当前用户信息,如果token有效则返回用户信息,无效则抛出异常 async def get_current_user(session: AsyncSessionDep, token: str = Depends(oauth2_scheme)): try: - username = CryptUtils.get_token_info(token).get('username') - if not username: + token_info: TokenInfo = CryptUtils.get_token_info(token) + username = token_info.get('username') + if not username or token_info.get('type') != 'access': raise unauthorized_exception except InvalidTokenError: raise unauthorized_exception