Browse Source

Add logout

pull/3/head
Kenneth Bruen 3 years ago
parent
commit
b390bfc5c4
Signed by: kbruen
GPG Key ID: C1980A470C3EE5B1
  1. 12
      server/decorators.py
  2. 9
      server/login.py
  3. 6
      server/ram_db.py

12
server/decorators.py

@ -0,0 +1,12 @@
from http import HTTPStatus
from functools import wraps
def no_content(fn):
@wraps(fn)
def wrapper(*args, **kargs):
result = fn(*args, **kargs)
if result is None:
return None, HTTPStatus.NO_CONTENT
else:
return result
return wrapper

9
server/login.py

@ -4,6 +4,7 @@ from flask import Blueprint, request
from pyotp import TOTP from pyotp import TOTP
import db_utils import db_utils
from decorators import no_content
import models import models
import ram_db import ram_db
import returns import returns
@ -41,9 +42,15 @@ def ensure_logged_in(fn):
user_id = ram_db.get_user(token) user_id = ram_db.get_user(token)
if user_id is None: if user_id is None:
return returns.INVALID_AUTHORIZATION return returns.INVALID_AUTHORIZATION
return fn(user_id=user_id, *args, **kargs) return fn(user_id=user_id, token=token, *args, **kargs)
return wrapper return wrapper
@login.post('/logout')
@ensure_logged_in
@no_content
def logout(token: str):
ram_db.logout_user(token)
@login.get('/whoami') @login.get('/whoami')
@ensure_logged_in @ensure_logged_in
def whoami(user_id): def whoami(user_id):

6
server/ram_db.py

@ -14,10 +14,16 @@ def login_user(user_id: int) -> str:
token = str(uuid4()) token = str(uuid4())
if len(USED_TOKENS) > 10_000_000: if len(USED_TOKENS) > 10_000_000:
USED_TOKENS.clear() USED_TOKENS.clear()
for token in LOGGED_IN_USERS:
USED_TOKENS.add(token)
USED_TOKENS.add(token) USED_TOKENS.add(token)
LOGGED_IN_USERS[token] = user_id, datetime.now() LOGGED_IN_USERS[token] = user_id, datetime.now()
return token return token
def logout_user(token: str):
if token in LOGGED_IN_USERS:
del LOGGED_IN_USERS[token]
def get_user(token: str) -> int | None: def get_user(token: str) -> int | None:
if token not in LOGGED_IN_USERS: if token not in LOGGED_IN_USERS:
return None return None

Loading…
Cancel
Save