Repository navigation
Expand file tree
/
Copy pathvalidation_utils.py
More file actions
187 lines (158 loc) · 6.06 KB
/
Copy pathvalidation_utils.py
File metadata and controls
187 lines (158 loc) · 6.06 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
import re
import datetime
import flask
import pymysql.cursors
from hacktech import constants
username_regex = re.compile(r'^[a-z][a-z0-9_-]*$', re.I)
name_regex = re.compile(r"^[a-z][a-z '-]{0,30}[a-z]$", re.I)
uid_regex = re.compile(r'^[0-9]{7}$')
year_regex = re.compile(r'^[0-9]{4}$')
email_regex = re.compile(r'^[a-z0-9\.\_\%\+\-]+@[a-z0-9\.\-]+\.[a-z]+$', re.I)
def validate_username(username, flash_errors=True):
"""
Checks to make sure username is valid. If flash_errors is True, then the
errors will be displayed as flashes. Returns True if valid, else False.
"""
error = None
if len(username) == 0:
error = 'You must provide a username!'
elif len(username) < constants.MIN_USERNAME_LENGTH:
error = 'Username must be at least {0} characters long!'.format(
constants.MIN_USERNAME_LENGTH)
elif len(username) > constants.MAX_USERNAME_LENGTH:
error = 'Username cannot be more than {0} characters long!'.format(
constants.MAX_USERNAME_LENGTH)
elif username_regex.match(username) is None:
error = 'Username may contain only alphanumeric characters, hyphens, or underscores and must begin with a letter.'
else:
# Check if username is already in use.
query = "SELECT 1 FROM users WHERE username = %s"
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, username)
result = cursor.fetchone()
if result is not None:
error = 'Username is already in use!'
if error is not None:
if flash_errors:
flask.flash(error)
return False
return True
def validate_password(password, password2, flash_errors=True):
"""
Checks to make sure a password is valid. password and password2 should be the
values from both times the user enters a password. If you need to check a
password outside of the context of a user setting/changing a password, then
use the same value for both inputs. If flash_errors is set to True, then the
errors will be displayed as flashes.
Returns True if valid, else False.
"""
error = None
if len(password) == 0:
error = 'You must provide a password!'
elif len(password2) == 0:
error = 'You must confirm your password!'
elif password != password2:
error = 'Passwords do not match. Please try again!'
elif len(password) < constants.MIN_PASSWORD_LENGTH:
error = 'Your password must be at least {0} characters long!'.format(
constants.MIN_PASSWORD_LENGTH)
elif len(password) > constants.MAX_PASSWORD_LENGTH:
error = 'Your password cannot be more than {0} characters long!'.format(
constants.MAX_PASSWORD_LENGTH)
if error is not None:
if flash_errors:
flask.flash(error)
return False
return True
def validate_name(name, flash_errors=True):
"""Validates a name. Flashes errors if flash_errors is True."""
# Allow letters, spaces, hyphens, and apostrophes.
# First and last characters must be letters.
if not name_regex.match(name):
if flash_errors:
flask.flash("'{0}' is not a valid name.".format(name))
return False
return True
def validate_uid(uid, flash_errors=True):
"""Validates a UID. Flashes errors if flash_errors is True."""
if not uid_regex.match(uid):
if flash_errors:
flask.flash("'{0}' is not a valid UID.".format(uid))
return False
return True
def check_uid_exists(uid):
"""Returns True if the UID exists in the database."""
if not validate_uid(uid, flash_errors=False):
return False
query = "SELECT 1 FROM members WHERE uid = %s"
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, uid)
result = cursor.fetchone()
return result is not None
def validate_year(year, flash_errors=True):
"""Validates a year. Flashes errors if flash_errors is True."""
# Also check that the year is in the range supported by MySQL's year type.
if year_regex.match(year) \
and int(year) >= 1901 \
and int(year) <= 2155:
return True
if flash_errors:
flask.flash("'{0}' is not a valid year.".format(year))
return False
def validate_email(email, flash_errors=True):
"""Validates an email. Flashes errrors if flash_errors is True."""
if not email_regex.match(email):
if flash_errors:
flask.flash("'{0}' is not a valid email.".format(email))
return False
return True
def validate_date(date, flash_errors=True):
"""
Validates date string. Format should be YYYY-MM-DD. Flashes errors if
flash_errors is True.
"""
try:
datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
if flash_errors:
flask.flash(
'Invalid date provided. Make sure dates are in YYYY-MM-DD format.'
)
return False
return True
def validate_exists(form, param, flash_errors=True):
"""
Validates that the specified parameter exists in the POST data
"""
if param not in form:
if flash_errors:
flask.flash("Missing form parameter: " + param)
return False
return True
def validate_in(value, values, flash_errors=True):
"""
Validates that value is in the iterable values
"""
if value not in values:
if flash_errors:
flask.flash("'" + value + "' not in " + str(values))
return False
return True
def validate_int(int_str, min=None, max=None, flash_errors=True):
"""
Requires that the given string represent an integer
and the integer lies between the bounds (inclusive) if provided
"""
try:
int_value = int(int_str)
except ValueError:
if flash_errors:
flask.flash("Not an integer: '" + int_str + "'")
return False
if not ((min is None or min <= int_value) and
(max is None or int_value <= max)):
if flash_errors:
flask.flash("Not between " + str(min) + " and " + str(max) + ": " +
int_str)
return False
return True