chat_back/chat_test/app/admin/auth.py

40 lines
1.3 KiB
Python

from sqladmin.authentication import AuthenticationBackend
from starlette.requests import Request
from app.config import settings
from app.users.auth import authenticate_user_by_username, create_access_token, validate_user_admin
from app.users.dependencies import get_current_user
ADMIN_ROLE = 100
class AdminAuth(AuthenticationBackend):
async def login(self, request: Request) -> bool:
form = await request.form()
username, password = form["username"], form["password"]
user = await authenticate_user_by_username(username, password)
if user and user.role == ADMIN_ROLE:
access_token = create_access_token({"sub": str(user.id)})
request.session.update({"token": access_token})
return True
async def logout(self, request: Request) -> bool:
# Usually you'd want to just clear the session
request.session.clear()
return True
async def authenticate(self, request: Request) -> bool:
token = request.session.get("token")
if not token:
return False
user = await get_current_user(token)
if user:
return await validate_user_admin(user.id)
return False
authentication_backend = AdminAuth(secret_key=settings.SECRET_KEY)