-
Notifications
You must be signed in to change notification settings - Fork 23
/
routes.py
350 lines (296 loc) 路 11.3 KB
/
routes.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
from flask import render_template, make_response, request, redirect, url_for, jsonify, abort, g, session
from app import app, db, scraper, cas
from app.models import User, Person, Key, PersonPersistent
from app.util import requires_login, forbidden_via_api, to_json, get_now, succ, fail, PERSISTENT_FIELDS, is_valid_instagram_username, is_valid_snapchat_username
from .cas_validate import validate
from sqlalchemy import distinct
from flask_cas.cas_urls import create_cas_login_url
from flask_cas.cas_urls import create_cas_logout_url
from flask_cas.cas_urls import create_cas_validate_url
import datetime
import calendar
with open('app/scraper/res/majors_clean.txt') as f:
majors = f.read().splitlines()
@app.before_request
def store_user():
if request.method != 'OPTIONS':
g.user = None
timestamp = get_now()
token_cookie = request.cookies.get('token')
if token_cookie:
g.user = User.from_token(token_cookie)
g.method_used = 'cookie'
authorization = request.headers.get('Authorization')
if g.user is None and authorization:
token = authorization.split(' ')[-1]
g.user = User.from_token(token)
g.method_used = 'header'
if g.user is None and cas.username:
g.user = User.query.get(cas.username)
if not g.user:
# If this is the first user (probably local run), there's been no chance to
# run the scraper yet, so make them admin to prevent an instant 403.
is_first_user = User.query.count() == 0
g.user = User(id=cas.username,
registered_on=timestamp,
admin=is_first_user)
db.session.add(g.user)
g.method_used = 'CAS'
if g.user:
g.person = Person.query.filter_by(netid=g.user.id, school_code='YC').first()
if g.user.banned or (not g.person and not g.user.admin):
# TODO: give a more graceful error than just a 403
abort(403)
try:
print(f'Authorized request by {g.person.first_name} {g.person.last_name} with {g.method_used} authentication.')
except AttributeError:
print('Could not render name.')
g.user.last_seen = timestamp
db.session.commit()
else:
print('Request made by unauthorized user.')
@app.route('/')
def index():
if not g.user:
return render_template('splash.html')
colleges = [
'Berkeley',
'Branford',
'Davenport',
'Ezra Stiles',
'Jonathan Edwards',
'Benjamin Franklin',
'Grace Hopper',
'Morse',
'Pauli Murray',
'Pierson',
'Saybrook',
'Silliman',
'Timothy Dwight',
'Trumbull',
]
years = get_years()
leave = ['Yes', 'No']
birth_months = {index + 1: name for index, name in enumerate(list(calendar.month_name)[1:])}
birth_days = list(range(1, 31 + 1))
# TODO: should this be loaded from the filters endpoint?
options = {}
for category in Person.__filterable__:
options[category] = untuple(db.session.query(distinct(getattr(Person, category))).order_by(getattr(Person, category)))
filters = {
'Students': {
'school': {
'header': 'School',
},
'year': {
'header': 'Year',
},
},
'Undergraduate': {
'college': {
'header': 'College',
},
'major': 'Major',
'leave': {
'header': 'Took Leave?',
'default': 'N/A'
},
'birth_month': {
'header': 'Birth Month',
},
'birth_day': {
'header': 'Birth Day',
},
},
'Graduate': {
'curriculum': {
'header': 'Grad Curriculum',
},
},
'Staff': {
'organization': {
'header': 'Staff Organization',
},
'unit': {
'header': 'Staff Unit',
},
'office_building': {
'header': 'Office Building',
},
},
}
return render_template('index.html', colleges=colleges,
years=years, leave=leave, majors=majors,
birth_months=birth_months, birth_days=birth_days, options=options, filters=filters)
def untuple(tuples):
return [t[0] for t in tuples]
@app.route('/login/')
def login():
if g.user:
return redirect(url_for(app.config['CAS_AFTER_LOGIN']))
token = None
# NOTE: most of this code is adapted from the flask_cas module, but has since been heavily modified.
redirect_url = create_cas_login_url(
app.config['CAS_SERVER'],
app.config['CAS_LOGIN_ROUTE'],
url_for('.login', _external=True))
if 'ticket' in request.args:
ticket = request.args['ticket']
valid, username = validate(ticket)
if not valid:
abort(401)
redirect_url = url_for(app.config['CAS_AFTER_LOGIN'])
g.user = User.query.get(username)
if g.user is None:
# TODO: this is duplicated from above. Decrease ick
is_first_user = User.query.count() == 0
g.user = User(id=username,
registered_on=get_now(),
admin=is_first_user)
db.session.add(g.user)
db.session.commit()
token = g.user.generate_token()
print('Logged in!')
app.logger.debug('Redirecting to: {0}'.format(redirect_url))
resp = make_response(redirect(redirect_url))
if token is not None:
resp.set_cookie('token', token, max_age=365 * 60 * 60 * 24)
return resp
@app.route('/logout/')
def logout():
cas_username_session_key = app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in session:
del session[cas_username_session_key]
if cas_attributes_session_key in session:
del session[cas_attributes_session_key]
redirect_url = app.config['CAS_AFTER_LOGOUT']
app.logger.debug('Redirecting to: {0}'.format(redirect_url))
resp = make_response(redirect(redirect_url))
resp.set_cookie('token', '', expires=0)
return resp
@app.route('/scraper', methods=['GET', 'POST'])
@requires_login
def scrape():
if not g.user.admin:
abort(403)
if request.method == 'GET':
return render_template('scraper.html')
payload = request.get_json()
scraper.scrape.apply_async(args=[payload['caches'], payload['face_book_cookie'], payload['people_search_session_cookie'], payload['csrf_token'], payload['yaleconnect_cookie']])
return '', 200
@app.route('/apidocs')
@requires_login
def apidocs():
return render_template('apidocs.html', title='API')
@app.route('/about')
@requires_login
def about():
return render_template('about.html', title='About')
@app.route('/faq')
def faq():
return render_template('faq.html', title='FAQ')
@app.route('/hide_me')
def hide_me():
return redirect(url_for('faq'))
@app.route('/keys', methods=['GET'])
@requires_login
@forbidden_via_api
def get_keys():
keys = Key.query.filter_by(user_id=g.user.id,
deleted=False).all()
return to_json(keys)
@app.route('/keys', methods=['POST'])
@requires_login
@forbidden_via_api
def create_key():
payload = request.get_json()
key = g.user.create_key(payload['description'])
db.session.add(key)
db.session.commit()
return to_json(key)
@app.route('/keys/<key_id>', methods=['DELETE'])
@requires_login
@forbidden_via_api
def delete_key(key_id):
key = Key.query.get(key_id)
if key.user_id != g.user.id:
return fail('You may not delete this key.', 403)
key.deleted = True
db.session.commit()
return succ('Key deleted.')
@app.route('/edit', methods=['GET'])
@requires_login
def edit():
if g.person is None:
return fail('Could not find person in the database.', 403)
person_persistent = g.person.get_persistent_data()
if person_persistent is None:
return render_template('edit.html')
return render_template(
'edit.html',
socials_instagram=person_persistent.socials_instagram,
socials_snapchat=person_persistent.socials_snapchat,
privacy_hide_image=person_persistent.privacy_hide_image,
privacy_hide_email=person_persistent.privacy_hide_email,
privacy_hide_room=person_persistent.privacy_hide_room,
privacy_hide_phone=person_persistent.privacy_hide_phone,
privacy_hide_address=person_persistent.privacy_hide_address,
privacy_hide_major=person_persistent.privacy_hide_major,
privacy_hide_birthday=person_persistent.privacy_hide_birthday
)
@app.route('/edit', methods=['POST'])
@requires_login
@forbidden_via_api
def edit_post():
payload = request.get_json()
socials_instagram = payload["socials_instagram"] if hasattr(payload, "socials_instagram") else None
socials_snapchat = payload["socials_snapchat"] if hasattr(payload, "socials_snapchat") else None
if (socials_instagram is not None) and (len(socials_instagram) != 0) and (not is_valid_instagram_username(payload["socials_instagram"])):
return fail('Invalid Instagram username.', 400)
if (socials_snapchat is not None) and (len(socials_snapchat) != 0) and (not is_valid_snapchat_username(payload["socials_snapchat"])):
return fail('Invalid Snapchat username.', 400)
if g.person is None:
return fail('Could not find person in the database.', 403)
person_persistent = g.person.get_persistent_data()
if person_persistent is None:
person_persistent = PersonPersistent(person_id=g.person.id)
db.session.add(person_persistent)
for key in PERSISTENT_FIELDS:
if key in payload:
setattr(person_persistent, key, payload[key])
db.session.commit()
return succ('Person edited.')
@app.route('/authorize', methods=['POST'])
def api_authorize_cas():
ticket = request.args.get('ticket')
if not ticket:
print('Aborting due to missing ticket')
abort(401)
valid, username = validate(ticket)
if not valid:
print('Aborting due to invalid ticket')
abort(401)
print('Logged in!')
g.user = User.query.get(username)
db.session.commit()
return to_json({'token': g.user.generate_token()})
def get_years():
"""
returns list of currently enrolled class years
After May, the oldest class should be removed
After July, the next class should be added
e.g.:
in January 2021: years = [2021, 2022, 2023, 2024]
in July 2021: years = [2022, 2023, 2024]
in September 2021: years = [2022, 2023, 2024, 2025]
"""
GRAD_MONTH = 5 # May
ADD_MONTH = 8 # August
NUM_CLASSES = 4
current_date = datetime.date.today()
oldest_class_year = current_date.year if current_date.month <= GRAD_MONTH else current_date.year + 1
youngest_class_year = current_date.year + NUM_CLASSES if current_date.month >= ADD_MONTH else current_date.year + NUM_CLASSES - 1
years = list(range(oldest_class_year, youngest_class_year + 1))
years.append('')
return years