python permission_required.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python permission_required.py相关的知识,希望对你有一定的参考价值。

def permission_required(*permission_list):
    def _wraps(func):
        @tornado.gen.coroutine
        def __wraps(*args, **kwargs):
            # 1. 检测 token 是否存在
            handle = args[0]      # tornado.web.RequestHander 函数的 self
            token = handle.request.headers.get('X-Auth-Token', "")
            if token is None or token.strip("") == "":
                handle.set_status(status_code=401)
                response_body = {
                  "message": "token 不存在",
                  "code": "401",
                  "response": {"error": "token 不存在"},
                  "success": False
                }
                handle.write(response_body)
                return
            # 2. token 换取 permission list
            keystone_url = 'http://172.24.6.155:8000/auth/tokens'
            req_header = {
                'X-Auth-Token': token,
            }
            client = AsyncHTTPClient()
            response = yield client.fetch(keystone_url, method="GET", body=None, headers=req_header)
            try:
                body = json.loads(response.body)
                permissions = body.get("response", {}).get("token", {}).get("permissions", [])
                is_admin = body.get("response", {}).get("token", {}).get("user", {}).get("is_admin", False)
                p_list = []
                for item in permissions:
                    tmp_name = item.get("service_name", "") + '.' + item.get("name", "")
                    p_list.append(tmp_name)

                # 取交集
                intersection = list(set(permission_list).intersection(p_list))
                if (intersection == permission_list) or is_admin:
                    # 满足权限需求
                    pass
                else:
                    d = {
                        "message": "无权限",
                        "code": "403",
                        "response": "无权限",
                        "success": False
                    }
                    handle.set_status(status_code=403)
                    handle.write(d)
                    return
            except:
                d = {
                    "message": "服务器出错",
                    "code": "500",
                    "response": "服务器出错",
                    "success": False
                }
                handle.set_status(status_code=500)
                handle.write(d)
                return
            ret = func(*args, **kwargs)
            raise tornado.gen.Return(ret)
        return __wraps
    return _wraps

以上是关于python permission_required.py的主要内容,如果未能解决你的问题,请参考以下文章

Django REST框架 - 如何快速检查用户权限?

需要 Django 权限

装饰器设置函数的属性

可以合并 PermissionRequiredMixin 和 LoginRequiredMixin 吗?

如何仅限超级用户查看?

Django编写通用更新视图