This repository has been archived by the owner on Mar 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
101 lines (77 loc) · 2.73 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# YTCTF Platform
# Copyright © 2018-2019 Evgeniy Filimonov <[email protected]>
# See full NOTICE at http://github.com/YummyTacos/YTCTF
from datetime import datetime
from pathlib import Path
from pprint import pprint
from traceback import format_exception
from hashlib import sha1
from re import compile as re_compile
from flask import g, redirect, url_for, request, flash, current_app as app
from functools import wraps
from enum import Enum, unique
from models import User, Event as EventModel
_safe_url_re = re_compile(r'^/[^/].*')
@unique
class Event(Enum):
NEW_TASK = 1
TASK_SOLVED = 2
TASK_FAILED = 3
FIRST_BLOOD = 4
def trigger(self, **kwargs):
return EventModel(time=datetime.utcnow(), type=self.value, **kwargs)
def save_exception(exc):
fe = format_exception(exc.__class__, exc, exc.__traceback__)
e = ''.join(fe)
h = sha1(e.encode()).hexdigest()
p = (Path(app.static_folder) / 'files/exc/').resolve()
p.mkdir(parents=True, exist_ok=True)
with (p / f'e{h}.txt').open('w') as f:
f.write(f'Last occurred at {datetime.utcnow()} UTC\n\n')
f.write(e)
f.write('\nuser.id: {}\n'.format(getattr(g, 'user') and g.user.id))
f.write(f'\nrequest.user_agent: {request.user_agent.string}\n')
f.write(f'\nrequest.url: {request.url}\n')
f.write('\nrequest:\n')
pprint(get_dir_dict(request, key=lambda x: not x.startswith('__')), stream=f, width=100)
return h
def find_user(name):
return User.query.filter_by(username=name).one_or_none()
def safe_next(url, fallback=None):
if url is not None and _safe_url_re.fullmatch(url) is not None:
return url
return fallback or url_for('main')
def login_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.path))
return f(*args, **kwargs)
return wrapper
def admin_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.path))
if not g.user.is_admin:
flash('Нет доступа!', 'danger')
return redirect(url_for('main'))
return f(*args, **kwargs)
return wrapper
def get_ending(word, n, one, two, five):
if n % 10 == 1 and n % 100 != 11:
return word + one
if 2 <= n % 10 < 5 and n % 100 // 10 != 1:
return word + two
return word + five
def get_plural(n, one, two, five):
return f'{n} {get_ending("", n, one, two, five)}'
def get_dir_dict(obj, *, key=None):
if key is None:
key = (lambda x: True)
d = {}
for _m in dir(obj):
if not key(_m):
continue
d[_m] = getattr(obj, _m)
return d