Python eve - 用户限制资源访问功能,项目的ID_FIELD为AUTH_FIELD

时间:2016-02-17 13:15:34

标签: python eve

我有一个用户集合,我把它打开而没有POST验证,所以用户可以创建帐户,现在我想限制访问说测试集合,用户只能创建一个测试文档,我添加了auth_field到user_id,我想用user_id作为field_id添加文档,同时将其用作auth_field,用于读/写限制。

这是我的测试模型,我添加了PUT,因为用户有自己的ID,它应该用作test_item id_field。

当我尝试使用此运行Eve时,我有一个例外,是否有正确执行此操作的方法,因此每个正确验证的用户请求以及auth_field设置为user_id都将以透明方式工作?

谢谢你的帮助。

tests = {
    'resource_methods': ['GET'],
    'upsert_on_put': True,
    'id_field': 'test_id'
    'item_title': 'test',
    'auth_field': 'test_id',
    'item_methods': ['GET', 'PATCH', 'PUT'],
    'schema': {
        'test_field': {
            'type': 'string',
            'required': True
        }
    }
}

例外:

eve.exceptions.ConfigException: "tests": auth_field cannot be set to id_field (test_id)

TL; DR

从用户和测试集合中做一对一的关系,每个用户都有一个测试,在认证后通过auth_field透明地工作。

1 个答案:

答案 0 :(得分:1)

如果您正在使用用户限制资源访问,则可以使用before insert event hook执行此1:1关系。因为那时你将在文档上有一个auth_field。在我的示例中,auth字段为user_id

你的on_insert_tests钩子会是这样的

from flask import current_app, abort

def check_inserted(documents):
    # get ID for current user
    user_id = current_app.auth.get_request_auth_value()
    # find tests for the current user
    collection = current_app.data.driver.db['tests']
    tests = collection.find({'user_id': user_id})

    if tests.count() > 0:
        abort(409, 'Test already present for this account. Only one allowed.')

因此,当为当前用户插入第二个测试时,它将中止。

顺便说一句,我不明白为什么要将测试中的ID字段更改为test_id,而不是使用默认的_id