2016-02-17 23 views
1

我有一個用戶的集合,我沒有驗證POST,所以用戶可以創建帳戶,現在我想限制訪問說測試集合,用戶只能創建一個測試文檔,我將auth_field添加到user_id,並且想要將user_id作爲field_id添加到文檔中,同時將其用作auth_field,以用於讀/寫限制。Python前夕 - 用戶限制的資源訪問功能項目的ID_FIELD作爲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

如果您提及的是使用用戶限制資源訪問,則可以使用before insert event hook執行1:1關係。因爲那樣你將在文檔上擁有一個auth_field。在我的例子中,驗證字段是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

+0

這就是我最終做的,謝謝。 –