Skip to content

Commit

Permalink
♻️ refactor(api-auth): implement standards
Browse files Browse the repository at this point in the history
  • Loading branch information
dannil76 committed Oct 31, 2024
1 parent 348de3d commit 5d87aea
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 19 deletions.
32 changes: 15 additions & 17 deletions fai-rag-app/fai-backend/fai_backend/auth/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
from datetime import timedelta
from typing import Annotated

from fastapi import HTTPException, Header
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi_jwt import JwtAccessBearerCookie, JwtRefreshBearerCookie
from passlib.context import CryptContext

Expand Down Expand Up @@ -74,32 +75,29 @@ def pattern_to_regex(p: str) -> str:
return False


def is_auth_disabled() -> bool:
return settings.ENV_MODE != 'production' and settings.DISABLE_AUTH
def is_authenticate_disabled() -> bool:
return settings.DISABLE_API_AUTHENTICATION


def read_public_key(file: str) -> str:
with open(file, 'r') as f:
return f.read()
def get_public_key() -> str:
return settings.PUBLIC_KEY


def validate_key(key: str, public_key: str) -> bool:
def validate_token_adapter(token: str, public_key: str, algorithm: str) -> bool:
try:
jwt.decode(key, public_key, algorithms=['RS256'])
jwt.decode(jwt=token, key=public_key, algorithms=[algorithm])
return True
except Exception as e:
logging.debug(msg=str(e), exc_info=True)
logging.info(e)
return False


def authenticate(x_api_key: Annotated[str, Header()] = None) -> None:
try:
if is_auth_disabled():
return
if not validate_key(x_api_key, read_public_key(settings.PUBLIC_KEY_FILE)):
raise HTTPException(status_code=401, detail='Unauthorized')
except Exception as e:
raise e
def authenticate(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(HTTPBearer())] = None) -> None:
if is_authenticate_disabled():
return None

if not validate_token_adapter(credentials.credentials, get_public_key(), settings.JWT_DECODE_ALGORITHM):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)


generate_pin_code = create_pin_factory_from_env()
5 changes: 3 additions & 2 deletions fai-rag-app/fai-backend/fai_backend/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ class Settings(BaseSettings, extra=Extra.ignore):
BREVO_API_URL: str = 'https://api.brevo.com/v3/smtp/email'
BREVO_API_KEY: SecretStr = 'api-key'
ALGORITHM: str = 'HS256'
JWT_DECODE_ALGORITHM: str = 'RS256'
DISABLE_API_AUTHENTICATION: bool = False
PUBLIC_KEY: str
ENV_MODE: Literal['testing', 'development', 'production'] = 'production'
DISABLE_AUTH: bool = True
PUBLIC_KEY_FILE: str | None = 'api-key.pub'
MONGO_DB_NAME: str = 'fai-rag-app'
MONGO_DB_URI: str = 'mongodb://localhost:27017'
FIXED_PIN: int | None = None
Expand Down

0 comments on commit 5d87aea

Please sign in to comment.