fastapi-template/utils/token_tools.py

78 lines
2.9 KiB
Python

import jwt
import aioredis
from datetime import datetime, timedelta
from fastapi import status, Depends
from fastapi_plugins import depends_redis
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.exceptions import HTTPException
from utils.user_tools import get_user_by_email, authenticate_user
from common import schemas
SECRET_KEY = "5cf366d7b06714683756ca019c6283ed440bf771edd281d8"
tokenUrl = "/token"
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl=tokenUrl,
scopes={"me": "Read information about the current user.", "items": "Read items."},
)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(),
cache: aioredis.Redis = Depends(depends_redis)):
"""验证成功后返回有效的用户访问令牌"""
user = authenticate_user(form_data)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=60)
access_token = create_access_token(data={"sub": user.Email}, expires_delta=access_token_expires)
# 将access_token 存到缓存里面
await cache.setex("TOKEN:" + str(user.Id), access_token_expires.seconds, access_token)
return dict(access_token=access_token, access_type="bearer")
def create_access_token(*, data: dict,
expires_delta: timedelta = None,
algorithm="HS256"):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=algorithm)
return encoded_jwt
async def decode_access_token(token, cache: aioredis.Redis, algorithm="HS256"):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[algorithm])
email: str = payload.get("sub")
if email is None:
raise credentials_exception
token_data = schemas.TokenData(email=email)
except jwt.PyJWTError:
raise credentials_exception
user = get_user_by_email(email=token_data.email)
if user is None:
raise credentials_exception
# 查询缓存
cached_token = await cache.get("TOKEN:" + str(user.Id), encoding="utf-8")
if cached_token is None or cached_token != token:
raise credentials_exception
return user
async def get_current_user(token: str = Depends(oauth2_scheme),
cache: aioredis.Redis = Depends(depends_redis)):
current_user = await decode_access_token(token, cache)
return current_user