# coding=utf-8

from rest_framework import permissions

from apps.WechatApplet.models import WechatApplet
from utils.exceptions import CustomError

class isLogin(permissions.BasePermission):
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        return True

def check_permission(request, perm):
    if not request.user or not request.user.is_authenticated:
        raise CustomError(u"身份认证失败，请重新登录！")
    from django.contrib.auth.models import Permission
    ps = perm.split('.')
    if request.user.has_perm(perm):
        return True
    else:
        try:
            p = Permission.objects.get(codename=ps[1], content_type__app_label=ps[0])
        except:
            raise CustomError(u"权限配置错误！")
        raise CustomError(u"您没有[%s--%s]权限，无法执行该操作，请联系管理员分配权限！" % (p.content_type.name, p.name))

decorator_with_arguments = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)

@decorator_with_arguments
def permission_required(function, perm):
    def _function(viewset, *args, **kwargs):
        # user_id = viewset.request.META.get('HTTP_USER_ID')
        # token = viewset.request.META.get('HTTP_Authorization')
        # if user_id and token:
        #     try:
        #         user = User.objects.get(pk=user_id)
        #     except:
        #         return ForbiddenJSONResponse()

            # valid = token_generator.check_token(user, token)
            # if valid:
            #     request.user = user
            # viewset.request.user = user
        # else:
        #     return ForbiddenJSONResponse()

        if viewset.request.user.has_perm(perm):
            return function(viewset, *args, **kwargs)
        else:
            from django.contrib.auth.models import Permission
            ps = perm.split('.')
            try:
                p = Permission.objects.get(codename=ps[1], content_type__app_label=ps[0])
            except:
                raise CustomError(u"权限配置错误！")

            raise CustomError(u"您没有[%s-%s]权限，无法执行该操作，请联系管理员分配权限！" % (p.content_type.name, p.name))
    return _function
