utils.py 3.5 KB

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