2023-10-17 23:06:27 +01:00
|
|
|
from time import time
|
|
|
|
|
|
|
|
import jwt
|
|
|
|
|
2023-10-21 17:17:09 +01:00
|
|
|
from cista.config import derived_secret
|
2023-10-17 23:06:27 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
|
|
|
def session_secret():
|
|
|
|
return derived_secret("session")
|
|
|
|
|
|
|
|
|
2023-10-24 00:03:11 +01:00
|
|
|
max_age = 365 * 86400 # Seconds since last login
|
2023-10-17 23:06:27 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-17 23:06:27 +01:00
|
|
|
def get(request):
|
|
|
|
try:
|
2023-10-19 00:06:14 +01:00
|
|
|
return jwt.decode(request.cookies.s, session_secret(), algorithms=["HS256"])
|
2023-10-26 15:18:59 +01:00
|
|
|
except Exception:
|
2023-10-17 23:06:27 +01:00
|
|
|
return False if "s" in request.cookies else None
|
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-17 23:06:27 +01:00
|
|
|
def create(res, username, **kwargs):
|
|
|
|
data = {
|
|
|
|
"exp": int(time()) + max_age,
|
|
|
|
"username": username,
|
|
|
|
**kwargs,
|
|
|
|
}
|
2023-10-19 00:06:14 +01:00
|
|
|
s = jwt.encode(data, session_secret())
|
2023-10-19 17:55:59 +01:00
|
|
|
res.cookies.add_cookie("s", s, httponly=True, max_age=max_age)
|
2023-10-17 23:06:27 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-17 23:06:27 +01:00
|
|
|
def update(res, s, **kwargs):
|
|
|
|
s.update(kwargs)
|
2023-10-19 00:06:14 +01:00
|
|
|
s = jwt.encode(s, session_secret())
|
2023-10-23 02:51:39 +01:00
|
|
|
max_age = max(1, s["exp"] - int(time())) # type: ignore
|
|
|
|
res.cookies.add_cookie("s", s, httponly=True, max_age=max_age)
|
2023-10-17 23:06:27 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-17 23:06:27 +01:00
|
|
|
def delete(res):
|
2023-10-19 17:55:59 +01:00
|
|
|
res.cookies.delete_cookie("s")
|
2023-10-21 02:44:43 +01:00
|
|
|
|
|
|
|
|
|
|
|
def flash(res, message: str | None):
|
|
|
|
if message is None:
|
|
|
|
res.cookies.delete_cookie("message")
|
|
|
|
else:
|
|
|
|
res.cookies.add_cookie("message", message, max_age=5)
|