45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
from rest_framework.permissions import BasePermission, SAFE_METHODS
|
|
|
|
from apps.accounts.models import Role
|
|
|
|
|
|
class IsTeacher(BasePermission):
|
|
message = "Only teachers can perform this action."
|
|
|
|
def has_permission(self, request, view):
|
|
u = request.user
|
|
return bool(u and u.is_authenticated and u.role == Role.TEACHER)
|
|
|
|
|
|
class IsApprovedTeacher(BasePermission):
|
|
message = "Your teacher profile must be approved by an admin first."
|
|
|
|
def has_permission(self, request, view):
|
|
u = request.user
|
|
if not (u and u.is_authenticated and u.role == Role.TEACHER):
|
|
return False
|
|
tp = getattr(u, "teacher_profile", None)
|
|
return bool(tp and tp.is_approved)
|
|
|
|
|
|
class IsCourseOwner(BasePermission):
|
|
"""Object-level: the course (or its parent for sections/lessons) must be owned by the request user."""
|
|
|
|
message = "You do not own this course."
|
|
|
|
def has_object_permission(self, request, view, obj):
|
|
from apps.courses.models import Course, Lesson, Section
|
|
|
|
if isinstance(obj, Course):
|
|
return obj.instructor_id == request.user.id
|
|
if isinstance(obj, Section):
|
|
return obj.course.instructor_id == request.user.id
|
|
if isinstance(obj, Lesson):
|
|
return obj.section.course.instructor_id == request.user.id
|
|
return False
|
|
|
|
|
|
class ReadOnly(BasePermission):
|
|
def has_permission(self, request, view):
|
|
return request.method in SAFE_METHODS
|