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 12, 2024
1 parent e91ce40 commit 69ad4c4
Show file tree
Hide file tree
Showing 13 changed files with 687 additions and 7 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
8 changes: 6 additions & 2 deletions course/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,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 @@ -1051,12 +1051,16 @@ def __call__(self, request):

facilities = set()

for name, props in get_facilities_config(request).items():
facilities_config = get_facilities_config(request)
if facilities_config is None:
facilities_config = {}
for name, props in facilities_config.items():
ip_ranges = props.get("ip_ranges", [])
for ir in ip_ranges:
if remote_address in ipaddress.ip_network(str(ir)):
facilities.add(name)

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

return self.get_response(request)
Expand Down
Empty file added prairietest/__init__.py
Empty file.
102 changes: 102 additions & 0 deletions prairietest/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
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, PrairieTestFacility


if TYPE_CHECKING:
from accounts.models import User


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


@admin.register(PrairieTestFacility)
class PrairieTestFacilityAdmin(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 = PrairieTestFacilityAdminForm


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)
if request.user.is_superuser:
return qs
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)
if request.user.is_superuser:
return qs
return _filter_events_for_user(qs, request.user)

list_display = [
"event_id", "test_facility", "start", "end", "deny_uuid"]
list_filter = ["test_facility"]
86 changes: 86 additions & 0 deletions prairietest/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Generated by Django 5.1 on 2024-09-12 14:41

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='PrairieTestFacility',
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': 'PrairieTest facility',
'verbose_name_plural': 'PrairieTest 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.prairietestfacility')),
],
),
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.prairietestfacility')),
],
),
migrations.AddIndex(
model_name='prairietestfacility',
index=models.Index(fields=['course', 'identifier'], name='prairietest_course__462b09_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'),
),
]
Empty file.
108 changes: 108 additions & 0 deletions prairietest/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
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 django.core.validators import RegexValidator
from django.db import models
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _

from course.models import Course


TEST_FACILITY_ID_REGEX = "(?P<test_facility_id>[a-zA-Z][a-zA-Z0-9_]*)"


class PrairieTestFacility(models.Model):
id = models.BigAutoField(primary_key=True)

course = models.ForeignKey(Course, on_delete=models.CASCADE)
identifier = models.CharField(max_length=200, unique=True,
validators=[RegexValidator(f"^{TEST_FACILITY_ID_REGEX}$")],
db_index=True)

description = models.TextField(blank=True, null=True)
secret = models.CharField(max_length=220)

class Meta:
indexes = [
models.Index(fields=["course", "identifier"]),
]
verbose_name = _("PrairieTest facility")
verbose_name_plural = _("PrairieTest facilities")

def __str__(self) -> str:
return f"PrairieTest Facility '{self.identifier}' in {self.course.identifier}"


class PrairieTestEvent(models.Model):
id = models.BigAutoField(primary_key=True)

test_facility = models.ForeignKey(PrairieTestFacility, on_delete=models.CASCADE)
event_id = models.UUIDField()
created = models.DateTimeField(verbose_name=_("Created time"))
received_time = models.DateTimeField(default=now,
verbose_name=_("Received time"))

class Meta:
abstract = True
indexes = [
models.Index(fields=["event_id"]),
models.Index(fields=["created"]),
]


class AllowEvent(PrairieTestEvent):
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()

def __str__(self) -> str:
return f"PrairieTest allow event {self.event_id} for {self.user_uid}"

class Meta:
indexes = [
models.Index(fields=["user_uid", "exam_uuid", "start"]),
models.Index(fields=["user_uid", "exam_uuid", "end"]),
]


class DenyEvent(PrairieTestEvent):
deny_uuid = models.UUIDField()
start = models.DateTimeField(verbose_name=_("Start time"), db_index=True)
end = models.DateTimeField(verbose_name=_("End time"), db_index=True)
cidr_blocks = models.JSONField()

def __str__(self) -> str:
return f"PrairieTest deny event {self.event_id} with {self.deny_uuid}"

class Meta:
indexes = [
models.Index(fields=["deny_uuid", "created"]),
models.Index(fields=["deny_uuid", "start"]),
models.Index(fields=["deny_uuid", "end"]),
]
Loading

0 comments on commit 69ad4c4

Please sign in to comment.