45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
import os
|
|
from crypt import crypt
|
|
from functools import lru_cache
|
|
|
|
import pkg_resources
|
|
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):
|
|
file = pkg_resources.resource_filename("bifrost", "../" + 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
|