-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
executable file
·429 lines (366 loc) · 12.7 KB
/
utils.py
File metadata and controls
executable file
·429 lines (366 loc) · 12.7 KB
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
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import mail
from google.appengine.api import datastore_errors
import re
import hmac
import hashlib
import datetime
import random
import string
import logging
from secret import *
try:
# When deployed
from google.appengine.runtime import OverQuotaError
except ImportError:
# In the development server
from google.appengine.runtime.apiproxy_errors import OverQuotaError
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
PASS_RE = re.compile(r"^.{3,20}$")
class Email_Verification(db.Model):
email = db.StringProperty(required = True)
date_created = db.DateTimeProperty(auto_now_add = True)
class Users(db.Model):
email = db.StringProperty(required = True)
name = db.StringProperty(required = True)
password = db.StringProperty(required = True)
date_created = db.DateTimeProperty(auto_now_add = True)
email_verified = db.BooleanProperty(required = True)
class Courses(db.Model):
course = db.StringProperty(required = True)
mods_monday = db.StringProperty(required = False)
mods_tuesday = db.StringProperty(required = False)
mods_wed = db.StringProperty(required = False)
mods_thursday = db.StringProperty(required = False)
mods_friday = db.StringProperty(required = False)
students_enrolled = db.StringListProperty(required = True)
GET_USER = db.GqlQuery("SELECT * FROM Users WHERE email = :email LIMIT 1")
def remember_me():
'''Returns expiration time for remember me cookie'''
expiration = datetime.datetime.now() + datetime.timedelta(days=50)
return expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
def hash_str(string):
'''Hashes a string for user cookie'''
return hmac.new(SECRET, str(string), hashlib.sha512).hexdigest()
def salted_hash(password, salt):
'''Hashes a string for user password'''
return hashlib.sha256(password + salt).hexdigest()
def make_salt():
'''Makes random salt for user cookie'''
return ''.join(random.choice(string.letters) for x in xrange(5))
def unique_email(email):
'''Checks that an email is not taken already'''
accounts = (db.GqlQuery("SELECT * FROM Users WHERE email = :email", email = email)).get()
if accounts is None:
return True
return False
def get_user(email, cached = True):
'''Get User object from email'''
user = memcache.get('user-'+email)
if user and cached and not user is None:
logging.info('CACHE GET_USER: '+email)
return user
else:
logging.info('DB GET_USER: '+email)
GET_USER.bind(email = email)
user = GET_USER.get()
memcache.set('user-'+email, user)
logging.info('CACHE set user-'+email)
return user
def get_name(email, cached=True):
'''Gets name from db from email'''
return get_user(email, cached).name
def check_login(email, password):
"""Checks if login info is correct
Returns:
[False, error text]
OR
[True, cookie]
"""
correct = False
if email != '' and password != '':
accounts = memcache.get('user-'+email)
if accounts:
logging.info("CACHE LOGIN check_login(): "+email)
else:
logging.info("DB LOGIN check_login(): "+email)
GET_USER.bind(email = email)
accounts = GET_USER.get()
memcache.set('user-'+email, accounts)
logging.info("CACHE set user-"+email)
if accounts is None:
return [False, 'email does not exist']
(db_password, salt) = (accounts.password).split("|")
if salted_hash(password, salt) == db_password:
return [True, '%s=%s|%s;' % (LOGIN_COOKIE_NAME, str(email), str(hash_str(email)))]
return [False, 'Invalid email or password!']
def change_email(previous_email, new_email):
"""
Changes a user's email
Returns:
[Success_bool, error]
"""
if new_email == '':
return [False, 'No email entered']
if not EMAIL_RE.match(new_email + "@bergen.org"):
return [False, "That's not a valid email."]
user = get_user(previous_email)
user.email = new_email
user.email_verified = False
memcache.set('user-'+new_email, user)
user.put()
email_verification(new_email, user.name)
return [True]
def change_password(old, new, verify, email):
'''Change a user's password'''
if new == '':
return [False, {'new_password_error' : "Enter a password"}]
if old == '':
return [False, {'password_error' : "Enter your current password"}]
elif not PASS_RE.match(new):
return [False, {'new_password_error' : "That's not a valid password."}]
elif verify == '':
return [False, {'verify_password_error' : "Verify your password"}]
elif verify != new:
return [False, {'verify_password_error' : "Your passwords didn't match."}]
if not check_login(email, old)[0]:
return [False, {'password_error' : "Incorrect password."}]
user = get_user(email)
(db_password, db_salt) = (user.password).split("|")
if salted_hash(old, db_salt) == db_password:
salt = make_salt()
hashed = salted_hash(new, salt)
hashed_pass = hashed + '|' + salt
user.password = hashed_pass
user.put()
memcache.set('user-'+email, user)
memcache.set('useremail-'+str(user.email), user)
logging.info('CACHE set user-'+email)
logging.info('CACHE set useremail-'+str(user.email))
cookie = LOGIN_COOKIE_NAME + '=%s|%s; Expires=%s Path=/' % (str(email), hash_str(email), remember_me())
return [True, cookie]
else:
return [False, {'current_password_error' : 'Incorrect current password'}]
def get_verified(email):
'''Gets email_verified from db from email'''
return get_user(email, True).email_verified
def signup(email='', password='', verify='', agree='', name=''):
"""Signs up user
Returns:
Dictionary of elements with error messages and 'success' : False
OR
{'cookie' : cookie, 'success' : True}
"""
to_return = {'success' : False}
if password == '':
to_return['password'] = "Please enter a password"
elif not PASS_RE.match(password):
to_return['password'] = "That's not a valid password."
elif verify == '':
to_return['verify'] = "Please verify your password"
elif verify != password:
to_return['verify'] = "Your passwords didn't match."
if name == '':
to_return['name'] = "Please enter your name."
if not EMAIL_RE.match(email + "@bergen.org") and email != '':
to_return['email'] = "That's not a valid email."
elif not unique_email(email):
to_return['email'] = "Email already exits!"
if agree != 'on':
to_return['agree'] = "You must agree to the Terms of Service to create an account"
if len(to_return) == 1:
salt = make_salt()
hashed = salted_hash(password, salt)
hashed_pass = hashed + '|' + salt
account = Users(email = email, password = hashed_pass, email_verified = False, name = name)
account.put()
cookie = LOGIN_COOKIE_NAME + '=%s|%s; Expires=%s Path=/' % (str(email), hash_str(email), remember_me())
to_return['cookie'] = cookie
to_return['success'] = True
email_verification(email, name)
return to_return
def email_verification(email, name):
'''Sends a verification email for new user'''
link, dellink = get_unique_link(email)
body, html = make_activation_email(email, link, dellink, name)
try:
mail.send_mail(sender="ClassMatch <classmatch.verify@gmail.com>",
to="%s <%s>" % (name, email + "@bergen.org"),
subject="Email Verification",
body=body,
html=html)
except OverQuotaError:
return
def get_unique_link(email):
'''Creates a verification link for new user'''
reset_user_link(email)
link_row = Email_Verification(email = email)
link_row.put()
return 'http://class-match.appspot.com/verify/' + str(link_row.key()), 'http://class-match.appspot.com/delete_email/' + str(link_row.key())
def reset_user_link(email):
'''Deletes email verification links for user'''
links = db.GqlQuery("SELECT * FROM Email_Verification WHERE email = :email", email = email)
for i in links:
i.delete()
def deleted(key):
'''Wrong email, delete verficiation link'''
link = db.get(key)
if link is None:
return False
GET_USER.bind(email = link.email)
user = GET_USER
if user is None:
return False
memcache.delete(link.email + '_submitted')
link.delete()
for i in user:
i.delete()
return True
def delete_user_account(email):
'''Deletes a user account and all related data (minus comments)'''
GET_USER.bind(email = email)
user = GET_USER.get()
classes = get_classes(email)
for i in classes:
x = Courses.get(i.course_id)
x.students_enrolled.remove(user.name)
x.put()
i.delete()
user.delete()
memcache.delete(email + '_submitted')
def verify(key):
'''Verfies email from verification link'''
link = db.get(key)
if link is None:
return False
if datetime.datetime.now() >= link.date_created + datetime.timedelta(hours=12):
link.delete()
return False
user = get_user(link.email)
if user is None:
return False
user.email_verified = True
user.put()
memcache.delete(link.email + '_submitted')
memcache.delete('user-'+link.email)
link.delete()
return True
def make_activation_email(email, link, ignore_link, name):
html = """
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
Hi %s,<br/><br/>
Thank you for visiting and joining <a href="http://class-match.appspot.com">ClassMatch</a>!<br/><br/><br/>
To verify your email please click this link (or copy and paste it into your browser): <a href="%s">%s</a><br/><br/>
If you did not make an account on ClassMatch click this link: <a href="%s">%s</a>
<br/><br/><br/>
NOTE: Links will expire in 12 hours
</body>
</html>
""" % (name, link, link, ignore_link, ignore_link)
logging.error([link,ignore_link])
body = """Hi %s,
Thank you for visiting and joining ClassMatch (http://class-match.appspot.com)!
To verify your email please click this link (or copy and paste it into your browser): %s
If you did not make an account on ClassMatch click this link: %s
NOTE: Links will expire in 12 hours"""% (name, link, ignore_link)
return body, html
def get_classes(email, cached=True):
courses = memcache.get('courses-' + email)
if courses and cached:
logging.info('CACHE GET_CLASSES: ' + email)
return courses
else:
logging.info('DB GET_CLASSES: ' + email)
courses = db.GqlQuery("SELECT * FROM Schedule WHERE unique_id = :unique_id ORDER BY course DESC", unique_id = email)
memcache.set('courses-' + email, courses)
logging.info('CACHE set courses-' + email)
return courses
# peoples_classes = db.GqlQuery("SELECT * FROM Schedule ORDER BY course DESC")
# return get_user_courses(peoples_classes,email)
def get_user_courses(peoples_classes, email):
user_courses = []
for people in peoples_classes:
if people.unique_id == email:
user_courses.append(people)
return user_courses
def remove_user_course(email,course_name):
course = db.GqlQuery("SELECT * FROM Schedule WHERE unique_id = :email and course = :course_name LIMIT 1", email = email, course_name = course_name).get()
course_from_Courses = Courses.get(course.course_id)
course_from_Courses.students_enrolled.remove(get_name(email))
course_from_Courses.put()
course.delete()
# user_courses = []
# for people in peoples_classes:
# if people.unique_id == email:
# user_courses.append(people)
# if people.course == course_name:
# user_courses.remove(people)
# return user_courses
def list_to_str(lst):
'''Converts a list into a string to put into HTML'''
to_return = '['
for i in lst:
if i == lst[len(lst) - 1]:
to_return += '"' + i + '"]'
else:
to_return += '"' + i + '",'
return to_return
def get_courses_list():
lst = list_to_str(get_all_courses())
if lst == '[':
lst = None
return lst
def get_all_courses():
'''Get all courses'''
lst = memcache.get('all_courses')
if not lst:
all_users = db.GqlQuery("SELECT * FROM Courses")
courses = []
for i in all_users:
# i.course = i.course.encode('utf-8')
notIn = True
for c in courses:
if i.course.lower().strip() == c.lower().strip():
notIn = False
break
if notIn:
courses.append(i.course)
memcache.set('all_courses', courses)
return courses
return lst
def get_course_id(course, mods_monday, mods_tuesday, mods_wed, mods_thursday, mods_friday, email):
retrieved_course = db.GqlQuery("SELECT * FROM Courses\
WHERE course = :course\
AND mods_monday = :mods_monday\
AND mods_tuesday = :mods_tuesday\
AND mods_wed = :mods_wed\
AND mods_thursday = :mods_thursday\
AND mods_friday = :mods_friday\
LIMIT 1",
course = course,
mods_monday = mods_monday,
mods_tuesday = mods_tuesday,
mods_wed = mods_wed,
mods_thursday = mods_thursday,
mods_friday = mods_friday).get()
to_return = ''
if retrieved_course is None:
logging.error(course)
c = Courses(course = course,
mods_monday = mods_monday,
mods_tuesday = mods_tuesday,
mods_wed = mods_wed,
mods_thursday = mods_thursday,
mods_friday = mods_friday,
students_enrolled = [email])
c.put()
to_return = str(c.key())
else:
to_return = str(retrieved_course.key())
return to_return