-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.py
303 lines (254 loc) · 10.8 KB
/
app.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import falcon
import json
import os
import shutil
import subprocess
import sys
import traceback
from datetime import datetime, timedelta
from sqlalchemy import func, desc
from sqlalchemy.exc import SQLAlchemyError
import model
import endpoint
import util
from db import engine, session
from util import UserInfo
# Cache of the current year.
c_year = None
c_year_update = None
class JSONTranslator(object):
def process_request(self, req, resp):
return
def process_response(self, req, resp, *_):
if 'result' not in req.context:
return
resp.body = json.dumps(
req.context['result'],
sort_keys=True,
indent=4,
ensure_ascii=False,
)
class Authorizer(object):
def process_request(self, req, resp):
if req.auth:
token_str = req.auth.split(' ')[-1]
try:
token = session.query(model.Token).get(token_str)
if token is not None:
if (req.relative_uri != '/auth' and
token.expire < datetime.utcnow()):
# user timeouted
req.context['user'] = UserInfo()
return
try:
req.context['user'] = UserInfo(
session.query(model.User).get(token.user),
token_str
)
return
except AttributeError:
pass
except:
session.rollback()
req.context['user'] = UserInfo()
class SourceAddressFill:
def process_request(self, req, resp):
try:
ip = req.env['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()
except KeyError:
ip = req.env['REMOTE_ADDR']
req.context['source_ip'] = ip
class Year_fill(object):
# This middleware has 2 purposes:
# 1) Get current year.
# 2) Test connection with db. (this is very important!)
def process_request(self, req, resp):
if req.method == 'OPTIONS':
return
try:
if ('YEAR' in req.headers):
req.context['year'] = req.headers['YEAR']
req.context['year_obj'] = session.query(model.Year).\
get(req.context['year'])
else:
year_obj = session.query(model.Year).\
order_by(desc(model.Year.id)).first()
req.context['year_obj'] = year_obj
req.context['year'] = year_obj.id
except SQLAlchemyError:
session.rollback()
try:
if ('YEAR' in req.headers):
req.context['year'] = req.headers['YEAR']
req.context['year_obj'] = session.query(model.Year).\
get(req.context['year'])
else:
year_obj = session.query(model.Year).\
order_by(desc(model.Year.id)).first()
req.context['year_obj'] = year_obj
req.context['year'] = year_obj.id
except:
session.rollback()
raise
class AddCORS:
def process_request(self, req, resp):
return
def process_response(self, req, resp, *_):
cors = util.config.access_control_allow_origin()
if cors:
resp.set_header('Access-Control-Allow-Origin', cors)
def log(req, resp):
user = req.context.get("user")
user_id = user.id if user else '_'
ip = req.context['source_ip']
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] '
f'[INFO] [HTTP] '
f'[{ip}] '
f'[{req.method}] '
f'[{resp.status.split()[0]}] '
f'[{user_id}] '
f'{req.relative_uri}')
sys.stdout.flush()
class Logger(object):
def process_request(self, req, resp):
pass
def process_response(self, req, resp, *_):
log(req, resp)
class RemoveTrailingSlashMiddleware:
def process_request(self, req, resp):
if req.path != '/' and req.path.endswith('/'):
raise falcon.HTTPMovedPermanently(req.path.rstrip('/'))
def log_sink(req, resp):
resp.status = falcon.HTTP_404
# Uncomment this to log sink
log(req, resp)
class Corser(object):
def process_response(self, request, response, *_):
response.set_header('Access-Control-Allow-Headers',
'authorization,content-type,year')
response.set_header('Access-Control-Allow-Methods',
'OPTIONS,PUT,POST,GET,DELETE')
def error_handler(ex, req, resp, params):
if isinstance(ex, falcon.HTTPError):
req.context['result'] = {
'errors': [ {
'status': ex.status,
'title': ex.title,
'detail': ex.description,
} ]
}
resp.status = ex.status
else:
req.context['result'] = {
'errors': [ {
'status': '500',
'title': 'Internal server error',
'detail': 'Vnitřní chyba serveru, kontaktujte správce backendu.',
} ]
}
resp.status = falcon.HTTP_500
log(req, resp)
if resp.status == falcon.HTTP_500:
dt = datetime.now().strftime('[%Y-%m-%d %H:%M:%S]')
lines = '\n'.join(
[dt + ' ' + line for line in traceback.format_exc().split('\n')]
)
print(lines)
# Add Logger() to middleware for logging
api = falcon.API(middleware=[SourceAddressFill(), RemoveTrailingSlashMiddleware(), JSONTranslator(), Authorizer(), Year_fill(),
Corser(), AddCORS(), Logger()])
api.add_error_handler(Exception, handler=error_handler)
api.req_options.auto_parse_form_urlencoded = True
# Odkomentovat pro vytvoreni tabulek v databazi
# model.Base.metadata.create_all(engine)
# Create /tmp/box with proper permissions (for sandbox)
if os.path.isdir(util.programming.EXEC_PATH):
shutil.rmtree(util.programming.EXEC_PATH, ignore_errors=True)
try:
os.makedirs(util.programming.EXEC_PATH)
except FileExistsError:
pass
p = subprocess.Popen(["setfacl", "-d", "-m", "group:ksi:rwx",
util.programming.EXEC_PATH])
p.wait()
if p.returncode != 0:
raise Exception("Cannot change umask to %s!" %
(util.programming.EXEC_PATH))
api.add_route('/robots.txt', endpoint.Robots())
api.add_route('/csp', endpoint.CSP())
api.add_route('/articles', endpoint.Articles())
api.add_route('/articles/{id}', endpoint.Article())
api.add_route('/achievements', endpoint.Achievements())
api.add_route('/achievements/{id}', endpoint.Achievement())
api.add_route('/achievements/special/successful', endpoint.AchievementSuccessfulParticipant())
api.add_route('/posts', endpoint.Posts())
api.add_route('/posts/{id}', endpoint.Post())
api.add_route('/tasks', endpoint.Tasks())
api.add_route('/tasks/{id}', endpoint.Task())
api.add_route('/taskDetails/{id}', endpoint.TaskDetails())
api.add_route('/modules/{id}', endpoint.Module())
api.add_route('/modules/{id}/submit', endpoint.ModuleSubmit())
api.add_route('/modules/{id}/submitFiles', endpoint.ModuleSubmit()) # alias required for swagger
api.add_route('/submFiles/{id}', endpoint.ModuleSubmittedFile())
api.add_route('/threads', endpoint.Threads())
api.add_route('/threads/{id}', endpoint.Thread())
api.add_route('/threadDetails/{id}', endpoint.ThreadDetails())
api.add_route('/users', endpoint.Users())
api.add_route('/users/{id}', endpoint.User())
api.add_route('/users/{id}/discord', endpoint.DiscordInviteLink())
api.add_route('/users/discord/validate', endpoint.DiscordBotValidateUser())
api.add_route('/profile/picture', endpoint.PictureUploader())
api.add_route('/profile/{id}', endpoint.OrgProfile())
api.add_route('/profile', endpoint.Profile())
api.add_route('/basicProfile', endpoint.BasicProfile())
api.add_route('/images/{context}/{id}', endpoint.Image())
api.add_route('/content', endpoint.Content())
api.add_route('/taskContent/{id}', endpoint.TaskContent())
api.add_route('/task-content/{id}/{view}', endpoint.TaskContent())
api.add_route('/registration', endpoint.Registration())
api.add_route('/auth', endpoint.Authorize())
api.add_route('/logout', endpoint.Logout())
api.add_route('/runCode/{id}/submit', endpoint.RunCode())
api.add_route('/feedback', endpoint.FeedbackEmail())
api.add_route('/settings/changePassword', endpoint.ChangePassword())
api.add_route('/forgottenPassword', endpoint.ForgottenPassword())
api.add_route('/waves', endpoint.Waves())
api.add_route('/waves/{id}', endpoint.Wave())
api.add_route('/years', endpoint.Years())
api.add_route('/years/{id}', endpoint.Year())
api.add_route('/feedbacks', endpoint.FeedbacksTask())
api.add_route('/feedbacks/{id}', endpoint.FeedbackTask())
api.add_route('/diplomas/{user}', endpoint.Diploma())
api.add_route('/diplomas/{user}/{year}/show', endpoint.DiplomaDownload())
"""
task-content endpoint contains: (defined in endpoint/content.py, see also
./gunicorn_cfg.py.example)
* /taskContent/{id}/zadani/{file_path}
* /taskContent/{id}/reseni/{file_path}
* /taskContent/[id]/icon/{file_name}
"""
api.add_route('/admin/evaluations/{id}', endpoint.admin.Evaluation())
api.add_route('/admin/corrections', endpoint.admin.Corrections())
api.add_route('/admin/corrections/{id}', endpoint.admin.Correction())
api.add_route('/admin/correctionsInfos', endpoint.admin.CorrectionsInfo())
api.add_route('/admin/correctionsInfos/{id}', endpoint.admin.CorrectionInfo())
api.add_route('/admin/correctionsEmail/{id}', endpoint.admin.CorrectionsEmail())
api.add_route('/admin/corrections/{id}/publish', endpoint.admin.CorrectionsPublish())
api.add_route('/admin/subm/eval/{eval_id}', endpoint.admin.SubmFilesEval())
api.add_route('/admin/subm/task/{task_id}', endpoint.admin.SubmFilesTask())
api.add_route('/admin/e-mail', endpoint.admin.Email())
api.add_route('/admin/atasks', endpoint.admin.Tasks())
api.add_route('/admin/atasks/{id}', endpoint.admin.Task())
api.add_route('/admin/atasks/{id}/deploy', endpoint.admin.TaskDeploy())
api.add_route('/admin/atasks/{id}/merge', endpoint.admin.TaskMerge())
api.add_route('/admin/waves/{id}/diff', endpoint.admin.WaveDiff())
api.add_route('/admin/achievements/grant', endpoint.admin.AchievementGrant())
api.add_route('/admin/user-export', endpoint.admin.UserExport())
api.add_route('/admin/evalCodes/{id}', endpoint.admin.EvalCode())
api.add_route('/admin/execs', endpoint.admin.Execs())
api.add_route('/admin/execs/{id}', endpoint.admin.Exec())
api.add_route('/admin/monitoring-dashboard', endpoint.admin.MonitoringDashboard())
api.add_route('/admin/diploma/{id}/grant', endpoint.admin.DiplomaGrant())
api.add_route('/admin/instanceConfig', endpoint.admin.InstanceConfig())
api.add_route('/unsubscribe/{id}', endpoint.Unsubscribe())
api.add_sink(log_sink)