56 lines
2.9 KiB
Python
56 lines
2.9 KiB
Python
from rest_framework import permissions
|
|
from rest_framework.exceptions import PermissionDenied
|
|
|
|
|
|
# ----------------------------------------------------
|
|
# Base Class เพื่อใช้ Logic การตรวจสอบสิทธิ์ร่วมกัน
|
|
# ----------------------------------------------------
|
|
class BaseRolePermission(permissions.BasePermission):
|
|
"""
|
|
Base class สำหรับตรวจสอบสิทธิ์ตาม is_superuser และ is_staff
|
|
"""
|
|
def is_admin(self, user):
|
|
return user.is_authenticated and user.is_superuser
|
|
|
|
def is_manager(self, user):
|
|
# ผู้จัดการคือ is_staff แต่ไม่ใช่ superuser
|
|
return user.is_authenticated and user.is_staff and not user.is_superuser
|
|
|
|
# หรือเพิ่มฟังก์ชัน is_model_owner(user) ถ้าจำเป็น
|
|
# ถ้าใช้ฟิลด์ 'role' ที่คุณเพิ่มใน Serializer ควรใช้:
|
|
# return user.is_authenticated and getattr(user, 'role', '').upper() == 'ADMIN'
|
|
|
|
|
|
# ----------------------------------------------------
|
|
# 1. Permission: อนุญาตเฉพาะ Admin เท่านั้น
|
|
# ----------------------------------------------------
|
|
class IsAdmin(BaseRolePermission):
|
|
message = "คุณไม่มีสิทธิ์เข้าถึงหน้านี้ (Admin Required)."
|
|
|
|
def has_permission(self, request, view):
|
|
# Admin คือ is_superuser
|
|
return self.is_admin(request.user)
|
|
|
|
|
|
# ----------------------------------------------------
|
|
# 2. Permission: อนุญาตเฉพาะ Admin หรือ Manager เท่านั้น
|
|
# ----------------------------------------------------
|
|
class IsAdminOrManager(BaseRolePermission):
|
|
message = "คุณต้องมีสิทธิ์ Admin หรือ Manager."
|
|
|
|
def has_permission(self, request, view):
|
|
# Admin หรือ Manager (is_staff)
|
|
return self.is_admin(request.user) or self.is_manager(request.user)
|
|
|
|
|
|
# ----------------------------------------------------
|
|
# 3. Permission: อนุญาตเฉพาะผู้ใช้ที่ผ่านการยืนยันตัวตนแล้ว (IsAuthenticated)
|
|
# และเป็น Viewer ขึ้นไป
|
|
# ----------------------------------------------------
|
|
# ไม่จำเป็นต้องสร้างคลาสนี้ถ้าใช้ DRF's IsAuthenticated โดยตรง
|
|
# แต่ถ้าต้องการเพิ่ม Logic อื่นๆ ในอนาคต ควรใช้คลาสนี้
|
|
class IsAuthenticatedViewer(permissions.BasePermission):
|
|
message = "คุณต้องเข้าสู่ระบบก่อน"
|
|
|
|
def has_permission(self, request, view):
|
|
return request.user.is_authenticated |