-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.wsgi
executable file
·648 lines (536 loc) · 21.3 KB
/
app.wsgi
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2024 Stephen Warren
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import google.auth.transport.requests
import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery
import os
import flask
import requests
import sqlite3
from werkzeug.middleware.proxy_fix import ProxyFix
# Configuration
app_dir = '/var/www/fcch-gdrive-chown'
fcch_creator_hub_public_folder = '0BztS2sNeBoIFYXI0bVlncWswZmc'
target_owner_email_by_domain = {
None: ('[email protected]', True),
'gmail.com': ('[email protected]', True),
'fortcollinscreatorhub.org': ('[email protected]', False),
}
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
# This variable specifies the name of a file that contains the OAuth 2.0
# information for this application, including its client_id and client_secret.
CLIENT_SECRETS_FILE = app_dir + "/client_secret.json"
# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = [
'openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/drive',
]
API_SERVICE_NAME = 'drive'
# v3 API doesn't seem to work for consumer ownership transfers:-(
API_VERSION = 'v2'
REACHABLE_UNKNOWN = 0
REACHABLE_NO = 1
REACHABLE_YES = 2
CHOWN_UNKNOWN = 0
CHOWN_NO = 1
CHOWN_YES = 2
CHOWN_DONE = 3
PENDING_OWNER_NO = 0
PENDING_OWNER_YES = 1
PENDING_OWNER_DONE = 2
def url_for(path):
return script_name + '/' + path
def credentials_to_dict(credentials):
return {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'id_token':credentials.id_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes,
'expiry': credentials.expiry,
}
app = flask.Flask(__name__)
app.config['SESSION_COOKIE_NAME'] = 'fcch_gdrive_chown'
# Note: A secret key is included in the sample so that it works.
# If you use this code in your application, replace this with a truly secret
# key. See https://flask.palletsprojects.com/quickstart/#sessions.
app.secret_key = 'a3102d0ce0ce1f0b622b03b788cb788a0e66826778abe03b1a599ef3f0f5f42d'
# Reverse proxy configuration
app.wsgi_app = ProxyFix(
app.wsgi_app, x_for=1, x_proto=0, x_host=0, x_prefix=0
)
def js_response(msg, data=None):
js = {'message': str(msg)}
if data is not None:
js['data'] = data
return flask.jsonify(js)
def exc_to_text(e):
import traceback
es = traceback.format_exception(e)
return 'ERROR:\n' + '\n'.join(es)
def exc_to_html(e):
import traceback
es = traceback.format_exception(e)
# FIXME: HTML-escape the lines...
return 'ERROR:<br/>' + '<br/>'.join(es)
def batch_callback(request_id, response, exception):
if exception:
raise exception
def get_db():
dbcon = getattr(flask.g, '_dbcon', None)
if dbcon is None:
dbcon = flask.g._dbcon = sqlite3.connect(app_dir + "/var/db.db")
dbcur = dbcon.cursor()
dbcur.execute("CREATE TABLE IF NOT EXISTS files (user TEXT, id TEXT, title TEXT, isFolder INT, owner TEXT, reachable INT, needChown INT, doChown INT, pendingOwner INT, alternateLink TEXT)")
dbcur.execute("CREATE TABLE IF NOT EXISTS fileParents (user TEXT, id TEXT, parent TEXT)")
return (dbcon, dbcur)
@app.teardown_appcontext
def close_connection(exception):
dbcon = getattr(flask.g, '_dbcon', None)
if dbcon is not None:
dbcon.close()
@app.route('/')
def index():
logged_in = 'credentials' in flask.session
return flask.render_template('index.html', prefix=url_for(''), logged_in=logged_in)
@app.route('/login')
def login():
try:
if 'credentials' in flask.session:
raise Exception('Can\'t log in: Already logged in')
# Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)
# The URI created here must exactly match one of the authorized redirect URIs
# for the OAuth 2.0 client, which you configured in the API Console. If this
# value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
# error.
flow.redirect_uri = oauth2callback_uri
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true')
# Store the state so the callback can verify the auth server response.
flask.session['state'] = state
return flask.redirect(authorization_url)
except Exception as e:
msg = 'ERROR: ' + exc_to_html(e)
flask.flash(msg)
return flask.redirect(url_for(''))
@app.route('/oauth2callback')
def oauth2callback():
try:
# Specify the state when creating the flow in the callback so that it can
# verified in the authorization server response.
state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
flow.redirect_uri = oauth2callback_uri
# Use the authorization server's response to fetch the OAuth 2.0 tokens.
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
# Store credentials in the session.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
credentials = flow.credentials
flask.session['credentials'] = credentials_to_dict(credentials)
user_info_service = googleapiclient.discovery.build(
serviceName='oauth2', version='v2', credentials=credentials)
user_info = user_info_service.userinfo().get().execute()
flask.session['email'] = user_info['email']
msg = 'Log in succeeded'
except Exception as e:
msg = 'ERROR: ' + exc_to_html(e)
flask.flash(msg)
return flask.redirect(url_for(''))
@app.route('/logout')
def logout():
try:
if 'credentials' not in flask.session:
raise Exception('Can\'t log out: Not logged in')
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
revoke = requests.post('https://oauth2.googleapis.com/revoke',
params={'token': credentials.token},
headers = {'content-type': 'application/x-www-form-urlencoded'})
revoke.raise_for_status()
msg = 'Log out succeeded'
except Exception as e:
msg = 'ERROR: ' + exc_to_html(e)
if 'credentials' in flask.session:
del flask.session['credentials']
flask.flash(msg)
return flask.redirect(url_for(''))
def raise_if_unauth():
if 'credentials' not in flask.session:
raise Exception('Not logged in')
sess_creds = flask.session['credentials']
credentials = google.oauth2.credentials.Credentials(
sess_creds['token'],
refresh_token=sess_creds['refresh_token'],
id_token=sess_creds['id_token'],
token_uri=sess_creds['token_uri'],
client_id=sess_creds['client_id'],
client_secret=sess_creds['client_secret'],
scopes=sess_creds['scopes'],
)
# Google OAuth lib removes TZ info for backwards compatibility.
# The expiry time itself is already always in UTC, so this should work OK.
credentials.expiry = sess_creds['expiry'].replace(tzinfo=None)
if credentials.expired:
request = google.auth.transport.requests.Request()
credentials.refresh(request)
flask.session['credentials'] = credentials_to_dict(credentials)
@app.route('/get_drive_file_list')
def get_drive_file_list():
try:
raise_if_unauth()
page_token = flask.request.args.get('page_token', None)
if page_token is None:
flask.session['count'] = str(0)
count = int(flask.session['count'])
# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
(dbcon, dbcur) = get_db()
drive_service = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials)
response = drive_service.files().list(pageToken=page_token).execute()
files = response.get("items", [])
if page_token is None:
dbcur.execute("DELETE FROM files WHERE user=?",
(flask.session['email'], ))
dbcur.execute("DELETE FROM fileParents WHERE user=?",
(flask.session['email'], ))
for file in files:
file_id = file['id']
file_title = file['title']
file_type = file['mimeType']
if file_type == 'application/vnd.google-apps.shortcut':
continue
file_is_folder = file_type == 'application/vnd.google-apps.folder'
file_owner = file['owners'][0]['emailAddress']
file_reachable = REACHABLE_UNKNOWN
file_need_chown = CHOWN_UNKNOWN
file_do_chown = CHOWN_UNKNOWN
file_pending_owner = file['userPermission']['pendingOwner']
file_parents = file.get('parents', [])
file_alt_link = file['alternateLink']
dbcur.execute("INSERT INTO files (user, id, title, isFolder, owner, reachable, needChown, doChown, pendingOwner, alternateLink) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(flask.session['email'], file_id, file_title, file_is_folder, file_owner, file_reachable, file_need_chown, file_do_chown, file_pending_owner, file_alt_link))
for file_parent in file_parents:
dbcur.execute("INSERT INTO fileParents (user, id, parent) VALUES (?, ?, ?)",
(flask.session['email'], file_id, file_parent['id']))
fetched = len(files)
count += fetched
msg = f'Fetched {fetched} files (total now {count})'
flask.session['count'] = str(count)
page_token = response.get("nextPageToken", None)
if page_token is None:
msg = msg + '; fetch complete'
data = {}
else:
msg = msg + '; continuing fetch'
data = {'page_token': page_token}
dbcon.commit()
# Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
flask.session['credentials'] = credentials_to_dict(credentials)
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
data = None
return js_response(msg, data)
@app.route('/show_drive_file_list')
def show_drive_file_list():
try:
raise_if_unauth()
(dbcon, dbcur) = get_db()
dbres = dbcur.execute(
"SELECT * FROM files WHERE user=?",
(flask.session['email'], ))
files = dbres.fetchall()
dbres = dbcur.execute(
"SELECT user, id, parent FROM fileParents WHERE user=?",
(flask.session['email'], ))
file_parents = dbres.fetchall()
msg = ''
msg += 'Files:\n'
for file in files:
msg += repr(file) + '\n'
msg += 'File Parents:\n'
for file_parent in file_parents:
msg += repr(file_parent) + '\n'
dbcon.commit()
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
return js_response(msg)
@app.route('/calc_files_to_change_ownership')
def calc_files_to_change_ownership():
try:
raise_if_unauth()
(dbcon, dbcur) = get_db()
dbres = dbcur.execute(
"SELECT id, isFolder, owner FROM files WHERE user=?",
(flask.session['email'], ))
files = dbres.fetchall()
dbres = dbcur.execute(
"SELECT id, parent FROM fileParents WHERE user=?",
(flask.session['email'], ))
file_parents = dbres.fetchall()
file_data_of_file_id = {}
for file_id, file_is_folder, file_owner in files:
file_data_of_file_id[file_id] = (file_is_folder, file_owner)
child_file_ids_of_parent = {}
for file_id, file_parent in file_parents:
child_file_ids = child_file_ids_of_parent.get(file_parent, [])
child_file_ids.append(file_id)
child_file_ids_of_parent[file_parent] = child_file_ids
reachable_files = []
need_chown_files = []
do_chown_files = []
parents_to_do = [fcch_creator_hub_public_folder]
parents_done = {}
target_owner_emails = [email for (email, use_pending) in target_owner_email_by_domain.values()]
while parents_to_do:
parent = parents_to_do.pop()
child_file_ids = child_file_ids_of_parent.get(parent, [])
for file_id in child_file_ids:
file_is_folder, file_owner = file_data_of_file_id[file_id]
if file_is_folder:
if file_id not in parents_done:
parents_done[file_id] = True
parents_to_do.append(file_id)
reachable_files.append(file_id)
need_chown = file_owner not in target_owner_emails
if need_chown:
need_chown_files.append(file_id)
if (file_owner == flask.session['email']) and need_chown:
do_chown_files.append(file_id)
dbcur.execute("UPDATE files SET reachable=? WHERE user=?",
(REACHABLE_NO, flask.session['email']))
rows = [(REACHABLE_YES, flask.session['email'], file_id) for file_id in reachable_files]
dbcur.executemany("UPDATE files SET reachable=? WHERE user=? AND id=?", rows)
dbcur.execute("UPDATE files SET needChown=? WHERE user=?",
(CHOWN_NO, flask.session['email']))
rows = [(CHOWN_YES, flask.session['email'], file_id) for file_id in need_chown_files]
dbcur.executemany("UPDATE files SET needChown=? WHERE user=? AND id=?", rows)
dbcur.execute("UPDATE files SET doChown=? WHERE user=?",
(CHOWN_NO, flask.session['email']))
rows = [(CHOWN_YES, flask.session['email'], file_id) for file_id in do_chown_files]
dbcur.executemany("UPDATE files SET doChown=? WHERE user=? AND id=?", rows)
msg = 'Calculation complete'
dbcon.commit()
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
return js_response(msg)
@app.route('/show_files_need_change_ownership')
def show_files_need_change_ownership():
try:
raise_if_unauth()
(dbcon, dbcur) = get_db()
dbres = dbcur.execute(
"SELECT * FROM files WHERE user=? AND needChown=?",
(flask.session['email'], CHOWN_YES))
files = dbres.fetchall()
msg = ''
msg += 'Files:\n'
for file in files:
msg += repr(file) + '\n'
dbcon.commit()
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
return js_response(msg)
def get_owner_pend():
cur_domain = flask.session['email'].split('@')[1]
if cur_domain not in target_owner_email_by_domain:
cur_domain = None
target_owner, do_pending = target_owner_email_by_domain[cur_domain]
return target_owner, do_pending
@app.route('/show_files_to_change_ownership')
def show_files_to_change_ownership():
try:
raise_if_unauth()
(dbcon, dbcur) = get_db()
target_owner, do_pending = get_owner_pend()
dbres = dbcur.execute(
"SELECT * FROM files WHERE (user=? AND doChown=?) OR (user=? AND owner=? AND needChown=?)",
(flask.session['email'], CHOWN_YES, target_owner, flask.session['email'], CHOWN_YES))
files = dbres.fetchall()
msg = ''
msg += 'Files:\n'
for file in files:
msg += repr(file) + '\n'
dbcon.commit()
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
return js_response(msg)
@app.route('/chown_files')
def chown_files():
try:
raise_if_unauth()
init = flask.request.args.get('init', 'true')
if init == 'true':
flask.session['count'] = str(0)
count = int(flask.session['count'])
# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
target_owner, do_pending = get_owner_pend()
permission = {
'type': 'user',
'value': target_owner,
}
if do_pending:
permission['role'] = 'writer'
permission['pendingOwner'] = True
else:
permission['role'] = 'owner'
permission['transferOwnership'] = True
(dbcon, dbcur) = get_db()
drive_service = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials)
dbres = dbcur.execute(
"SELECT user, id, title FROM files WHERE (user=? AND doChown=?) OR (user=? AND owner=? AND needChown=?)",
(flask.session['email'], CHOWN_YES, target_owner, flask.session['email'], CHOWN_YES))
files = dbres.fetchall()
msg = ''
file_count = min(len(files), 25)
more = file_count < len(files)
batch = drive_service.new_batch_http_request(callback=batch_callback)
for user, file_id, file_title in files[:file_count]:
batch.add(drive_service.permissions().insert(fileId=file_id, body=permission, sendNotificationEmails=False))
dbcur.execute("UPDATE files SET needChown=?, doChown=?, owner=? WHERE user=? AND id=?",
(CHOWN_DONE, CHOWN_DONE, target_owner, user, file_id))
msg += f'{file_id} ({file_title})\n'
batch.execute()
count += file_count
flask.session['count'] = str(count)
if more:
cont = 'CONTINUING'
else:
cont = 'DONE'
msg = f'Ownership transfered for {file_count} files (total now {count}) ({cont}):\n' + msg
data = {'more': more}
dbcon.commit()
# Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
flask.session['credentials'] = credentials_to_dict(credentials)
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
data = None
return js_response(msg, data)
@app.route('/show_pending_ownership')
def show_pending_ownership():
try:
raise_if_unauth()
(dbcon, dbcur) = get_db()
dbres = dbcur.execute(
"SELECT * FROM files WHERE user=? AND reachable=? AND pendingOwner=?",
(flask.session['email'], REACHABLE_YES, PENDING_OWNER_YES))
files = dbres.fetchall()
msg = ''
msg += 'Files:\n'
for file in files:
msg += repr(file) + '\n'
dbcon.commit()
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
return js_response(msg)
@app.route('/accept_pending_ownership')
def accept_pending_ownership():
try:
raise_if_unauth()
init = flask.request.args.get('init', 'true')
if init == 'true':
flask.session['count'] = str(0)
count = int(flask.session['count'])
# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
target_owner, do_pending = get_owner_pend()
if not do_pending:
msg = 'Not needed for GSuite accounts'
return js_response(msg)
permission = {
'type': 'user',
'value': target_owner,
'role': 'owner',
'transferOwnership': True,
}
(dbcon, dbcur) = get_db()
drive_service = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials)
dbres = dbcur.execute(
"SELECT id, title FROM files WHERE user=? AND reachable=? AND pendingOwner=?",
(flask.session['email'], REACHABLE_YES, PENDING_OWNER_YES))
files = dbres.fetchall()
msg = ''
file_count = min(len(files), 25)
more = file_count < len(files)
batch = drive_service.new_batch_http_request(callback=batch_callback)
for file_id, file_title in files[:file_count]:
batch.add(drive_service.permissions().insert(fileId=file_id, body=permission))
dbcur.execute("UPDATE files SET pendingOwner=? WHERE user=? AND id=?",
(PENDING_OWNER_DONE, flask.session['email'], file_id))
msg += f'{file_id} ({file_title})\n'
batch.execute()
count += file_count
flask.session['count'] = str(count)
if more:
cont = 'CONTINUING'
else:
cont = 'DONE'
msg = f'Ownership accepted for {file_count} files (total now {count}) ({cont}):\n' + msg
data = {'more': more}
dbcon.commit()
# Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
flask.session['credentials'] = credentials_to_dict(credentials)
except Exception as e:
dbcon.rollback()
msg = exc_to_text(e)
data = None
return js_response(msg, data)
def application(environ, start_response):
global oauth2callback_uri
strip_len = len(environ['PATH_INFO']) - 1
oauth2callback_uri = environ['SCRIPT_URI'][:-strip_len] + 'oauth2callback'
global script_name
script_name = environ['SCRIPT_NAME']
return app(environ, start_response)