-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserschema.py
More file actions
407 lines (371 loc) · 14.4 KB
/
Copy pathuserschema.py
File metadata and controls
407 lines (371 loc) · 14.4 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
from marshmallow import ValidationError, post_dump, pre_load, validate
from marshmallow.fields import Nested
from marshmallow_sqlalchemy import field_for
from sqlalchemy.orm import load_only
from CTFd.models import Brackets, UserFieldEntries, UserFields, Users, ma
from CTFd.schemas.fields import UserFieldEntriesSchema
from CTFd.utils import get_config, string_types
from CTFd.utils.crypto import verify_password
from CTFd.utils.email import check_email_is_whitelisted
from CTFd.utils.user import get_current_user, is_admin
from CTFd.utils.validators import validate_country_code, validate_language
class UserSchema(ma.ModelSchema):
class Meta:
model = Users
include_fk = True
dump_only = ("id", "oauth_id", "created", "team_id")
load_only = ("password",)
name = field_for(
Users,
"name",
required=True,
allow_none=False,
validate=[
validate.Length(min=1, max=128, error="User names must not be empty")
],
)
email = field_for(
Users,
"email",
allow_none=False,
validate=[
validate.Email("Emails must be a properly formatted email address"),
validate.Length(min=1, max=128, error="Emails must not be empty"),
],
)
website = field_for(
Users,
"website",
validate=[
# This is a dirty hack to let website accept empty strings so you can remove your website
lambda website: validate.URL(
error="Websites must be a proper URL starting with http or https",
schemes={"http", "https"},
)(website)
if website
else True
],
)
subscription_level = field_for(Users, "subscription_level")
language = field_for(Users, "language", validate=[validate_language])
country = field_for(Users, "country", validate=[validate_country_code])
password = field_for(Users, "password", required=True, allow_none=False)
bracket_id = field_for(Users, "bracket_id")
fields = Nested(
UserFieldEntriesSchema, partial=True, many=True, attribute="field_entries"
)
@pre_load
def validate_name(self, data):
name = data.get("name")
if name is None:
return
name = name.strip()
existing_user = Users.query.filter_by(name=name).first()
current_user = get_current_user()
if is_admin():
user_id = data.get("id")
if user_id:
if existing_user and existing_user.id != user_id:
raise ValidationError(
"User name has already been taken", field_names=["name"]
)
else:
if existing_user:
if current_user:
if current_user.id != existing_user.id:
raise ValidationError(
"User name has already been taken", field_names=["name"]
)
else:
raise ValidationError(
"User name has already been taken", field_names=["name"]
)
else:
if name == current_user.name:
return data
else:
name_changes = get_config("name_changes", default=True)
if bool(name_changes) is False:
raise ValidationError(
"Name changes are disabled", field_names=["name"]
)
if existing_user:
raise ValidationError(
"User name has already been taken", field_names=["name"]
)
@pre_load
def validate_email(self, data):
email = data.get("email")
if email is None:
return
email = email.strip()
existing_user = Users.query.filter_by(email=email).first()
current_user = get_current_user()
if is_admin():
user_id = data.get("id")
if user_id:
if existing_user and existing_user.id != user_id:
raise ValidationError(
"Email address has already been used", field_names=["email"]
)
else:
if existing_user:
if current_user:
if current_user.id != existing_user.id:
raise ValidationError(
"Email address has already been used",
field_names=["email"],
)
else:
raise ValidationError(
"Email address has already been used", field_names=["email"]
)
else:
if email == current_user.email:
return data
else:
confirm = data.get("confirm")
if bool(confirm) is False:
raise ValidationError(
"Please confirm your current password", field_names=["confirm"]
)
test = verify_password(
plaintext=confirm, ciphertext=current_user.password
)
if test is False:
raise ValidationError(
"Your previous password is incorrect", field_names=["confirm"]
)
if existing_user:
raise ValidationError(
"Email address has already been used", field_names=["email"]
)
if check_email_is_whitelisted(email) is False:
raise ValidationError(
"Email address is not from an allowed domain",
field_names=["email"],
)
if get_config("verify_emails"):
current_user.verified = False
@pre_load
def validate_password_confirmation(self, data):
password = data.get("password")
confirm = data.get("confirm")
target_user = get_current_user()
if is_admin():
pass
else:
# If the user has no password set, allow them to set their password
if target_user.password is None:
return
if password and (bool(confirm) is False):
raise ValidationError(
"Please confirm your current password", field_names=["confirm"]
)
if password and confirm:
test = verify_password(
plaintext=confirm, ciphertext=target_user.password
)
if test is True:
return data
else:
raise ValidationError(
"Your previous password is incorrect", field_names=["confirm"]
)
else:
data.pop("password", None)
data.pop("confirm", None)
@pre_load
def validate_bracket_id(self, data):
bracket_id = data.get("bracket_id")
if is_admin():
bracket = Brackets.query.filter_by(id=bracket_id, type="users").first()
if bracket is None:
ValidationError(
"Please provide a valid bracket id", field_names=["bracket_id"]
)
else:
current_user = get_current_user()
# Users are not allowed to switch their bracket
if bracket_id is None:
# Remove bracket_id and short circuit processing
data.pop("bracket_id", None)
return
if (
current_user.bracket_id == int(bracket_id)
or current_user.bracket_id is None
):
bracket = Brackets.query.filter_by(id=bracket_id, type="users").first()
if bracket is None:
ValidationError(
"Please provide a valid bracket id", field_names=["bracket_id"]
)
else:
raise ValidationError(
"Please contact an admin to change your bracket",
field_names=["bracket_id"],
)
@pre_load
def validate_fields(self, data):
"""
This validator is used to only allow users to update the field entry for their user.
It's not possible to exclude it because without the PK Marshmallow cannot load the right instance
"""
fields = data.get("fields")
if fields is None:
return
current_user = get_current_user()
if is_admin():
user_id = data.get("id")
if user_id:
target_user = Users.query.filter_by(id=data["id"]).first()
else:
target_user = current_user
# We are editting an existing user
if self.view == "admin" and self.instance:
target_user = self.instance
provided_ids = []
for f in fields:
f.pop("id", None)
field_id = f.get("field_id")
# # Check that we have an existing field for this. May be unnecessary b/c the foriegn key should enforce
field = UserFields.query.filter_by(id=field_id).first_or_404()
# Get the existing field entry if one exists
entry = UserFieldEntries.query.filter_by(
field_id=field.id, user_id=target_user.id
).first()
if entry:
f["id"] = entry.id
provided_ids.append(entry.id)
# Extremely dirty hack to prevent deleting previously provided data.
# This needs a better soln.
entries = (
UserFieldEntries.query.options(load_only("id"))
.filter_by(user_id=target_user.id)
.all()
)
for entry in entries:
if entry.id not in provided_ids:
fields.append({"id": entry.id})
else:
provided_ids = []
for f in fields:
# Remove any existing set
f.pop("id", None)
field_id = f.get("field_id")
value = f.get("value")
# # Check that we have an existing field for this. May be unnecessary b/c the foriegn key should enforce
field = UserFields.query.filter_by(id=field_id).first_or_404()
# Get the existing field entry if one exists
entry = UserFieldEntries.query.filter_by(
field_id=field.id, user_id=current_user.id
).first()
if field.required is True:
if isinstance(value, str):
if value.strip() == "":
raise ValidationError(
f"Field '{field.name}' is required",
field_names=["fields"],
)
if field.editable is False and entry is not None:
raise ValidationError(
f"Field '{field.name}' cannot be editted",
field_names=["fields"],
)
if entry:
f["id"] = entry.id
provided_ids.append(entry.id)
# Extremely dirty hack to prevent deleting previously provided data.
# This needs a better soln.
entries = (
UserFieldEntries.query.options(load_only("id"))
.filter_by(user_id=current_user.id)
.all()
)
for entry in entries:
if entry.id not in provided_ids:
fields.append({"id": entry.id})
@post_dump
def process_fields(self, data):
"""
Handle permissions levels for fields.
This is post_dump to manipulate JSON instead of the raw db object
Admins can see all fields.
Users (self) can see their edittable and public fields
Public (user) can only see public fields
"""
# Gather all possible fields
removed_field_ids = []
fields = UserFields.query.all()
# Select fields for removal based on current view and properties of the field
for field in fields:
if self.view == "user":
if field.public is False:
removed_field_ids.append(field.id)
elif self.view == "self":
if field.editable is False and field.public is False:
removed_field_ids.append(field.id)
# Rebuild fuilds
fields = data.get("fields")
if fields:
data["fields"] = [
field for field in fields if field["field_id"] not in removed_field_ids
]
views = {
"user": [
"website",
"name",
"subscription_level",
"country",
"affiliation",
"bracket_id",
"id",
"oauth_id",
"fields",
"team_id",
],
"self": [
"website",
"name",
"email",
"language",
"subscription_level",
"country",
"affiliation",
"bracket_id",
"id",
"oauth_id",
"password",
"fields",
"team_id",
],
"admin": [
"website",
"name",
"created",
"subscription_level",
"country",
"banned",
"email",
"language",
"affiliation",
"secret",
"bracket_id",
"hidden",
"id",
"oauth_id",
"password",
"type",
"verified",
"fields",
"team_id",
],
}
def __init__(self, view=None, *args, **kwargs):
if view:
if isinstance(view, string_types):
kwargs["only"] = self.views[view]
elif isinstance(view, list):
kwargs["only"] = view
self.view = view
super(UserSchema, self).__init__(*args, **kwargs)