feat: refresh token 接口
This commit is contained in:
@@ -10,7 +10,7 @@ from starlette import status
|
|||||||
|
|
||||||
from app.config.env import env
|
from app.config.env import env
|
||||||
from app.model.BasicModel import BasicModel
|
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.db_utils import AsyncSessionDep
|
||||||
from app.utils.next_id import next_id
|
from app.utils.next_id import next_id
|
||||||
|
|
||||||
@@ -161,6 +161,26 @@ def add_user_route(app: FastAPI):
|
|||||||
"refresh_expires": refresh_expires,
|
"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")
|
@app.get("/users/me")
|
||||||
async def _me(current_user: PublicUser = Depends(get_current_user)):
|
async def _me(current_user: PublicUser = Depends(get_current_user)):
|
||||||
@@ -205,8 +225,9 @@ unauthorized_exception = HTTPException(
|
|||||||
# 获取当前用户信息,通过注入的token来获取当前用户信息,如果token有效则返回用户信息,无效则抛出异常
|
# 获取当前用户信息,通过注入的token来获取当前用户信息,如果token有效则返回用户信息,无效则抛出异常
|
||||||
async def get_current_user(session: AsyncSessionDep, token: str = Depends(oauth2_scheme)):
|
async def get_current_user(session: AsyncSessionDep, token: str = Depends(oauth2_scheme)):
|
||||||
try:
|
try:
|
||||||
username = CryptUtils.get_token_info(token).get('username')
|
token_info: TokenInfo = CryptUtils.get_token_info(token)
|
||||||
if not username:
|
username = token_info.get('username')
|
||||||
|
if not username or token_info.get('type') != 'access':
|
||||||
raise unauthorized_exception
|
raise unauthorized_exception
|
||||||
except InvalidTokenError:
|
except InvalidTokenError:
|
||||||
raise unauthorized_exception
|
raise unauthorized_exception
|
||||||
|
|||||||
Reference in New Issue
Block a user