초기 커밋
This commit is contained in:
56
app/admin/setup.py
Normal file
56
app/admin/setup.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI
|
||||
from sqladmin import Admin
|
||||
from sqladmin.authentication import AuthenticationBackend
|
||||
from starlette.requests import Request
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.constants import Role
|
||||
from app.core.security import decode_token
|
||||
from app.db.mariadb import async_engine
|
||||
|
||||
|
||||
class AdminAuth(AuthenticationBackend):
|
||||
async def login(self, request: Request) -> bool:
|
||||
form = await request.form()
|
||||
token = str(form.get("token", ""))
|
||||
payload = decode_token(token)
|
||||
if payload and payload.get("role") in Role.ADMIN_ROLES:
|
||||
request.session["token"] = token
|
||||
return True
|
||||
return False
|
||||
|
||||
async def logout(self, request: Request) -> bool:
|
||||
request.session.clear()
|
||||
return True
|
||||
|
||||
async def authenticate(self, request: Request) -> bool:
|
||||
token = request.session.get("token")
|
||||
if not token:
|
||||
return False
|
||||
payload = decode_token(token)
|
||||
return payload is not None and payload.get("role") in Role.ADMIN_ROLES
|
||||
|
||||
|
||||
def setup_admin(app: FastAPI) -> Admin:
|
||||
auth_backend = AdminAuth(secret_key=settings.SECRET_KEY)
|
||||
admin = Admin(
|
||||
app,
|
||||
engine=async_engine,
|
||||
authentication_backend=auth_backend,
|
||||
title=f"{settings.APP_NAME} Admin",
|
||||
)
|
||||
|
||||
from app.admin.views.device_admin import DeviceAdmin, DeviceGroupAdmin
|
||||
from app.admin.views.system_admin import AuditLogAdmin, SystemConfigAdmin
|
||||
from app.admin.views.user_admin import UserAdmin, UserProfileAdmin
|
||||
|
||||
admin.add_view(UserAdmin)
|
||||
admin.add_view(UserProfileAdmin)
|
||||
admin.add_view(DeviceAdmin)
|
||||
admin.add_view(DeviceGroupAdmin)
|
||||
admin.add_view(SystemConfigAdmin)
|
||||
admin.add_view(AuditLogAdmin)
|
||||
|
||||
return admin
|
||||
Reference in New Issue
Block a user