47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
from datetime import datetime, timedelta
|
||
|
||
import bcrypt
|
||
import jwt
|
||
from fastapi import Depends, HTTPException
|
||
from fastapi.security import OAuth2PasswordBearer
|
||
|
||
# 密钥,用于签名JWT
|
||
SECRET_KEY = "_CM__CMCMCM__CM_"
|
||
ALGORITHM = "HS256"
|
||
user_db = {
|
||
"admin": {
|
||
"user_id": "1",
|
||
"username": "admin",
|
||
"password": bcrypt.hashpw("admin123".encode("utf-8"), bcrypt.gensalt())
|
||
}
|
||
}
|
||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
|
||
|
||
|
||
def verify_password(plain_password, hashed_password):
|
||
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password)
|
||
|
||
|
||
def create_access_token(data: dict, expires_delta: timedelta = None):
|
||
to_encode = data.copy()
|
||
if expires_delta:
|
||
expire = datetime.utcnow() + expires_delta
|
||
else:
|
||
expire = datetime.utcnow() + timedelta(minutes=120)
|
||
to_encode.update({"exp": expire})
|
||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||
return encoded_jwt
|
||
|
||
|
||
def get_current_user(token: str = Depends(oauth2_scheme)):
|
||
try:
|
||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||
if payload["exp"] < int(datetime.utcnow().timestamp()):
|
||
raise HTTPException(status_code=401, detail="Token已过期")
|
||
username = payload["sub"]
|
||
except jwt.ExpiredSignatureError:
|
||
raise HTTPException(status_code=401, detail="Token已过期")
|
||
except jwt.InvalidSignatureError:
|
||
raise HTTPException(status_code=401, detail="Token无效")
|
||
return username
|