This repository has been archived by the owner on Oct 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathivled2_webapp.py
450 lines (375 loc) · 16.6 KB
/
ivled2_webapp.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import config
from flask import Flask, render_template, redirect, session, request, url_for, g, flash, abort
import json
import time
from requests.exceptions import ConnectionError, Timeout
from api import ivle
import dropbox
from oauth2client.client import OAuth2WebServerFlow
import models
import drivers
from utils import mail
app = Flask(__name__)
@app.before_request
def before_request():
g.request_start_time = time.time()
g.request_time = lambda: "%.5fs" % (time.time() - g.request_start_time)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/dashboard/")
def dashboard():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
selected_modules = ', '.join(sorted([course['Code'] for course in user.modules])) or 'None'
return render_template('dashboard.html', selected_modules=selected_modules, target=user.target, target_settings=user.target_settings,
DROPBOX_APPKEY=config.DROPBOX_APPKEY, user_id=user.user_id, key=user.key, sync_enabled=user.enabled,
uploadable_folder=user.uploadable_folder, email=user.email, auto_intro=(not user.modules) and (not user.target))
# return 'Logged in as %s' % session['user_id']
@app.route("/modules/")
def modules():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
try:
mods = ivle.get_modules_list(user)
except Exception as e:
return "IVLE is not responding. Please try again later."
selected_modules = [course['Code'] for course in user.modules]
return render_template('modules.html', modules=mods, selected_modules=selected_modules)
@app.route("/modules/submit/", methods=['POST'])
def modules_submit():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
courses = []
for course in request.form:
course_code, course_id = str(course).split('|')
courses.append({'Code': course_code, 'ID': course_id})
with user.lock:
user.sync_from_db()
user.modules = courses
user.update()
return ""
@app.route("/modules/get/")
def modules_get():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
selected_modules = ', '.join(sorted([course['Code'] for course in user.modules])) or 'None'
return selected_modules
@app.route("/settings/submit/", methods=['POST'])
def settings_submit():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
with user.lock:
user.sync_from_db()
try:
user.enabled = bool(request.form.get('sync_enabled', ''))
if (not user.enabled) or (drivers.drivers[user.target].check_settings(user.target_settings)):
user.uploadable_folder = bool(request.form.get('uploadable_folder', ''))
user.email = request.form.get('email', user.email)
user.update()
return json.dumps({'result': True})
else: # TODO: Should never reach
user.enabled = False
user.update()
return json.dumps({'result': False, 'message': 'An unknown error happened. Please refresh the page and try again.'})
except drivers.SyncException as e:
user.enabled = False
user.uploadable_folder = bool(request.form.get('uploadable_folder', ''))
user.email = request.form.get('email', user.email)
user.update()
return json.dumps({'result': False, 'message': e.message})
# Target: Dropbox
def get_dropbox_auth_flow():
redirect_uri = url_for('auth_dropbox_callback', _external=True, _scheme='https')
return dropbox.client.DropboxOAuth2Flow(config.DROPBOX_APPKEY, config.DROPBOX_APPSECRET, redirect_uri,
session, 'dropbox-auth-csrf-token')
@app.route("/auth/dropbox/")
def auth_dropbox():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
redirect_uri = get_dropbox_auth_flow().start()
session['dropbox-auth-csrf-token'] = str(session['dropbox-auth-csrf-token']) # Temporary walkaround for Dropbox SDK Bug on 3.x
return redirect(redirect_uri)
@app.route("/auth/dropbox/callback/")
def auth_dropbox_callback():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
try:
access_token, user_id, url_state = get_dropbox_auth_flow().finish(request.args)
except dropbox.client.DropboxOAuth2Flow.BadRequestException:
abort(400)
except dropbox.client.DropboxOAuth2Flow.BadStateException:
abort(400)
except dropbox.client.DropboxOAuth2Flow.CsrfException:
abort(403)
except dropbox.client.DropboxOAuth2Flow.NotApprovedException:
flash('Not approved?', 'warning')
return redirect(url_for('dashboard'))
except dropbox.client.DropboxOAuth2Flow.ProviderException as e:
app.logger.exception("Auth error" + str(e))
abort(403)
with user.lock:
user.sync_from_db()
user.target = 'dropbox'
dropbox_username = dropbox.client.DropboxClient(access_token).account_info()['display_name']
if user.last_target != 'dropbox':
user.target_settings = {'token': access_token, 'folder': '', 'files_revision': {}}
flash('Successfully logged in to Dropbox as %s' % dropbox_username, 'info')
else:
user.target_settings['token'] = access_token
flash('Successfully refreshed token for Dropbox user %s' % dropbox_username, 'info')
user.update()
return redirect(url_for('dashboard'))
@app.route("/auth/dropbox/logout/")
def auth_dropbox_unauth():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
user.unauth_target(True)
flash('Successfully logged out from Dropbox.', 'warning')
return redirect(url_for('dashboard'))
@app.route("/internal/dropbox/folder/")
def dropbox_folder():
user_id = request.args.get('user_id', '')
if not user_id:
return "Unauthorized!", 403
user = models.User(user_id)
if request.args.get('key', '') != user.key:
return "Unauthorized!", 403
dropbox_client = dropbox.client.DropboxClient(user.target_settings['token'])
try:
file_list = dropbox_client.search('/', '.Your_Workbin_Files')
for file in file_list:
dropbox_client.file_delete(file['path'])
except:
pass # TODO
return ""
@app.route("/internal/dropbox/update_folder/")
def dropbox_update_folder():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
dropbox_client = dropbox.client.DropboxClient(user.target_settings['token'])
file_list = dropbox_client.search('/', '.Your_Workbin_Files')
if file_list:
with user.lock:
user.sync_from_db()
new_path = file_list[0]['path']
user.target_settings['folder'] = new_path[:new_path.rfind('/') + 1]
user.update()
dropbox_client.file_delete(new_path)
return user.target_settings['folder']
else:
return "[Unknown Error, Please Retry]" # TODO
# End of Dropbox
# Target: Google Drive
def get_google_auth_flow():
redirect_uri = url_for('auth_google_callback', _external=True, _scheme='https')
return OAuth2WebServerFlow(config.GOOGLE_CLIENT_ID, config.GOOGLE_CLIENT_SECRET, config.GOOGLE_OAUTH_SCOPE, redirect_uri=redirect_uri,
approval_prompt='force')
@app.route("/auth/google/")
def auth_google():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
redirect_uri = get_google_auth_flow().step1_get_authorize_url()
return redirect(redirect_uri)
@app.route("/auth/google/callback/")
def auth_google_callback():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
code = request.args.get('code', '')
error = request.args.get('error', '')
if error:
flash('Error: ' + error, 'warning')
return redirect(url_for('dashboard'))
try:
credentials = get_google_auth_flow().step2_exchange(code)
if credentials.invalid:
flash('Credential Invalid.', 'warning')
return redirect(url_for('dashboard'))
except Exception as e:
flash('Error: ' + str(e), 'warning')
return redirect(url_for('dashboard'))
with user.lock:
user.sync_from_db()
user.target = 'google'
if user.last_target != 'google':
flash('Logged in to Google Drive.', 'info')
user.target_settings = {'credentials': credentials.to_json(), 'parent_id': ''}
else:
flash('Refreshed Google Drive token.', 'info')
user.target_settings['credentials'] = credentials.to_json()
user.update()
return redirect(url_for('dashboard'))
@app.route("/auth/google/logout/")
def auth_google_unauth():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
user.unauth_target(True)
flash('Successfully logged out from Google Drive.', 'warning')
return redirect(url_for('dashboard'))
@app.route("/internal/google/folder_ui/")
def google_folder_ui():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
return render_template('google_folder_ui.html', user_id=user.user_id, key=user.key)
@app.route("/internal/google/folder/")
def google_folder():
user_id = request.args.get('user_id', '')
if not user_id:
return "Unauthorized!", 403 # TODO
user = models.User(user_id)
if request.args.get('key', '') != user.key:
return "Unauthorized!", 403 # TODO
try:
apiclient = drivers.GoogleDriver.get_drive_client(user.target_settings)
params = {'q': "title = '.Your_Workbin_Files'"}
files = apiclient.files().list(**params).execute()
for file in files['items']:
apiclient.files().delete(fileId=file['id']).execute()
except:
pass
return "0"
@app.route("/internal/google/update_folder/")
def google_update_folder():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
apiclient = drivers.GoogleDriver.get_drive_client(user.target_settings)
params = {'q': "title = '.Your_Workbin_Files'"}
files = apiclient.files().list(**params).execute()
if len(files['items']) > 0:
with user.lock:
user.sync_from_db()
user.target_settings['parent_id'] = files['items'][0]['parents'][0]['id']
user.update()
apiclient.files().delete(fileId=files['items'][0]['id']).execute()
else:
pass # TODO
return ''
@app.route("/internal/google/get_folder/")
def google_get_folder():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
if user.target_settings['credentials'] and user.target_settings['parent_id']:
try:
apiclient = drivers.GoogleDriver.get_drive_client(user.target_settings)
result = {'result': True, 'path': drivers.GoogleDriver.get_folder_name(apiclient, user.target_settings['parent_id'])}
except Exception as e:
result = {'result': False, 'info': 'Error: ' + str(e)}
else:
result = {'result': False, 'info': 'Unknown / Not Set'}
return json.dumps(result)
# End of Google Drive
# Target: OneDrive
def get_onedrive_auth_flow():
redirect_uri = url_for('auth_onedrive_callback', _external=True, _scheme='https')
return OAuth2WebServerFlow(config.ONEDRIVE_CLIENT_ID, config.ONEDRIVE_CLIENT_SECRET, "wl.offline_access onedrive.readwrite",
redirect_uri=redirect_uri, auth_uri="https://login.live.com/oauth20_authorize.srf",
token_uri="https://login.live.com/oauth20_token.srf", revoke_uri="https://login.live.com/oauth20_logout.srf")
@app.route("/auth/onedrive/")
def auth_onedrive():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
redirect_uri = get_onedrive_auth_flow().step1_get_authorize_url()
return redirect(redirect_uri)
@app.route("/auth/onedrive/callback/")
def auth_onedrive_callback():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
code = request.args.get('code', '')
error = request.args.get('error', '')
if error:
flash('Error: ' + error, 'warning')
return redirect(url_for('dashboard'))
try:
credentials = get_onedrive_auth_flow().step2_exchange(code)
if credentials.invalid:
flash('Credential Invalid.', 'warning')
return redirect(url_for('dashboard'))
except Exception as e:
flash('Error: ' + str(e), 'warning')
return redirect(url_for('dashboard'))
with user.lock:
user.sync_from_db()
user.target = 'onedrive'
if user.last_target != 'onedrive':
flash('Logged in to OneDrive.', 'info')
user.target_settings = {'credentials': credentials.to_json(), 'folder': ''}
else:
flash('Refreshed OneDrive token.', 'info')
user.target_settings['credentials'] = credentials.to_json()
user.update()
return redirect(url_for('dashboard'))
@app.route("/auth/onedrive/logout/")
def auth_onedrive_unauth():
if 'user_id' not in session or session['user_id'] == '':
return redirect(url_for('login'))
user = models.User(session['user_id'])
user.unauth_target(True)
flash('Successfully logged out from OneDrive.', 'warning')
return redirect(url_for('dashboard'))
# End of OneDrive
@app.route("/login/")
def login():
return redirect(ivle.get_ivle_login_url(url_for('login_callback', _external=True, _scheme='https')))
@app.route("/login/emergency/")
def login_emergency():
return render_template('emergency_login.html', form_address=url_for('login_emergency_submit'))
@app.route("/login/emergency/submit/")
def login_emergency_submit():
user_id = request.args.get('user_id', '')
if not models.User.user_exists(user_id):
return json.dumps({'info': 'User does not exist!', 'type': 'danger'})
else:
user = models.User(user_id)
auth_code = user.generate_emergency_code()
mail.send_emergency_code_to_user(user.email, user_id, auth_code)
return json.dumps({'info': 'We have sent an email to your email address ending with @%s.' % user.email.split('@')[-1], 'type': 'info'})
@app.route("/login/emergency/check/")
def login_emergency_check():
user_id = request.args.get('user_id', '')
auth_code = request.args.get('auth_code', '')
if user_id and auth_code and models.User.user_exists(user_id):
user = models.User(user_id)
if user.check_emergency_code(auth_code):
session['user_id'] = user.user_id
flash('Successfully logged in (using emergency link) as %s.' % user.user_id, 'info')
return redirect(url_for('dashboard'))
else:
return 'Something went wrong, please try again.'
else:
abort(403)
@app.route("/login/callback/")
def login_callback():
token = request.args.get('token', '')
try:
user_dict = ivle.get_user_id_and_email(token)
except (ConnectionError, ValueError, Timeout):
return redirect(url_for('login_emergency'))
user = models.User(user_dict['UserID'], user_dict['Email'])
user.update_ivle_token(token)
session['user_id'] = user.user_id
flash('Successfully logged in as %s.' % user.user_id, 'info')
return redirect(url_for('dashboard'))
@app.route("/logout/")
def logout():
session.pop('user_id', None)
return redirect(url_for('index'))
app.secret_key = config.FLASK_SECRET_KEY
if __name__ == '__main__':
app.run(port=8000, debug=config.DEBUG)