You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.5 KiB

11 months ago
11 months ago
11 months ago
8 months ago
11 months ago
11 months ago
11 months ago
11 months ago
7 months ago
11 months ago
11 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
8 months ago
11 months ago
8 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
8 months ago
11 months ago
8 months ago
11 months ago
8 months ago
11 months ago
8 months ago
11 months ago
11 months ago
  1. from datetime import datetime, timedelta, timezone
  2. from jose import JWTError, jwt
  3. from passlib.context import CryptContext
  4. from fastapi.security import OAuth2PasswordBearer
  5. from fastapi import Depends, HTTPException, status
  6. from internal.models import TokenData, UserInDB, User
  7. from internal.database import execute_query
  8. # openssl rand -hex 32
  9. SECRET_KEY = "e86c54c19962d562dab09081e5a6ce0c8ef49ac9a49cdb7135aa670707bbc894"
  10. ALGORITHM = "HS256"
  11. ACCESS_TOKEN_EXPIRE_MINUTES = 240
  12. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  13. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/token")
  14. # 创建访问令牌
  15. def create_access_token(data: dict, expires_delta: timedelta):
  16. to_encode = data.copy()
  17. expire = datetime.now(timezone.utc) + expires_delta
  18. to_encode.update({"exp": expire})
  19. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  20. return encoded_jwt
  21. # 从数据库获取信息
  22. def get_user(username: str):
  23. query = "SELECT * FROM users WHERE username = %s"
  24. result = execute_query(query, (username,), fetchall=False)
  25. if result:
  26. return UserInDB(**result)
  27. async def get_current_user(token: str = Depends(oauth2_scheme)):
  28. credentials_exception = HTTPException(
  29. status_code=status.HTTP_401_UNAUTHORIZED,
  30. detail="Could not validate credentials",
  31. headers={"WWW-Authenticate": "Bearer"},
  32. )
  33. try:
  34. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  35. username: str = payload.get("sub")
  36. if username is None:
  37. raise credentials_exception
  38. token_data = TokenData(username=username)
  39. except JWTError:
  40. raise credentials_exception
  41. user = get_user(username=token_data.username)
  42. if user is None:
  43. raise credentials_exception
  44. return user
  45. # 验证用户是否为活跃用户
  46. async def get_current_active_user(current_user: User = Depends(get_current_user)):
  47. if current_user.disabled:
  48. raise HTTPException(status_code=400, detail="Inactive user")
  49. return current_user
  50. # 验证密码
  51. def verify_password(plain_password, hashed_password):
  52. return pwd_context.verify(plain_password, hashed_password)
  53. # 获取密码哈希
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. # 验证用户密码
  57. def authenticate_user(username: str, password: str):
  58. user = get_user(username)
  59. if not user:
  60. return False
  61. if not verify_password(password, user.hashed_password):
  62. return False
  63. return user