-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.py
More file actions
51 lines (43 loc) · 1.59 KB
/
auth.py
File metadata and controls
51 lines (43 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from auth_lib.methods import AuthLib
from fastapi import Request
from sqladmin.authentication import AuthenticationBackend
from auth_backend.settings import get_settings
from typing import Any
settings = get_settings()
class AdminAuth(AuthenticationBackend):
async def login(self, request: Request) -> bool:
form = await request.form()
username = form.get("username")
token = form.get("password")
if username != settings.ADMIN_LOGIN:
return False
valid = await self._is_valid_token(token)
if valid is None:
return False
request.session["token"] = token
request.session["user_id"] = valid.get("id")
return True
async def authenticate(self, request: Request) -> bool:
token = request.session.get("token")
if not token:
return False
userdata = await self._is_valid_token(token)
return userdata is not None
async def logout(self, request: Request) -> bool:
request.session.clear()
return True
@staticmethod
async def _is_valid_token(token: str) -> dict[str, Any] | None:
try:
result = AuthLib(auth_url=settings.AUTH_URL).check_token(token)
if not result:
return None
session_scopes = {
scope["name"].lower() for scope in result.get("session_scopes", [])
}
required_scopes = "auth.sqladmin.admin"
if required_scopes not in session_scopes:
return None
return result
except Exception:
return None