import os from crypt import crypt from functools import lru_cache from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials from . import config security = HTTPBasic() @lru_cache() def get_settings(): return config.Settings def validate(username: str, password: str, settings: config.Settings): here = os.path.abspath(os.path.dirname(__file__)) file = os.path.join(here, '../', settings.htpasswd) if not os.path.isfile(file): return None users = {} with open(file, "r") as f: for line in f: login, pwd = line.split(":") users[login] = pwd.rstrip("\n") if username in users: return crypt(password, users[username]) == users[username] else: return False def get_current_username( credentials: HTTPBasicCredentials = Depends(security), settings: config.Settings = Depends(get_settings), ): if not validate(credentials.username, credentials.password, settings): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username