Python eve - User-Restricted Resource Access feature with item's ID_FIELD as AUTH_FIELD

我怕爱的太早我们不能终老 提交于 2019-12-24 15:45:37

问题


I have a collection of users, that I left it open without authentication for POST so user can create accounts, now I want to restrict the access say for tests collection, the user can only create one test document, I added the auth_field to the user_id and I want to add the documents with the user_id as the field_id, at the same time use it as the auth_field, for read/write restriction.

This is my test model, I added the PUT because the user have its own ID and it should be used as the test_item id_field.

When I try to run Eve with this, I have an exception, is there a way of doing this properly, so each user request that is correctly authenticated and the auth_field is set to the user_id will work transparently ?

Thank you fir your help.

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
        }
    }
}

Exception:

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

TL;DR

Do one to one relation from users and tests collection, each user have one test, works transparently through auth_field after authentication.


回答1:


You can do this 1:1 relation using a before insert event hook, if you are using User-Restricted Resource Access as you mention. Because then you will have an auth_field on documents. In my example the auth field is user_id.

Your on_insert_tests hook would be like this

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.')

So when inserting the second test for the current user, it will abort.

By the way, I don't see why you are changing the ID field in tests to test_id, instead of using the default _id.



来源:https://stackoverflow.com/questions/35457787/python-eve-user-restricted-resource-access-feature-with-items-id-field-as-aut

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!