summaryrefslogtreecommitdiffstats
path: root/authentication/backend.py
diff options
context:
space:
mode:
Diffstat (limited to 'authentication/backend.py')
-rw-r--r--authentication/backend.py48
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 @@
1from datetime import datetime, UTC
2from typing import Optional
3
4from sqlalchemy import update
5from sqlmodel import select
6from starlette.authentication import AuthenticationBackend, AuthCredentials, BaseUser, UnauthenticatedUser
7from starlette.requests import HTTPConnection
8
9from db.models import Session, User
10from db.session import get_session_context
11
12
13class 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 )