# -*- encoding: utf-8 -*-

from rest_framework.permissions import BasePermission

from apps.home.models import Server
from apps.authentication.models import ServerMember


class HasServerAccess(BasePermission):
    """
    An object permission class, the object must have a 'server' attribute.
    """

    message = "You lack administrator access to this server"

    def has_object_permission(self, request, view, obj):
        if not hasattr(obj, "server"):
            raise Exception(f"obj '{obj}' must have attr 'server'")

        return ServerMember.objects.filter(user=request.user, server=obj.server).exists()
