This repository has been archived by the owner on Jul 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorators.py
68 lines (51 loc) · 1.81 KB
/
decorators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from typing import Callable
from objects import glob
from constants.privileges import Privileges
from objects.responses import ajson
from starlette.requests import Request
from starlette.responses import RedirectResponse
from functools import wraps
# this is the decorator used
# to insert all endpoints
# into glob.route_map where
# we then add it to starlette's routes
def web(url: str, methods: list = ["GET"]) -> Callable:
def callback(cb: Callable) -> Callable:
glob.route_map.append({
"cb": cb,
"url": url,
"methods": methods
})
return callback
def login_test(cb: Callable):
def decorator(f):
@wraps(f)
async def wrapper(req: Request, *args, **kwargs):
if not req["session"]:
return RedirectResponse("/login")
return await cb(req, *args, **kwargs)
return wrapper
return decorator
def login_required(cb: Callable) -> Callable:
check = login_test(cb)
if check:
return check(cb)
return check
def required_params(params: list[str]):
def decorator(cb: Callable):
@wraps(cb)
async def wrapper(req: Request, *args, **kwargs):
if not all(x in req.query_params for x in params):
return ajson({"error": "missing params"})
return await cb(req, *args, **kwargs)
return wrapper
return decorator
def required_priv(priv = Privileges.ACCESS):
def decorator(cb: Callable):
@wraps(cb)
async def wrapper(req: Request, *args, **kwargs):
if not req.session["priv"] & priv:
return RedirectResponse("/no_perms")
return await cb(req, *args, **kwargs)
return wrapper
return decorator