-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
70 lines (52 loc) · 1.99 KB
/
utils.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
69
70
from typing import Callable, Any, Union
from sanic import Request, response
from db.player import Player
from db.types import Permission
from shared import app
def get_post(request: Request) -> dict:
"""
DEPRECATED
"""
data = request.form
for key in data:
data[key] = data[key]
return data
# listen before request
@app.middleware("request")
async def add_session_to_request(request: Request) -> None:
if request.headers.get("Cookie") is not None:
# check login with cookie
player = await Player.filter(codename=request.cookies.get("codename")).first()
if player is not None and player.check_password(request.cookies.get("password")):
request.ctx.session.update({
"codename": player.codename,
"player_id": player.player_id,
"permissions": player.permissions
})
async def render_template(r, template, *args, **kwargs) -> str:
additional_kwargs = {
"session": r.ctx.session,
"config": r.app.ctx.config,
"Permission": Permission,
"str": str,
}
kwargs = {**kwargs, **additional_kwargs}
text = await app.ctx.jinja.render_async(template, r, *args, **kwargs)
return text
async def render_cached_template(r, template, *args, **kwargs) -> str:
return r, template, args, kwargs
def admin_only(f) -> Callable:
async def wrapper(request: Request, *args, **kwargs) -> Union[response.HTTPResponse, Any]:
if not request.ctx.session.get("permissions", 0) == Permission.ADMIN:
request.ctx.session["previous_page"] = request.path
return response.redirect("/login")
return await f(request, *args, **kwargs)
return wrapper
def is_admin(request: Request) -> bool:
return request.ctx.session.get("permissions", 0) == Permission.ADMIN
def banner_type_to_color(type: str) -> str:
return {
"info": "#4da6ff",
"warning": "#cfa602",
"danger": "#ff4d4d",
}.get(type, "#4da6ff")