2018-01-11 12:10:27 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
|
|
|
from rest_framework import permissions
|
2018-07-20 10:42:01 +00:00
|
|
|
from django.contrib.auth.mixins import UserPassesTestMixin
|
|
|
|
|
|
|
|
from orgs.utils import current_org
|
2018-01-11 12:10:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission):
|
|
|
|
"""Allows access to valid user, is active and not expired"""
|
|
|
|
|
|
|
|
def has_permission(self, request, view):
|
|
|
|
return super(IsValidUser, self).has_permission(request, view) \
|
|
|
|
and request.user.is_valid
|
|
|
|
|
|
|
|
|
|
|
|
class IsAppUser(IsValidUser):
|
|
|
|
"""Allows access only to app user """
|
|
|
|
|
|
|
|
def has_permission(self, request, view):
|
|
|
|
return super(IsAppUser, self).has_permission(request, view) \
|
|
|
|
and request.user.is_app
|
|
|
|
|
|
|
|
|
2018-07-23 04:55:13 +00:00
|
|
|
class IsOrgAdmin(IsValidUser):
|
2018-01-11 12:10:27 +00:00
|
|
|
"""Allows access only to superuser"""
|
|
|
|
|
|
|
|
def has_permission(self, request, view):
|
2018-07-23 04:55:13 +00:00
|
|
|
return super(IsOrgAdmin, self).has_permission(request, view) \
|
|
|
|
and current_org.can_admin_by(request.user)
|
2018-01-11 12:10:27 +00:00
|
|
|
|
|
|
|
|
2018-07-23 04:55:13 +00:00
|
|
|
class IsOrgAdminOrAppUser(IsValidUser):
|
2018-01-11 12:10:27 +00:00
|
|
|
"""Allows access between superuser and app user"""
|
|
|
|
|
|
|
|
def has_permission(self, request, view):
|
2018-07-23 04:55:13 +00:00
|
|
|
return super(IsOrgAdminOrAppUser, self).has_permission(request, view) \
|
|
|
|
and (current_org.can_admin_by(request.user) or request.user.is_app)
|
2018-01-11 12:10:27 +00:00
|
|
|
|
|
|
|
|
2018-07-23 04:55:13 +00:00
|
|
|
class IsOrgAdminOrAppUserOrUserReadonly(IsOrgAdminOrAppUser):
|
2018-01-11 12:10:27 +00:00
|
|
|
def has_permission(self, request, view):
|
|
|
|
if IsValidUser.has_permission(self, request, view) \
|
|
|
|
and request.method in permissions.SAFE_METHODS:
|
|
|
|
return True
|
|
|
|
else:
|
2018-07-23 04:55:13 +00:00
|
|
|
return IsOrgAdminOrAppUser.has_permission(self, request, view)
|
2018-01-11 12:10:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
class IsCurrentUserOrReadOnly(permissions.BasePermission):
|
|
|
|
def has_object_permission(self, request, view, obj):
|
|
|
|
if request.method in permissions.SAFE_METHODS:
|
|
|
|
return True
|
|
|
|
return obj == request.user
|
2018-07-20 10:42:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AdminUserRequiredMixin(UserPassesTestMixin):
|
|
|
|
def test_func(self):
|
|
|
|
if not self.request.user.is_authenticated:
|
|
|
|
return False
|
2018-07-23 04:55:13 +00:00
|
|
|
elif not current_org.can_admin_by(self.request.user):
|
2018-07-20 10:42:01 +00:00
|
|
|
self.raise_exception = True
|
|
|
|
return False
|
|
|
|
return True
|