2023-09-24 15:54:35 -06:00
|
|
|
from functools import wraps
|
|
|
|
|
|
|
|
import basicauth
|
|
|
|
from flask import Response, request
|
|
|
|
|
2024-05-07 12:20:53 -06:00
|
|
|
from llm_server.config.global_config import GlobalConfig
|
2023-09-24 15:54:35 -06:00
|
|
|
|
|
|
|
|
2023-09-26 22:09:11 -06:00
|
|
|
def parse_token(input_token):
|
2023-09-24 15:54:35 -06:00
|
|
|
password = None
|
2023-09-26 22:09:11 -06:00
|
|
|
if input_token.startswith('Basic '):
|
2023-09-24 15:54:35 -06:00
|
|
|
try:
|
2023-09-26 22:09:11 -06:00
|
|
|
_, password = basicauth.decode(input_token)
|
2023-09-24 15:54:35 -06:00
|
|
|
except:
|
|
|
|
return False
|
2023-09-26 22:09:11 -06:00
|
|
|
elif input_token.startswith('Bearer '):
|
|
|
|
password = input_token.split('Bearer ', maxsplit=1)
|
2023-09-24 15:54:35 -06:00
|
|
|
del password[0]
|
|
|
|
password = ''.join(password)
|
2023-09-26 22:09:11 -06:00
|
|
|
return password
|
|
|
|
|
|
|
|
|
|
|
|
def check_auth(token):
|
2024-05-07 12:20:53 -06:00
|
|
|
if not GlobalConfig.get().admin_token:
|
2023-09-26 22:09:11 -06:00
|
|
|
# The admin token is not set/enabled.
|
|
|
|
# Default: deny all.
|
|
|
|
return False
|
2024-05-07 12:20:53 -06:00
|
|
|
return parse_token(token) == GlobalConfig.get().admin_token
|
2023-09-24 15:54:35 -06:00
|
|
|
|
|
|
|
|
|
|
|
def authenticate():
|
|
|
|
"""Sends a 401 response that enables basic auth"""
|
|
|
|
return Response(
|
|
|
|
'AUTHENTICATION REQUIRED', 401,
|
|
|
|
{'WWW-Authenticate': 'Basic realm="Login Required"'})
|
|
|
|
|
|
|
|
|
|
|
|
def requires_auth(f):
|
|
|
|
@wraps(f)
|
|
|
|
def decorated(*args, **kwargs):
|
|
|
|
auth = request.headers.get('Authorization')
|
|
|
|
if not auth or not check_auth(auth):
|
|
|
|
return authenticate()
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
|
|
|
|
return decorated
|