Skip to content

Commit 0b5ef20

Browse files
committed
auth logic
1 parent a047999 commit 0b5ef20

3 files changed

Lines changed: 34 additions & 9 deletions

File tree

auth_backend/admin/auth.py

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,48 @@
22
from sqladmin.authentication import AuthenticationBackend
33

44
from auth_backend.settings import get_settings
5-
5+
from auth_backend.utils.security import UnionAuth
6+
from auth_lib.methods import AuthLib
67

78
settings = get_settings()
89

9-
1010
class AdminAuth(AuthenticationBackend):
11+
1112
async def login(self, request: Request) -> bool:
1213
form = await request.form()
1314
username = form.get("username")
14-
password = form.get("password")
15-
if username == settings.ADMIN_LOGIN and password == settings.ADMIN_PASSWORD:
16-
request.session["user"] = username
15+
token = form.get("password")
16+
if username != settings.ADMIN_LOGIN:
17+
return False
18+
valid = await self._is_valid_token(token)
19+
if valid:
20+
request.session["token"] = token
1721
return True
18-
return False
22+
else:
23+
return False
24+
25+
async def authenticate(self, request: Request) -> bool:
26+
token = request.session.get("token")
27+
if not token:
28+
return False
29+
return await self._is_valid_token(token)
1930

2031
async def logout(self, request: Request) -> bool:
2132
request.session.clear()
2233
return True
2334

24-
async def authenticate(self, request: Request) -> bool:
25-
user = request.session.get("user")
26-
return user is not None
35+
@staticmethod
36+
async def _is_valid_token(token: str) -> bool:
37+
try:
38+
result = AuthLib(auth_url=settings.AUTH_URL).check_token(token)
39+
if not result:
40+
return False
41+
session_scopes = {
42+
scope["name"].lower() for scope in result.get("session_scopes", [])
43+
}
44+
required_scopes = "auth.sqladmin.admin"
45+
if required_scopes not in session_scopes:
46+
return False
47+
return True
48+
except Exception:
49+
return False

auth_backend/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class Settings(BaseSettings):
2323
ADMIN_SECRET_KEY: str = "default"
2424
ADMIN_LOGIN: str = "admin"
2525
ADMIN_PASSWORD: str = "admin"
26+
AUTH_URL: str = "https://api.test.profcomff.com/auth/"
2627

2728
ROOT_PATH: str = '/' + os.getenv('APP_NAME', '')
2829

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ event-schema-profcomff
1717
aiocache
1818
python-multipart
1919
sqladmin[full]
20+
auth-lib-profcomff[fastapi]
2021

2122
# Google Auth Method
2223
google-api-python-client

0 commit comments

Comments
 (0)