-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask_app.py
271 lines (230 loc) · 9.63 KB
/
flask_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
from database import *
from flask import abort
from werkzeug.security import generate_password_hash, check_password_hash
import datetime
# from telegram_ import get_valid, send_code
from rest import *
# Main page
@app.route('/')
@app.route('/index')
def main():
if 'user_id' not in session:
return redirect('/not_logged')
return render_template('main.html', problems=Problem.query.filter(Problem.author_id == session['user_id'], ).all())
@app.route('/delegated')
def delegated():
if 'user_id' not in session:
return redirect('/not_logged')
problems = Problem.query.filter(Problem.solver_id == session['user_id']).all()
return render_template('delegated.html', problems=problems)
# User logout
@app.route('/logout')
def logout():
session.pop('username', 0)
session.pop('user_id', 0)
session.pop('admin', 0)
return redirect('/')
@app.route('/not_logged')
def unlog():
return render_template('unlogged.html')
# User login
@app.route('/login', methods=['GET', 'POST'])
def login():
if 'user_id' in session:
return redirect('/')
if request.method == "GET":
return render_template('login.html', title=': Вход', fixed_footer=True)
elif request.method == "POST":
login = request.form["login"]
password = request.form["u_password"]
correct = User.query.filter(User.login == login).first()
if correct is None:
correct1 = User.query.filter(User.email == login).first()
if not correct1 is None:
correct = correct1
if correct is None:
error = 'Такого пользователя нет в системе'
elif not (login and password):
error = "Одно из полей не заполнено"
elif not check_password_hash(correct.password, password):
error = "Неправильный пароль"
else:
tids = TID.query.filter_by(login=login).all()
if tids:
for i in tids:
send_code(i)
session['tid'] = tids[0].tid
return redirect('/oauth')
session['username'] = correct.login
session['user_id'] = correct.id
session['admin'] = correct.admin
return redirect('/')
return render_template('login.html', title=': Вход', fixed_footer=True, error=error)
@app.route('/oauth', methods=['GET', 'POST'])
def oauth():
if 'user_id' in session:
return redirect('/')
if 'tid' not in session:
return '2FA Spoofing attempt detected.'
if request.method == "GET":
return render_template('oauth.html', title='2FA', fixed_footer=True)
elif request.method == "POST":
code = request.form["code"]
if str(code) != get_valid(session['tid']):
return 'Login failed.'
user = User.query.filter(User.login == TID.query.filter(str(TID.tid) == str(session['tid'])).first().login).first()
session['username'] = user.login
session['user_id'] = user.id
session['admin'] = user.admin
return redirect('/')
# User registration
@app.route('/registration', methods=['GET', 'POST'])
def registration():
if request.method == "GET":
return render_template('registration.html', title=': Регистрация', fixed_footer=True)
elif request.method == "POST":
login = request.form["login"]
password = request.form["u_password"]
password_conf = request.form["u_password_once_again"]
email = request.form["email"]
if not (login and password):
error = "Одно из полей не заполнено"
elif password != password_conf:
error = 'Пароли не совпадают'
elif User.query.filter(User.login == login).first():
error = "Пользователь с таким именем уже зарегистрирован в системе. Исправьте данные"
elif User.query.filter(User.email == email).first():
error = "Пользователь с таким e-mail уже зарегистрирован в системе. Исправьте данные"
else:
if not request.form["email"]:
email = ''
password = generate_password_hash(password)
user = User(password=password, login=login, email=email, admin=0)
db.session.add(user)
db.session.commit()
return render_template('registration_success.html')
return render_template('registration.html', title=': Регистрация', fixed_footer=True, error=error)
@app.route('/add-task', methods=['GET', 'POST'])
def add_task():
if 'user_id' not in session:
return redirect('/')
if request.method == "GET":
users = User.query.all()
print(len(users))
problem = Problem(name='Новая задача', statement='', time_end=(datetime.now() + datetime.timedelta(days=1)).strftime("%d/%m/%Y %H:%M:%S"),
author_id=session['user_id'], completion_stage=0)
session['problem_id'] = problem.id
return render_template('edit_task.html', title='Добавление задачи', problem=problem, users=users)
elif request.method == "POST":
name = request.form["name"]
end_time = request.form["time_end"]
description = request.form["description"]
completion = request.form["completion_stage"]
solver = request.form["solver"]
print(solver)
user = Problem(name=name, statement=description, time_end=end_time, author_id=session['user_id'], completion_stage=completion, solver_id=solver)
Problem.query.filter(Problem.id == session['problem_id']).delete()
db.session.add(user)
session['problem_id'] = user.id
db.session.commit()
return redirect(f'/edit-task/{user.id}')
@app.route('/edit-task/<int:task_id>', methods=['GET', 'POST'])
def edit_task(task_id):
if 'user_id' not in session:
return abort(404)
if request.method == "GET":
problem = Problem.query.filter(Problem.id == task_id).first()
if problem is None:
return 'Not found :('
if str(problem.author_id) != str(session['user_id']):
return 'Forbidden!!'
if problem.deleted:
return 'Scheduled delete.'
users = User.query.all()
print(len(users))
session['problem_id'] = problem.id
return render_template('edit_task.html', title='Редактирование задачи', problem=problem, users=users)
elif request.method == "POST":
name = request.form["name"]
end_time = request.form["time_end"]
description = request.form["description"]
completion = request.form["completion_stage"]
solver = request.form.get('solver', session['user_id'])
print(solver)
user = Problem(name=name, statement=description, time_end=end_time, author_id=session['user_id'],
completion_stage=completion, solver_id=solver)
Problem.query.filter(Problem.id == session['problem_id']).delete()
db.session.add(user)
session['problem_id'] = user.id
db.session.commit()
return render_template('edit_task.html', problem=user)
@app.route('/full/<int:task_id>', methods=['GET', 'POST'])
def full(task_id):
if 'user_id' not in session:
return abort(404)
problem = Problem.query.filter(Problem.id == task_id).first()
if problem is None:
return 'Not found :('
if str(problem.author_id) != str(session['user_id']):
return 'Forbidden!!'
if problem.deleted:
return 'Scheduled delete.'
return render_template('full_info.html', title='Информация о задаче', problem=problem)
@app.route('/del-task/<int:task_id>', methods=['GET', 'POST'])
def del_task(task_id):
if 'user_id' not in session:
return abort(404)
problem = Problem.query.filter(Problem.id == task_id).first()
if problem is None:
return 'Not found :('
if str(problem.id) != str(session['user_id']):
return 'Forbidden!!'
problem.deleted = True
db.session.commit()
return redirect('/')
@app.errorhandler(404)
def not_found(error):
return render_template("error_404.html", title=": Страница не найдена", fixed_footer=True)
api = Api(app)
api.add_resource(Task, '/api/task/<int:task_id>')
api.add_resource(Tasks,'/api/task')
api.add_resource(Auth, '/api/auth')
from flask import Flask, request
import logging
import json
import random
from requests import post
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
@app.route('/alice', methods=['POST'])
def alice():
logging.info('Request: %r', request.json)
response = {
'session': request.json['session'],
'version': request.json['version'],
'response': {
'end_session': False
}
}
handle_dialog(response, request.json)
logging.info('Response: %r', response)
return json.dumps(response)
def handle_dialog(res, req):
if req['session']['new']:
res['response']['text'] = 'Привет! Введи <login> <password>'
return
args = req["original_utterance"].strip()
login, passw = args
print(login, passw)
response = post('http://localhost:5000/api/auth',
data={"login": login, "password": passw}).json()
print(response)
if response["token"]:
res["text"] = "Успешно"
else:
res["text"] = response["error"]
return
if __name__ == '__main__':
app.run()
if __name__ == '__main__':
app.run('127.0.0.1', port=5000, debug=True)