Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent students from taking other students' attendances #450

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 39 additions & 14 deletions csm_web/scheduler/views/student.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.utils import timezone
from scheduler.models import Attendance, SectionOccurrence
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
import datetime

from .utils import log_str, logger, get_object_or_error
from ..models import Student
from ..serializers import AttendanceSerializer, StudentSerializer
from .utils import get_object_or_error, logger


class StudentViewSet(viewsets.GenericViewSet):
Expand All @@ -28,24 +26,31 @@ def get_queryset(self):

@action(detail=True, methods=["patch"])
def drop(self, request, pk=None):
"""
Drops a student from a section.
Students can drop themselves, and coordinators can drop students from their course.
Mentors are unable to drop students from any course under any circumstances.
Deletes futures attendances for the dropped student.
"""
student = get_object_or_error(self.get_queryset(), pk=pk)
is_coordinator = student.course.coordinator_set.filter(
user=request.user
).exists()
if student.user != request.user and not is_coordinator:
# Students can drop themselves, and Coordinators can drop students from their course
# Mentors CANNOT drop their own students, or anyone else for that matter
raise PermissionDenied("You do not have permission to drop this student")
student.active = False
if is_coordinator:
student.banned = request.data.get("banned", False)
if student.course.is_restricted and request.data.get("blacklisted", False):
student.course.whitelist.remove(student.user)
student.save()

logger.info(
f"<Drop> User {log_str(request.user)} dropped Section {log_str(student.section)} for Student user {log_str(student.user)}"
"<Drop> User %s dropped Section %s for Student user %s",
request.user,
student.section,
student.user,
)
# filter attendances and delete future attendances
now = timezone.now().astimezone(timezone.get_default_timezone())
num_deleted, _ = student.attendance_set.filter(
Q(
Expand All @@ -54,20 +59,32 @@ def drop(self, request, pk=None):
)
).delete()
logger.info(
f"<Drop> Deleted {num_deleted} attendances for user {log_str(student.user)} in Section {log_str(student.section)} after {now.date()}"
"<Drop> Deleted %s attendances for user %s in Section %s after %s",
num_deleted,
student.user,
student.section,
now.date(),
)
return Response(status=status.HTTP_204_NO_CONTENT)

@action(detail=True, methods=["get", "put"])
def attendances(self, request, pk=None):
"""
Take attendance for a student.
"""
student = get_object_or_error(self.get_queryset(), pk=pk)
is_mentor = student.course.mentor_set.filter(user=request.user).exists()
if request.method == "GET":
return Response(
AttendanceSerializer(student.attendance_set.all(), many=True).data
)
# PUT
if student.user == self.request.user:
raise PermissionDenied("You cannot record your own attendance (nice try)")
if not is_mentor:
raise PermissionDenied(
"You cannot record your own attendance (nice try) or your friend's. But"
" seeing as you're familiar with our API Endpoints, you should apply to"
" work for us!"
)
try: # update
attendance = student.attendance_set.get(pk=request.data["id"])
serializer = AttendanceSerializer(
Expand All @@ -81,18 +98,26 @@ def attendances(self, request, pk=None):
)
except ObjectDoesNotExist:
logger.error(
f"<Attendance:Failure> Could not record attendance for User {log_str(request.user)}, used non-existent attendance id {request.data['id']}"
(
"<Attendance:FAILURE> Could not record attendance for User %s, used"
" non-existent attendance id %s"
),
request.user,
request.data["id"],
)
return Response(status=status.HTTP_400_BAD_REQUEST)

if serializer.is_valid():
attendance = serializer.save()
logger.info(
f"<Attendance:Success> Attendance {log_str(attendance)} recorded for User {log_str(request.user)}"
"<Attendance:Success> Attendance %s taken for User %s",
attendance,
request.user,
)
return Response(status=status.HTTP_204_NO_CONTENT)
logger.error(
f"<Attendance:Failure> Could not record attendance for User {log_str(request.user)}, errors: {serializer.errors}"
"<Attendance:FAILURE> Could not record attendance for User %s, errors %s",
request.user,
serializer.errors,
)
return Response(serializer.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)

Loading