2015-08-04 05:22:37 +00:00
|
|
|
# coding=utf-8
|
2015-10-14 01:57:43 +00:00
|
|
|
import functools
|
2015-08-12 15:18:22 +00:00
|
|
|
from functools import wraps
|
2015-08-04 05:22:37 +00:00
|
|
|
|
2015-10-14 01:57:43 +00:00
|
|
|
from django.http import HttpResponseRedirect
|
2015-08-04 05:22:37 +00:00
|
|
|
|
2015-10-14 01:57:43 +00:00
|
|
|
from utils.shortcuts import error_response
|
|
|
|
from .models import SUPER_ADMIN, ADMIN
|
2015-08-04 05:22:37 +00:00
|
|
|
|
|
|
|
|
2015-10-14 01:57:43 +00:00
|
|
|
class BasePermissionDecorator(object):
|
|
|
|
def __init__(self, func):
|
|
|
|
self.func = func
|
2015-08-04 05:22:37 +00:00
|
|
|
|
2015-10-14 01:57:43 +00:00
|
|
|
def __get__(self, obj, obj_type):
|
|
|
|
return functools.partial(self.__call__, obj)
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
2015-09-22 08:18:32 +00:00
|
|
|
if len(args) == 2:
|
2015-10-14 01:57:43 +00:00
|
|
|
self.request = args[1]
|
2015-09-22 08:18:32 +00:00
|
|
|
else:
|
2015-10-14 01:57:43 +00:00
|
|
|
self.request = args[0]
|
|
|
|
|
|
|
|
if self.check_permission():
|
|
|
|
return self.func(*args, **kwargs)
|
2015-08-06 04:25:16 +00:00
|
|
|
else:
|
2015-10-14 01:57:43 +00:00
|
|
|
if self.request.is_ajax():
|
|
|
|
return error_response(u"请先登录")
|
|
|
|
else:
|
|
|
|
return HttpResponseRedirect("/login/")
|
2015-09-22 08:18:32 +00:00
|
|
|
|
2015-10-14 01:57:43 +00:00
|
|
|
def check_permission(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
|
|
class login_required(BasePermissionDecorator):
|
|
|
|
def check_permission(self):
|
|
|
|
return self.request.user.is_authenticated()
|
|
|
|
|
|
|
|
|
|
|
|
class super_admin_required(BasePermissionDecorator):
|
|
|
|
def check_permission(self):
|
|
|
|
return self.request.user.is_authenticated() and self.request.user.admin_type == SUPER_ADMIN
|
2015-09-22 08:18:32 +00:00
|
|
|
|
|
|
|
|
2015-10-14 01:57:43 +00:00
|
|
|
class admin_required(BasePermissionDecorator):
|
|
|
|
def check_permission(self):
|
|
|
|
return self.request.user.is_authenticated() and self.request.user.admin_type in [SUPER_ADMIN, ADMIN]
|