Skip to content

Commit

Permalink
support checking admin teachers
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Dec 12, 2023
1 parent ffc147b commit 181eb96
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
4 changes: 2 additions & 2 deletions codeforlife/user/permissions/is_student.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ def __init__(self, student_id: t.Optional[int] = None):
"""Initialize permission.
Args:
student_id: A student's ID. If passed, the user must be this
student.
student_id: A student's ID. If None, check if the user is any
student. Else, check if the user is the specific student.
"""

super().__init__()
Expand Down
20 changes: 16 additions & 4 deletions codeforlife/user/permissions/is_teacher.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,39 @@
from rest_framework.request import Request
from rest_framework.views import APIView

from ..models import User
from ..models import Teacher, User


class IsTeacher(BasePermission):
"""Request's user must be a teacher."""

def __init__(self, teacher_id: t.Optional[int] = None):
def __init__(
self,
teacher_id: t.Optional[int] = None,
is_admin: t.Optional[bool] = None,
):
"""Initialize permission.
Args:
teacher_id: A teacher's ID. If passed, the user must be this
teacher.
teacher_id: A teacher's ID. If None, check if the user is any
teacher. Else, check if the user is the specific teacher.
is_admin: If the teacher is an admin. If None, don't check if the
teacher is an admin. Else, check if the teacher is (not) an
admin.
"""

super().__init__()
self.teacher_id = teacher_id
self.is_admin = is_admin

def has_permission(self, request: Request, view: APIView):
user = request.user
return (
isinstance(user, User)
and user.teacher_id is not None
and (self.teacher_id is None or user.teacher_id == self.teacher_id)
and (
self.is_admin is None
or t.cast(Teacher, user.teacher).is_admin == self.is_admin
)
)

0 comments on commit 181eb96

Please sign in to comment.