2023-01-31 16:24:56 +00:00
|
|
|
import datetime
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from fastapi import Header, HTTPException, Depends
|
|
|
|
from jose import jwt
|
|
|
|
|
|
|
|
from pagermaid.config import Config
|
|
|
|
|
2023-03-12 03:56:01 +00:00
|
|
|
ALGORITHM = "HS256"
|
2023-01-31 16:24:56 +00:00
|
|
|
TOKEN_EXPIRE_MINUTES = 30
|
|
|
|
|
|
|
|
|
|
|
|
def authentication():
|
2024-08-12 07:38:32 +00:00
|
|
|
def inner(token: Optional[str] = Header(None)):
|
2023-01-31 16:46:26 +00:00
|
|
|
if Config.WEB_SECRET_KEY:
|
2023-02-01 06:39:41 +00:00
|
|
|
if token == Config.WEB_SECRET_KEY:
|
|
|
|
return
|
2023-01-31 16:46:26 +00:00
|
|
|
try:
|
|
|
|
jwt.decode(token, Config.WEB_SECRET_KEY, algorithms=ALGORITHM)
|
|
|
|
except (jwt.JWTError, jwt.ExpiredSignatureError, AttributeError):
|
2023-03-12 03:56:01 +00:00
|
|
|
raise HTTPException(status_code=400, detail="登录验证失败或已失效,请重新登录")
|
2023-01-31 16:24:56 +00:00
|
|
|
|
|
|
|
return Depends(inner)
|
|
|
|
|
|
|
|
|
|
|
|
def create_token():
|
|
|
|
data = {
|
2023-03-12 03:56:01 +00:00
|
|
|
"exp": datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
+ datetime.timedelta(minutes=TOKEN_EXPIRE_MINUTES),
|
2023-01-31 16:24:56 +00:00
|
|
|
}
|
|
|
|
return jwt.encode(data, Config.WEB_SECRET_KEY, algorithm=ALGORITHM)
|