auth.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import logging
  2. from abc import ABC, abstractmethod
  3. from typing import TYPE_CHECKING, Optional
  4. from fastapi import Security
  5. from fastapi.security import (
  6. APIKeyHeader,
  7. HTTPAuthorizationCredentials,
  8. HTTPBearer,
  9. )
  10. from ..abstractions import R2RException, Token, TokenData
  11. from ..api.models import User
  12. from .base import Provider, ProviderConfig
  13. from .crypto import CryptoProvider
  14. # from .database import DatabaseProvider
  15. from .email import EmailProvider
  16. logger = logging.getLogger()
  17. if TYPE_CHECKING:
  18. from core.database import PostgresDatabaseProvider
  19. api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
  20. class AuthConfig(ProviderConfig):
  21. secret_key: Optional[str] = None
  22. require_authentication: bool = False
  23. require_email_verification: bool = False
  24. default_admin_email: str = "admin@example.com"
  25. default_admin_password: str = "change_me_immediately"
  26. access_token_lifetime_in_minutes: Optional[int] = None
  27. refresh_token_lifetime_in_days: Optional[int] = None
  28. @property
  29. def supported_providers(self) -> list[str]:
  30. return ["r2r"]
  31. def validate_config(self) -> None:
  32. pass
  33. class AuthProvider(Provider, ABC):
  34. security = HTTPBearer(auto_error=False)
  35. crypto_provider: CryptoProvider
  36. email_provider: EmailProvider
  37. database_provider: "PostgresDatabaseProvider"
  38. def __init__(
  39. self,
  40. config: AuthConfig,
  41. crypto_provider: CryptoProvider,
  42. database_provider: "PostgresDatabaseProvider",
  43. email_provider: EmailProvider,
  44. ):
  45. if not isinstance(config, AuthConfig):
  46. raise ValueError(
  47. "AuthProvider must be initialized with an AuthConfig"
  48. )
  49. self.config = config
  50. self.admin_email = config.default_admin_email
  51. self.admin_password = config.default_admin_password
  52. self.crypto_provider = crypto_provider
  53. self.database_provider = database_provider
  54. self.email_provider = email_provider
  55. super().__init__(config)
  56. self.config: AuthConfig = config
  57. self.database_provider: "PostgresDatabaseProvider" = database_provider
  58. async def _get_default_admin_user(self) -> User:
  59. return await self.database_provider.users_handler.get_user_by_email(
  60. self.admin_email
  61. )
  62. @abstractmethod
  63. def create_access_token(self, data: dict) -> str:
  64. pass
  65. @abstractmethod
  66. def create_refresh_token(self, data: dict) -> str:
  67. pass
  68. @abstractmethod
  69. async def decode_token(self, token: str) -> TokenData:
  70. pass
  71. @abstractmethod
  72. async def user(self, token: str) -> User:
  73. pass
  74. @abstractmethod
  75. def get_current_active_user(self, current_user: User) -> User:
  76. pass
  77. @abstractmethod
  78. async def register(self, email: str, password: str) -> User:
  79. pass
  80. @abstractmethod
  81. async def verify_email(
  82. self, email: str, verification_code: str
  83. ) -> dict[str, str]:
  84. pass
  85. @abstractmethod
  86. async def login(self, email: str, password: str) -> dict[str, Token]:
  87. pass
  88. @abstractmethod
  89. async def refresh_access_token(
  90. self, refresh_token: str
  91. ) -> dict[str, Token]:
  92. pass
  93. def auth_wrapper(
  94. self,
  95. public: bool = False,
  96. ):
  97. async def _auth_wrapper(
  98. auth: Optional[HTTPAuthorizationCredentials] = Security(
  99. self.security
  100. ),
  101. api_key: Optional[str] = Security(api_key_header),
  102. ) -> User:
  103. # If authentication is not required and no credentials are provided, return the default admin user
  104. if (
  105. ((not self.config.require_authentication) or public)
  106. and auth is None
  107. and api_key is None
  108. ):
  109. return await self._get_default_admin_user()
  110. if not auth and not api_key:
  111. raise R2RException(
  112. message="No credentials provided",
  113. status_code=401,
  114. )
  115. if auth and api_key:
  116. raise R2RException(
  117. message="Cannot have both Bearer token and API key",
  118. status_code=400,
  119. )
  120. # 1. Try JWT if `auth` is present (Bearer token)
  121. if auth is not None:
  122. credentials = auth.credentials
  123. try:
  124. token_data = await self.decode_token(credentials)
  125. user = await self.database_provider.users_handler.get_user_by_email(
  126. token_data.email
  127. )
  128. if user is not None:
  129. return user
  130. except R2RException:
  131. # JWT decoding failed for logical reasons (invalid token)
  132. pass
  133. except Exception as e:
  134. # JWT decoding failed unexpectedly, log and continue
  135. logger.debug(f"JWT verification failed: {e}")
  136. # 2. If JWT failed, try API key from Bearer token
  137. # Expected format: key_id.raw_api_key
  138. if "." in credentials:
  139. key_id, raw_api_key = credentials.split(".", 1)
  140. api_key_record = await self.database_provider.users_handler.get_api_key_record(
  141. key_id
  142. )
  143. if api_key_record is not None:
  144. hashed_key = api_key_record["hashed_key"]
  145. if self.crypto_provider.verify_api_key(
  146. raw_api_key, hashed_key
  147. ):
  148. user = await self.database_provider.users_handler.get_user_by_id(
  149. api_key_record["user_id"]
  150. )
  151. if user is not None and user.is_active:
  152. return user
  153. # 3. If no Bearer token worked, try the X-API-Key header
  154. if api_key is not None and "." in api_key:
  155. key_id, raw_api_key = api_key.split(".", 1)
  156. api_key_record = await self.database_provider.users_handler.get_api_key_record(
  157. key_id
  158. )
  159. if api_key_record is not None:
  160. hashed_key = api_key_record["hashed_key"]
  161. if self.crypto_provider.verify_api_key(
  162. raw_api_key, hashed_key
  163. ):
  164. user = await self.database_provider.users_handler.get_user_by_id(
  165. api_key_record["user_id"]
  166. )
  167. if user is not None and user.is_active:
  168. return user
  169. # If we reach here, both JWT and API key auth failed
  170. raise R2RException(
  171. message="Invalid token or API key",
  172. status_code=401,
  173. )
  174. return _auth_wrapper
  175. @abstractmethod
  176. async def change_password(
  177. self, user: User, current_password: str, new_password: str
  178. ) -> dict[str, str]:
  179. pass
  180. @abstractmethod
  181. async def request_password_reset(self, email: str) -> dict[str, str]:
  182. pass
  183. @abstractmethod
  184. async def confirm_password_reset(
  185. self, reset_token: str, new_password: str
  186. ) -> dict[str, str]:
  187. pass
  188. @abstractmethod
  189. async def logout(self, token: str) -> dict[str, str]:
  190. pass
  191. @abstractmethod
  192. async def send_reset_email(self, email: str) -> dict[str, str]:
  193. pass