schemas.py 16.2 KB
Newer Older
Peter Stanko's avatar
Peter Stanko committed
1
2
3
"""
Schemas used to serialize/deserialize and validate of the models in the DB
"""
Peter Stanko's avatar
Peter Stanko committed
4
5
import functools

Peter Stanko's avatar
Peter Stanko committed
6
from marshmallow import Schema, ValidationError, fields, validates_schema
7
8
from marshmallow_enum import EnumField

Peter Stanko's avatar
Peter Stanko committed
9
from portal.database.models import ClientType, ProjectState, SubmissionState, WorkerState
Barbora Kompišová's avatar
Barbora Kompišová committed
10

11

12
class NestedCollection:
Peter Stanko's avatar
Peter Stanko committed
13
14
15
16
17
18
19
20
21
22
23
    ENTITIES = {
        'Role': ('id', 'codename', 'course.id'),
        'Group': ('id', 'codename', 'course.id'),
        'Project': ('id', 'codename', 'course.id'),
        'Course': ('id', 'codename'),
        'User': ('id', 'username', 'uco', 'codename'),
        'Worker': ('id', 'codename', 'name'),
        'Client': ('id', 'type', 'name', 'codename'),
        'Component': ('id', 'name', 'type'),
        'Submission': ('id', 'state', 'user.id', 'user.username',
                       'project.id', 'project.codename',
24
                       'course.id', 'course.codename',
Peter Stanko's avatar
Peter Stanko committed
25
26
27
28
29
                       'created_at', 'updated_at'),
        'ReviewItem': ('id', 'review.id', 'line', 'content', 'file', 'user.id'),
        'Secret': ('id', 'name', 'expires_at')
    }

30
31
32
    def __init__(self, mod_name):
        self.mod_name = mod_name
        self.collection = {}
Peter Stanko's avatar
Peter Stanko committed
33
        self.__build_nested()
34
35
36
37
38
39
40
41

    def class_path(self, schema_name: str):
        return f'{self.mod_name}.{schema_name}Schema'

    def __call__(self, *args, **kwargs):
        return self.nested(*args, **kwargs)

    def nested(self, schema_name, *args, only=None, **kwargs):
Peter Stanko's avatar
Peter Stanko committed
42
43
44
45
46
47
48
49
50
        params = []
        if only:
            params.extend(only)
        if args:
            params.extend(args)
        other = {**kwargs}
        if params:
            other['only'] = params
        return fields.Nested(self.class_path(schema_name), **other)
51
52
53
54

    def _set_nested(self, schema_name: str, params, many=False):
        lower = schema_name.lower()
        if many:
Peter Stanko's avatar
Peter Stanko committed
55
            lower = lower + 's'
Peter Stanko's avatar
Peter Stanko committed
56
        self.collection[lower] = self.nested(schema_name, *params, many=many)
57
58
59

    def _set_nested_and_list(self, schema_name, params):
        self._set_nested(schema_name=schema_name, params=params)
Peter Stanko's avatar
Peter Stanko committed
60
        # List version
61
62
63
        self._set_nested(schema_name=schema_name, params=params, many=True)

    def __build_nested(self):
Peter Stanko's avatar
Peter Stanko committed
64
        for (name, params) in self.entities.items():
65
66
67
68
            self._set_nested_and_list(name, params=params)

    @property
    def entities(self):
Peter Stanko's avatar
Peter Stanko committed
69
        return self.__class__.ENTITIES
70
71
72
73
74
75
76
77
78
79
80

    def get(self, name):
        return self.collection[name]

    def __getitem__(self, item):
        return self.get(item)


NESTED = NestedCollection(__name__)


Peter Stanko's avatar
Peter Stanko committed
81
# pylint: disable=too-few-public-methods
82
83
84
85
86
87
class BaseSchema(object):
    id = fields.Str(dump_only=True, required=True)
    created_at = fields.LocalDateTime()
    updated_at = fields.LocalDateTime()


Peter Stanko's avatar
Peter Stanko committed
88
89
90
91
92
93
class NamedSchema(object):
    name = fields.Str(required=True)
    codename = fields.Str(required=True)
    description = fields.Str(required=False, allow_none=True)


94
class UserSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
95
96
    """User schema
    """
97
98
    uco = fields.Int(required=True)
    email = fields.Email(required=True)
99
    username = fields.Str(required=True)
100
    name = fields.Str()
101
    codename = fields.Str()
Peter Stanko's avatar
Peter Stanko committed
102
    type = fields.Str()
103
    is_admin = fields.Bool(default=False, missing=False)
Peter Stanko's avatar
Peter Stanko committed
104
105
106
107
    submissions = NESTED['submissions']
    review_items = NESTED['reviewitems']
    roles = NESTED['roles']
    groups = NESTED['groups']
108
109
110


class PasswordChangeSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
111
112
    """Password Change Schema
    """
113
114
115
116
    old_password = fields.String()
    new_password = fields.String(required=True)


Peter Stanko's avatar
Peter Stanko committed
117
class CourseSchema(BaseSchema, NamedSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
118
119
    """Course Schema
    """
120
121
122
    roles = NESTED['roles']
    groups = NESTED['groups']
    projects = NESTED['projects']
123
124
125


class SubmissionFileSourceSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
126
127
    """Submissions File Source Schema
    """
Peter Stanko's avatar
Peter Stanko committed
128
    type = fields.Str(required=True)
Peter Stanko's avatar
Peter Stanko committed
129
130
    url = fields.Str(allow_none=True)  # git@gitlab.fi.muni.cz:foo/project.git
    branch = fields.Str(allow_none=True)
131
132
133
134
135
136
137
138
139
140
141
    checkout = fields.Str()

    @validates_schema
    def validate_present_fields(self, data):
        if data.get('type') is None:
            raise ValidationError(
                f"Submission source type is required. Supported values: 'git', 'zip'.")
        if data['type'] not in ('git', 'zip'):
            raise ValidationError(
                f"Submission source unsupported: {data['type']}. Supported sources: git, zip.")
        if data['type'] == 'git':
Peter Stanko's avatar
Peter Stanko committed
142
143
            if any(key not in data.keys()
                   for key in ['url', 'branch', 'checkout']):
144
                raise ValidationError(
Peter Stanko's avatar
Peter Stanko committed
145
                    f"File source 'git' require precisely 'url', "
146
                    f"'branch' and 'checkout' attributes."
147
                )
148
        if data['type'] == 'zip':
Peter Stanko's avatar
Peter Stanko committed
149
150
151
152
            if any(key in data.keys()
                   for key in ['url', 'branch', 'checkout']):
                raise ValidationError(
                    f"File source 'zip' does not require any other attributes.")
153
154


Peter Stanko's avatar
Peter Stanko committed
155
156
157
158
class SubmissionFileParamsSchema(Schema):
    """Submission File Params Schema
    """
    source = NESTED('SubmissionFileSource', required=True)
Peter Stanko's avatar
Peter Stanko committed
159
    from_dir = fields.Str(allow_none=True)
Peter Stanko's avatar
Peter Stanko committed
160
161


162
class SubmissionCreateSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
163
164
    """Submission Create Schema
    """
Peter Stanko's avatar
Peter Stanko committed
165
    file_params = NESTED('SubmissionFileParams', required=True)
Peter Stanko's avatar
Peter Stanko committed
166
    project_params = fields.Dict(required=False, allow_none=True)
167
168


Peter Stanko's avatar
Peter Stanko committed
169
class ProjectSchema(BaseSchema, NamedSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
170
171
    """Project Schema
    """
172
    assignment_url = fields.Str(required=False, allow_none=True)
Peter Stanko's avatar
Peter Stanko committed
173
174
175
    config = NESTED('ProjectConfig',
                    exclude=('id', '_submissions_allowed_from',
                             '_submissions_allowed_to', '_archive_from'))
176
    state = EnumField(ProjectState)
177
178
179
    course = NESTED['course']
    submissions = NESTED['submissions']
    groups = NESTED['groups']
180

181

182
class ProjectConfigSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
183
184
    """Project config Schema
    """
185
    project = NESTED['project']
186
187
    submissions_cancellation_period = fields.Number(allow_none=True)
    test_files_source = fields.Str(allow_none=True)
Peter Stanko's avatar
Peter Stanko committed
188
    test_files_subdir = fields.Str(allow_none=True)
189
190
191
192
193
194
195
196
    file_whitelist = fields.Str(allow_none=True)
    pre_submit_script = fields.Str(allow_none=True)
    post_submit_script = fields.Str(allow_none=True)
    submission_parameters = fields.Str(allow_none=True)
    submission_scheduler_config = fields.Str(allow_none=True)
    submissions_allowed_from = fields.LocalDateTime(allow_none=True)
    submissions_allowed_to = fields.LocalDateTime(allow_none=True)
    archive_from = fields.LocalDateTime(allow_none=True)
197
198


Peter Stanko's avatar
Peter Stanko committed
199
class RoleSchema(BaseSchema, NamedSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
200
201
    """Role Schema
    """
Barbora Kompisova's avatar
Barbora Kompisova committed
202
    clients = NESTED['clients']
203
    course = NESTED['course']
Peter Stanko's avatar
Peter Stanko committed
204
205
    # this could be done prettier (e.g. flattening the structure, showing only
    # set fields)
Peter Stanko's avatar
Peter Stanko committed
206
    permissions = NESTED("RolePermissions")
207
208


Barbora Kompisova's avatar
Barbora Kompisova committed
209
class ClientSchema(BaseSchema, Schema):
Peter Stanko's avatar
Peter Stanko committed
210
    type = EnumField(ClientType, by_value=True)
Barbora Kompisova's avatar
Barbora Kompisova committed
211
212


213
class RolePermissionsSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
214
215
    """Role Permissions Schema
    """
216
    role = NESTED['role']
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    view_course_limited = fields.Bool()
    view_course_full = fields.Bool()
    update_course = fields.Bool()
    handle_notes_access_token = fields.Bool()

    assign_roles = fields.Bool()
    write_roles = fields.Bool()
    read_roles = fields.Bool()

    write_groups = fields.Bool()
    read_groups = fields.Bool()

    write_projects = fields.Bool()
    read_projects = fields.Bool()
    archive_projects = fields.Bool()

    create_submissions = fields.Bool()
234
    create_submissions_other = fields.Bool()
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
    resubmit_submissions = fields.Bool()
    evaluate_submissions = fields.Bool()

    read_submissions_all = fields.Bool()
    read_submissions_groups = fields.Bool()
    read_submissions_own = fields.Bool()
    read_all_submission_files = fields.Bool()

    read_reviews_all = fields.Bool()
    read_reviews_groups = fields.Bool()
    read_reviews_own = fields.Bool()

    write_reviews_all = fields.Bool()
    write_reviews_group = fields.Bool()
    write_reviews_own = fields.Bool()


Peter Stanko's avatar
Peter Stanko committed
252
class GroupSchema(BaseSchema, NamedSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
253
254
    """Group Schema
    """
255
256
257
    course = NESTED['course']
    users = NESTED['users']
    projects = NESTED['projects']
258
259


260
class SubmissionSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
261
262
    """Submission Schema
    """
263
264
265
266
    note = fields.Str()
    state = EnumField(SubmissionState)
    scheduled_for = fields.LocalDateTime()
    parameters = fields.Dict()
267
    project = NESTED['project']
268
    course = NESTED['course']
269
    user = NESTED['user']
270
271


272
class ReviewSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
273
274
    """Review Schema
    """
275
276
    submission = NESTED['submission']
    review_items = NESTED['reviewitems']
277
278


279
class ReviewItemSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
280
281
    """Review Item Schema
    """
282
283
284
    content = fields.Str()
    file = fields.Str()
    line = fields.Int()
Peter Stanko's avatar
Peter Stanko committed
285
    review = NESTED('Review', only=('id',))
286
    user = NESTED['user']
287
288


Barbora Kompišová's avatar
Barbora Kompišová committed
289
class WorkerSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
290
291
    """Component Schema
    """
292
    name = fields.Str()
293
    codename = fields.Str(allow_none=True)
Peter Stanko's avatar
Peter Stanko committed
294
    type = fields.Str()
Peter Stanko's avatar
Peter Stanko committed
295
296
297
    url = fields.Str(allow_none=True)
    tags = fields.Str(allow_none=True)
    portal_secret = fields.Str(allow_none=True)
Peter Stanko's avatar
Peter Stanko committed
298
    state = EnumField(WorkerState, by_value=True)
Barbora Kompišová's avatar
Barbora Kompišová committed
299
300


301
class SecretSchema(BaseSchema, Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
302
303
304
    """Secret schema
    """
    name = fields.Str()
305
    expires_at = fields.LocalDateTime(allow_none=True)
Barbora Kompišová's avatar
Barbora Kompišová committed
306
    client = NESTED['client']
307
308
309


class CourseImportConfigSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
310
311
    """Course Import Config Schema
    """
312
313
314
315
316
317
    roles = fields.Str()
    groups = fields.Str()
    projects = fields.Str()


class CourseImportSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
318
319
    """Course Import Schema
    """
320
    source_course = fields.Str(required=True)
Peter Stanko's avatar
Peter Stanko committed
321
    config = NESTED('CourseImportConfig', required=True)
322
323


Barbora Kompisova's avatar
Barbora Kompisova committed
324
class ClientListUpdateSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
325
326
    """User List Update Schema
    """
327
328
329
330
331
    add = fields.List(fields.Str())
    remove = fields.List(fields.Str())


class GroupImportSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
332
333
    """Group Import Schema
    """
334
335
336
337
338
    source_course = fields.Str()
    source_group = fields.Str()
    with_users = fields.Str()


Peter Stanko's avatar
Peter Stanko committed
339
340
341
342
343
344
345
346
347
348
349
class RoleImportSchema(Schema):
    source_course = fields.Str()
    source_role = fields.Str()
    with_users = fields.Str()


class ProjectImportSchema(Schema):
    source_course = fields.Str()
    source_project = fields.Str()


350
class SubmissionResultTemplateSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
351
352
    """Submission Result Template Schema
    """
353
354
355
356
357
358
    template = fields.Str(required=True)
    role = fields.Str()
    user = fields.Str()


class SubmissionResultSchema(Schema):
Barbora Kompišová's avatar
Barbora Kompišová committed
359
360
    """Submission Result Schema
    """
361
362
363
    data = fields.Dict(required=True)
    templates = fields.List(
        fields.Nested(SubmissionResultTemplateSchema, required=True)
364
    )
365
366


Peter Stanko's avatar
Peter Stanko committed
367
368
# pylint: enable=too-few-public-methods

Peter Stanko's avatar
Peter Stanko committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

def fn_name(func):
    @functools.wraps(func)
    def __wrap(*args, **kwargs):
        return func(*args, select_params=func.__name__, **kwargs)

    return __wrap


class Schemas:
    ALWAYS_ALLOWED = ['updated_at', 'created_at', 'id']
    CODENAME_W_DESC = [*ALWAYS_ALLOWED, 'name', 'codename', 'description']
    ENT_W_COURSE = (*CODENAME_W_DESC, 'course')
    PARAMS = {
        'user_reduced': (*ALWAYS_ALLOWED, 'username', 'uco', 'email', 'name'),
        'users': (*ALWAYS_ALLOWED, 'username', 'uco', 'email'),
385
        'submissions': (*ALWAYS_ALLOWED, 'course', 'state', 'project', 'scheduled_for', 'user'),
Peter Stanko's avatar
Peter Stanko committed
386
        'submission_state': (*ALWAYS_ALLOWED, 'state', 'parameters', 'scheduled_for'),
Peter Stanko's avatar
Peter Stanko committed
387
388
389
390
391
392
393
        'roles': ENT_W_COURSE,
        'groups': ENT_W_COURSE,
        'projects': ENT_W_COURSE,
        'course_reduced': (*CODENAME_W_DESC,),
        'courses': (*CODENAME_W_DESC,),
        'config_reduced': (*ALWAYS_ALLOWED, 'project', 'submissions_allowed_from',
                           'submissions_allowed_to', 'file_whitelist'),
Barbora Kompišová's avatar
Barbora Kompišová committed
394
395
        'secrets': (*ALWAYS_ALLOWED, 'name', 'expires_at', 'client.id', 'client.type', 'client.name', 'client.codename'),
        'secret': (*ALWAYS_ALLOWED, 'name', 'expires_at', 'client.id', 'client.type', 'client.name', 'client.codename')
Peter Stanko's avatar
Peter Stanko committed
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
    }

    def __get_schema(self, schema_klass, select_params=None, only=None, strict=True, **kwargs):
        if only is None:
            only = self._select_params(select_params)
        params = {'strict': strict, **kwargs}
        if only is not None:
            params['only'] = only
        return schema_klass(**params)

    def _select_params(self, select_params):
        return self.__class__.PARAMS.get(select_params)

    @fn_name
    def user(self, **kwargs):
        return self.__get_schema(UserSchema, **kwargs)

    @fn_name
    def users(self, **kwargs):
        return self.__get_schema(UserSchema, many=True, **kwargs)

    @fn_name
    def user_reduced(self, **kwargs):
        return self.__get_schema(UserSchema, **kwargs)

    @fn_name
    def password_change(self, **kwargs):
        return self.__get_schema(PasswordChangeSchema, **kwargs)

    @fn_name
    def submission(self, **kwargs):
        return self.__get_schema(SubmissionSchema, **kwargs)

    @fn_name
    def submissions(self, **kwargs):
        return self.__get_schema(SubmissionSchema, many=True, **kwargs)

    @fn_name
    def submission_create(self, **kwargs):
        return self.__get_schema(SubmissionCreateSchema, strict=False, **kwargs)

    @fn_name
    def submission_state(self, **kwargs):
        return self.__get_schema(SubmissionSchema, **kwargs)

    @fn_name
    def reviews(self, **kwargs):
        return self.__get_schema(ReviewSchema, many=True, **kwargs)

    @fn_name
    def review(self, **kwargs):
        return self.__get_schema(ReviewSchema, **kwargs)

    @fn_name
    def courses(self, **kwargs):
        return self.__get_schema(CourseSchema, many=True, **kwargs)

    @fn_name
    def course(self, **kwargs):
        return self.__get_schema(CourseSchema, **kwargs)

    @fn_name
    def course_reduced(self, **kwargs):
        return self.__get_schema(CourseSchema, **kwargs)

    @fn_name
    def roles(self, **kwargs):
        return self.__get_schema(RoleSchema, many=True, **kwargs)

    @fn_name
    def role(self, **kwargs):
        return self.__get_schema(RoleSchema, **kwargs)

    @fn_name
    def group(self, **kwargs):
        return self.__get_schema(GroupSchema, **kwargs)

    @fn_name
    def groups(self, **kwargs):
        return self.__get_schema(GroupSchema, many=True, **kwargs)

    @fn_name
    def project(self, **kwargs):
        return self.__get_schema(ProjectSchema, **kwargs)

    @fn_name
    def projects(self, **kwargs):
        return self.__get_schema(ProjectSchema, many=True, **kwargs)

    @fn_name
    def permissions(self, **kwargs):
        return self.__get_schema(RolePermissionsSchema, **kwargs)

    @fn_name
    def config(self, **kwargs):
        return self.__get_schema(ProjectConfigSchema, **kwargs)

    @fn_name
    def config_reduced(self, **kwargs) -> ProjectConfigSchema:
        return self.__get_schema(ProjectConfigSchema, **kwargs)

    @fn_name
    def client_list_update(self, **kwargs) -> ClientListUpdateSchema:
        return self.__get_schema(ClientListUpdateSchema, **kwargs)

    @fn_name
    def group_import(self, **kwargs) -> GroupImportSchema:
        return self.__get_schema(GroupImportSchema, **kwargs)

    @fn_name
    def role_import(self, **kwargs) -> RoleImportSchema:
        return self.__get_schema(RoleImportSchema, **kwargs)

    @fn_name
    def project_import(self, **kwargs) -> ProjectImportSchema:
        return self.__get_schema(ProjectImportSchema, **kwargs)

    @fn_name
    def course_import(self, **kwargs) -> CourseImportSchema:
        return self.__get_schema(CourseImportSchema, **kwargs)

    @fn_name
    def worker(self, **kwargs) -> ProjectImportSchema:
        return self.__get_schema(WorkerSchema, **kwargs)

    @fn_name
    def workers(self, **kwargs) -> WorkerSchema:
        return self.__get_schema(WorkerSchema, many=True, **kwargs)

    @fn_name
    def submission_result(self, **kwargs) -> SubmissionResultSchema:
        return self.__get_schema(SubmissionResultSchema, **kwargs)

    @fn_name
    def secret(self, **kwargs) -> SecretSchema:
        return self.__get_schema(SecretSchema, **kwargs)

    @fn_name
    def secrets(self, **kwargs) -> SecretSchema:
        return self.__get_schema(SecretSchema, many=True, **kwargs)

    def dump(self, schema_name: str, obj: object) -> dict:
        schema: Schema = getattr(self, schema_name)()
        return schema.dump(obj)[0]


SCHEMAS = Schemas()