from django.core.exceptions import PermissionDenied

def require_permission(permission_code):
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            user = request.user
            if not user.is_authenticated:
                raise PermissionDenied("Authentication required")
            user_permissions = [
                rp.permission.code
                for ur in user.userrole_set.all()
                for rp in ur.role.rolepermission_set.all()
            ]
            if permission_code not in user_permissions:
                raise PermissionDenied("You do not have permission")
            return view_func(request, *args, **kwargs)
        return _wrapped_view
    return decorator
