Skip to content

Commit

Permalink
Add PrairieTest integration
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Sep 13, 2024
1 parent 5a179dd commit 19f7eaf
Show file tree
Hide file tree
Showing 15 changed files with 823 additions and 11 deletions.
2 changes: 1 addition & 1 deletion .ci/run-mypy.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#! /bin/bash

mypy relate course accounts
mypy relate course accounts prairietest
15 changes: 11 additions & 4 deletions course/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@
THE SOFTWARE.
"""

from typing import Any
from typing import TYPE_CHECKING, Any

from django import forms
from django.contrib import admin
from django.db.models import QuerySet
from django.utils.translation import gettext_lazy as _, pgettext

from course.constants import exam_ticket_states, participation_permission as pperm
Expand Down Expand Up @@ -56,9 +57,13 @@
from relate.utils import string_concat


if TYPE_CHECKING:
from accounts.models import User


# {{{ permission helpers

def _filter_courses_for_user(queryset, user):
def _filter_courses_for_user(queryset: QuerySet, user: User) -> QuerySet:
if user.is_superuser:
return queryset
z = queryset.filter(
Expand All @@ -67,7 +72,7 @@ def _filter_courses_for_user(queryset, user):
return z


def _filter_course_linked_obj_for_user(queryset, user):
def _filter_course_linked_obj_for_user(queryset: QuerySet, user: User) -> QuerySet:
if user.is_superuser:
return queryset
return queryset.filter(
Expand All @@ -76,7 +81,9 @@ def _filter_course_linked_obj_for_user(queryset, user):
)


def _filter_participation_linked_obj_for_user(queryset, user):
def _filter_participation_linked_obj_for_user(
queryset: QuerySet, user: User
) -> QuerySet:
if user.is_superuser:
return queryset
return queryset.filter(
Expand Down
33 changes: 27 additions & 6 deletions course/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
parse_date_spec,
)
from course.page.base import PageBase, PageContext
from prairietest.utils import has_access_to_exam
from relate.utils import (
RelateHttpRequest,
not_none,
Expand Down Expand Up @@ -164,6 +163,8 @@ def _eval_generic_conditions(
now_datetime: datetime.datetime,
flow_id: str,
login_exam_ticket: ExamTicket | None,
*,
remote_ip_address: IPv4Address | IPv6Address | None = None,
) -> bool:

if hasattr(rule, "if_before"):
Expand All @@ -189,6 +190,22 @@ def _eval_generic_conditions(
if login_exam_ticket.exam.flow_id != flow_id:
return False

if hasattr(rule, "if_has_prairietest_exam_access"):
if remote_ip_address is None:
return False
if participation is None:
return False

from prairietest.utils import has_access_to_exam
if not has_access_to_exam(
course,
participation.user.email,
rule.if_has_prairietest_exam_access,
now_datetime,
remote_ip_address,
):
return False

return True


Expand Down Expand Up @@ -313,7 +330,8 @@ def get_session_start_rule(
for rule in rules:
if not _eval_generic_conditions(rule, course, participation,
now_datetime, flow_id=flow_id,
login_exam_ticket=login_exam_ticket):
login_exam_ticket=login_exam_ticket,
remote_ip_address=remote_ip_address):
continue

if not _eval_participation_tags_conditions(rule, participation):
Expand Down Expand Up @@ -401,9 +419,11 @@ def get_session_access_rule(

for rule in rules:
if not _eval_generic_conditions(
rule, session.course, session.participation,
now_datetime, flow_id=session.flow_id,
login_exam_ticket=login_exam_ticket):
rule, session.course, session.participation,
now_datetime, flow_id=session.flow_id,
login_exam_ticket=login_exam_ticket,
remote_ip_address=remote_ip_address,
):
continue

if not _eval_participation_tags_conditions(rule, session.participation):
Expand Down Expand Up @@ -1050,7 +1070,7 @@ class FacilityFindingMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
def __call__(self, request: http.HttpRequest) -> http.HttpResponse:
pretend_facilities = request.session.get("relate_pretend_facilities")

if pretend_facilities is not None:
Expand All @@ -1071,6 +1091,7 @@ def __call__(self, request):
if remote_address in ip_network(str(ir)):
facilities.add(name)

request = cast(RelateHttpRequest, request)
request.relate_facilities = frozenset(facilities)

return self.get_response(request)
Expand Down
2 changes: 2 additions & 0 deletions course/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ def validate_session_start_rule(
("if_has_fewer_sessions_than", int),
("if_has_fewer_tagged_sessions_than", int),
("if_signed_in_with_matching_exam_ticket", bool),
("if_has_prairietest_exam_access", str),
("tag_session", (str, type(None))),
("may_start_new_session", bool),
("may_list_existing_sessions", bool),
Expand Down Expand Up @@ -673,6 +674,7 @@ def validate_session_access_rule(
("if_expiration_mode", str),
("if_session_duration_shorter_than_minutes", (int, float)),
("if_signed_in_with_matching_exam_ticket", bool),
("if_has_prairietest_exam_access", str),
("message", str),
]
)
Expand Down
Empty file added prairietest/__init__.py
Empty file.
113 changes: 113 additions & 0 deletions prairietest/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2024 University of Illinois Board of Trustees"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from typing import TYPE_CHECKING

from django import forms, http
from django.contrib import admin
from django.db.models import QuerySet

from accounts.models import User
from course.constants import participation_permission as pperm
from prairietest.models import AllowEvent, DenyEvent, Facility, MostRecentDenyEvent


if TYPE_CHECKING:
from accounts.models import User


class FacilityAdminForm(forms.ModelForm):
class Meta:
model = Facility
fields = "__all__"
widgets = {
"secret": forms.PasswordInput,
}


@admin.register(Facility)
class FacilityAdmin(admin.ModelAdmin):
def get_queryset(self, request: http.HttpRequest) -> QuerySet:
assert request.user.is_authenticated

qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
from course.admin import _filter_course_linked_obj_for_user
return _filter_course_linked_obj_for_user(qs, request.user)

list_display = ["identifier", "course"]
list_filter = ["identifier", "course"]

form = FacilityAdminForm


def _filter_events_for_user(queryset: QuerySet, user: User) -> QuerySet:
if user.is_superuser:
return queryset
return queryset.filter(
test_facility__course__participations__user=user,
test_facility__course__participations__roles__permissions__permission=pperm.use_admin_interface)


@admin.register(AllowEvent)
class AllowEventAdmin(admin.ModelAdmin):
def get_queryset(self, request: http.HttpRequest) -> QuerySet:
assert request.user.is_authenticated

qs = super().get_queryset(request)
return _filter_events_for_user(qs, request.user)

list_display = [
"event_id", "test_facility", "user_uid", "start", "end", "exam_uuid"]
list_filter = ["test_facility", "user_uid", "exam_uuid"]


@admin.register(DenyEvent)
class DenyEventAdmin(admin.ModelAdmin):
def get_queryset(self, request: http.HttpRequest) -> QuerySet:
assert request.user.is_authenticated

qs = super().get_queryset(request)
return _filter_events_for_user(qs, request.user)

list_display = [
"event_id", "test_facility", "start", "end", "deny_uuid"]
list_filter = ["test_facility"]


@admin.register(MostRecentDenyEvent)
class MostRecentDenyEventAdmin(admin.ModelAdmin):
def get_queryset(self, request: http.HttpRequest) -> QuerySet:
assert request.user.is_authenticated

qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(
event__test_facility__course__participations__user=request.user,
event__test_facility__course__participations__roles__permissions__permission=pperm.use_admin_interface)

list_display = ["deny_uuid"]
93 changes: 93 additions & 0 deletions prairietest/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Generated by Django 5.1 on 2024-09-13 04:22

import django.core.validators
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
('course', '0121_alter_flowaccessexceptionentry_permission_and_more'),
]

operations = [
migrations.CreateModel(
name='Facility',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('identifier', models.CharField(db_index=True, max_length=200, unique=True, validators=[django.core.validators.RegexValidator('^(?P<test_facility_id>[a-zA-Z][a-zA-Z0-9_]*)$')])),
('description', models.TextField(blank=True, null=True)),
('secret', models.CharField(max_length=220)),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.course')),
],
options={
'verbose_name_plural': 'Facilities',
},
),
migrations.CreateModel(
name='DenyEvent',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('event_id', models.UUIDField()),
('created', models.DateTimeField(verbose_name='Created time')),
('received_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Received time')),
('deny_uuid', models.UUIDField()),
('start', models.DateTimeField(db_index=True, verbose_name='Start time')),
('end', models.DateTimeField(db_index=True, verbose_name='End time')),
('cidr_blocks', models.JSONField()),
('test_facility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='prairietest.facility')),
],
),
migrations.CreateModel(
name='AllowEvent',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('event_id', models.UUIDField()),
('created', models.DateTimeField(verbose_name='Created time')),
('received_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Received time')),
('user_uid', models.CharField(max_length=200)),
('user_uin', models.CharField(max_length=200)),
('exam_uuid', models.UUIDField()),
('start', models.DateTimeField(verbose_name='Start time')),
('end', models.DateTimeField(verbose_name='End time')),
('cidr_blocks', models.JSONField()),
('test_facility', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='prairietest.facility')),
],
),
migrations.CreateModel(
name='MostRecentDenyEvent',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('deny_uuid', models.UUIDField(unique=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='prairietest.denyevent')),
],
),
migrations.AddIndex(
model_name='facility',
index=models.Index(fields=['course', 'identifier'], name='prairietest_course__2525b9_idx'),
),
migrations.AddIndex(
model_name='denyevent',
index=models.Index(fields=['deny_uuid', 'created'], name='prairietest_deny_uu_bbbbf1_idx'),
),
migrations.AddIndex(
model_name='denyevent',
index=models.Index(fields=['deny_uuid', 'start'], name='prairietest_deny_uu_b13822_idx'),
),
migrations.AddIndex(
model_name='denyevent',
index=models.Index(fields=['deny_uuid', 'end'], name='prairietest_deny_uu_3c9537_idx'),
),
migrations.AddIndex(
model_name='allowevent',
index=models.Index(fields=['user_uid', 'exam_uuid', 'start'], name='prairietest_user_ui_e93827_idx'),
),
migrations.AddIndex(
model_name='allowevent',
index=models.Index(fields=['user_uid', 'exam_uuid', 'end'], name='prairietest_user_ui_e11aa4_idx'),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Generated by Django 5.1 on 2024-09-13 15:39

import django.utils.timezone
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('prairietest', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='mostrecentdenyevent',
name='end',
field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='End time'),
preserve_default=False,
),
migrations.AlterField(
model_name='denyevent',
name='end',
field=models.DateTimeField(verbose_name='End time'),
),
migrations.AlterField(
model_name='denyevent',
name='start',
field=models.DateTimeField(verbose_name='Start time'),
),
migrations.AddIndex(
model_name='mostrecentdenyevent',
index=models.Index(fields=['end'], name='prairietest_end_31b76d_idx'),
),
]
Empty file.
Loading

0 comments on commit 19f7eaf

Please sign in to comment.