utils.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
  2. from fastapi import HTTPException, status, Depends
  3. from apps.web.models.users import Users
  4. from apps.web.models.auths import Auths
  5. from pydantic import BaseModel
  6. from typing import Union, Optional
  7. from constants import ERROR_MESSAGES
  8. from passlib.context import CryptContext
  9. from datetime import datetime, timedelta
  10. import requests
  11. import jwt
  12. import uuid
  13. import logging
  14. import config
  15. logging.getLogger("passlib").setLevel(logging.ERROR)
  16. SESSION_SECRET = config.WEBUI_SECRET_KEY
  17. ALGORITHM = "HS256"
  18. ##############
  19. # Auth Utils
  20. ##############
  21. bearer_security = HTTPBearer()
  22. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  23. def verify_password(plain_password, hashed_password):
  24. return (
  25. pwd_context.verify(plain_password, hashed_password) if hashed_password else None
  26. )
  27. def get_password_hash(password):
  28. return pwd_context.hash(password)
  29. def create_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
  30. payload = data.copy()
  31. if expires_delta:
  32. expire = datetime.utcnow() + expires_delta
  33. payload.update({"exp": expire})
  34. encoded_jwt = jwt.encode(payload, SESSION_SECRET, algorithm=ALGORITHM)
  35. return encoded_jwt
  36. def decode_token(token: str) -> Optional[dict]:
  37. try:
  38. decoded = jwt.decode(token, SESSION_SECRET, algorithms=[ALGORITHM])
  39. return decoded
  40. except Exception as e:
  41. return None
  42. def extract_token_from_auth_header(auth_header: str):
  43. return auth_header[len("Bearer ") :]
  44. def create_api_key():
  45. key = str(uuid.uuid4()).replace("-", "")
  46. return f"sk-{key}"
  47. def get_http_authorization_cred(auth_header: str):
  48. try:
  49. scheme, credentials = auth_header.split(" ")
  50. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
  51. except:
  52. raise ValueError(ERROR_MESSAGES.INVALID_TOKEN)
  53. def get_current_user(
  54. auth_token: HTTPAuthorizationCredentials = Depends(bearer_security),
  55. ):
  56. # auth by api key
  57. if auth_token.credentials.startswith("sk-"):
  58. return get_current_user_by_api_key(auth_token.credentials)
  59. # auth by jwt token
  60. data = decode_token(auth_token.credentials)
  61. if data != None and "id" in data:
  62. user = Users.get_user_by_id(data["id"])
  63. if user is None:
  64. raise HTTPException(
  65. status_code=status.HTTP_401_UNAUTHORIZED,
  66. detail=ERROR_MESSAGES.INVALID_TOKEN,
  67. )
  68. return user
  69. else:
  70. raise HTTPException(
  71. status_code=status.HTTP_401_UNAUTHORIZED,
  72. detail=ERROR_MESSAGES.UNAUTHORIZED,
  73. )
  74. def get_current_user_by_api_key(api_key: str):
  75. user = Auths.authenticate_user_by_api_key(api_key)
  76. if user is None:
  77. raise HTTPException(
  78. status_code=status.HTTP_401_UNAUTHORIZED,
  79. detail=ERROR_MESSAGES.INVALID_TOKEN,
  80. )
  81. return user
  82. def get_verified_user(user=Depends(get_current_user)):
  83. if user.role not in {"user", "admin"}:
  84. raise HTTPException(
  85. status_code=status.HTTP_401_UNAUTHORIZED,
  86. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  87. )
  88. return user
  89. def get_admin_user(user=Depends(get_current_user)):
  90. if user.role != "admin":
  91. raise HTTPException(
  92. status_code=status.HTTP_401_UNAUTHORIZED,
  93. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  94. )
  95. return user