diff options
| author | 2026-07-03 15:49:08 +0200 | |
|---|---|---|
| committer | 2026-07-03 15:49:14 +0200 | |
| commit | 7784c60c03ec277b456db6e2709383e302d9382b (patch) | |
| tree | a008def666f04041fe77740693d42cfef89af558 /authentication/backend.py | |
| parent | fb28c648390464c75ba4903b0e1e0ff2642c8ffb (diff) | |
| download | server-7784c60c03ec277b456db6e2709383e302d9382b.tar.gz server-7784c60c03ec277b456db6e2709383e302d9382b.tar.bz2 server-7784c60c03ec277b456db6e2709383e302d9382b.zip | |
Added basic oauth flow
Diffstat (limited to 'authentication/backend.py')
| -rw-r--r-- | authentication/backend.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/authentication/backend.py b/authentication/backend.py new file mode 100644 index 0000000..29408e3 --- /dev/null +++ b/authentication/backend.py | |||
| @@ -0,0 +1,48 @@ | |||
| 1 | from datetime import datetime, UTC | ||
| 2 | from typing import Optional | ||
| 3 | |||
| 4 | from sqlalchemy import update | ||
| 5 | from sqlmodel import select | ||
| 6 | from starlette.authentication import AuthenticationBackend, AuthCredentials, BaseUser, UnauthenticatedUser | ||
| 7 | from starlette.requests import HTTPConnection | ||
| 8 | |||
| 9 | from db.models import Session, User | ||
| 10 | from db.session import get_session_context | ||
| 11 | |||
| 12 | |||
| 13 | class AuthBackend(AuthenticationBackend): | ||
| 14 | async def authenticate(self, request: HTTPConnection) -> Optional[tuple[AuthCredentials, BaseUser]]: | ||
| 15 | if "id" not in request.session: | ||
| 16 | return None | ||
| 17 | |||
| 18 | query = ( | ||
| 19 | select(Session) | ||
| 20 | .join(User) | ||
| 21 | .where( | ||
| 22 | Session.id == request.session['id'] | ||
| 23 | ) | ||
| 24 | ) | ||
| 25 | |||
| 26 | |||
| 27 | with get_session_context() as db_session: | ||
| 28 | session: Session = db_session.exec(query).first() | ||
| 29 | |||
| 30 | if session is not None: | ||
| 31 | db_session.execute( | ||
| 32 | update(Session).where(Session.id == session.id) | ||
| 33 | ) | ||
| 34 | db_session.commit() | ||
| 35 | |||
| 36 | return ( | ||
| 37 | AuthCredentials( | ||
| 38 | [ | ||
| 39 | "authenticated", | ||
| 40 | *[ | ||
| 41 | connection.type for connection in session.user.app_connections | ||
| 42 | ] | ||
| 43 | ] | ||
| 44 | if session is not None | ||
| 45 | else [] | ||
| 46 | ), | ||
| 47 | session.user if session is not None else UnauthenticatedUser() | ||
| 48 | ) | ||
