52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
from fastapi import Request, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import JWT_SECRET, ACCESS_TOKEN_EXPIRE_MINUTES
|
|
from app.database import get_db
|
|
from app.models.user_settings import UserSettings
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
ALGORITHM = "HS256"
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
|
to_encode = data.copy()
|
|
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
|
to_encode.update({"exp": expire})
|
|
return jwt.encode(to_encode, JWT_SECRET, algorithm=ALGORITHM)
|
|
|
|
|
|
def decode_access_token(token: str) -> dict:
|
|
return jwt.decode(token, JWT_SECRET, algorithms=[ALGORITHM])
|
|
|
|
|
|
def get_current_user(request: Request) -> dict:
|
|
auth_header = request.headers.get("Authorization", "")
|
|
token = auth_header.replace("Bearer ", "")
|
|
if not token:
|
|
raise HTTPException(status_code=401, detail="未登录")
|
|
try:
|
|
payload = decode_access_token(token)
|
|
return payload
|
|
except JWTError:
|
|
raise HTTPException(status_code=401, detail="登录已过期,请重新登录")
|
|
|
|
|
|
def set_default_password(db: Session, settings: UserSettings):
|
|
if not settings.password_hash:
|
|
settings.password_hash = hash_password("elysia")
|
|
db.commit()
|