如何从 check_auth 访问查找字典

how to access lookup dictionary from check_auth

我的应用程序中有 users 资源并实施了 BasicAuth 方案。

这是我的安全要求 -

实现这些要求的最简单方法是在 check_auth 方法中访问查找字典,然后我可以将经过身份验证的用户与电子邮件参数进行比较。但我找不到任何方法来做到这一点。相反,我想出了以下使用事件挂钩的 hacky 解决方案。

class UserAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource, method):
        try:
            user = db.session.query(User).filter(User.email == username).one()
            return user.authenticate(password)
        except Exception as e:
            # TODO: Log this exception
            print('Error - {}'.format(e))
            return False


def authz(req, lookup):
    authn_user = db.session.query(User).filter(User.email == req.authorization['username']).one()
    if 'email' in lookup and lookup['email'] == req.authorization['username']:
        print('User requesting their own profile')
        return
    elif authn_user.is_superuser:
        print('Superuser requesting something')
        return
    else:
        print('Not authorized. Sabotaging request.')
        lookup['email'] = 'None'


app.on_pre_GET_users += authz

我的 settings.py 文件中的片段 -

DOMAIN['users']['public_methods'] = ['POST']
DOMAIN['users']['additional_lookup'] = {'url': 'regex("[\w]+@[\w]+\.[\w]+")', 'field': 'email'}

有没有更好的设计方法?

一个简单的选择是使用来自 Flask 的 request 对象:

from flask import request

class UserAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource, method):
        # you can inspect the request object here
        print request.args, request.url, request.headers
        return True