https://docs.ckan.org/en/2.9/extensions/tutorial.html#using-the-plugins-toolkit
CKAN plugins toolkit 是一個 Python module,提供 CKAN 相關的 functions, classes 及 exceptions 協助撰寫 CKAN extension。
toolkit.get_action 可用來呼叫 CKAN 的 action function,這和透過 web interface 或 API 呼叫 的方法一樣。以下程式,ckan.plugins.toolkit.get_action 呼叫ckan.logic.action.get.member_list 取得 curators group 的成員名單,結果和 API 呼叫 /api/3/action/member_list 會是一樣的:
members = toolkit.get_action('member_list')(
data_dict={'id': 'curators', 'object_type': 'user'})
延續上個 CKACKAN Extensions Tutorial(v2.9): 實作 IAuthFunctions 自訂授權規則,以下將實作只允許 curators 群組成員建立群組的功能。
建立 curators 群組
在 CKAN 中建立 curators 群組。
修改 plugin.py:實作 IAuthFunctions
修改 ckanext-iauthfunctions/ckanext/iauthfunctions/plugin.py (程式碼)
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def group_create(context, data_dict=None):
# Get the user name of the logged-in user.
user_name = context['user']
# Get a list of the members of the 'curators' group.
members = toolkit.get_action('member_list')(
data_dict={'id': 'curators', 'object_type': 'user'})
# 'members' is a list of (user_id, object_type, capacity) tuples, we're
# only interested in the user_ids.
member_ids = [member_tuple[0] for member_tuple in members]
# We have the logged-in user's user name, get their user id.
convert_user_name_or_id_to_id = toolkit.get_converter(
'convert_user_name_or_id_to_id')
user_id = convert_user_name_or_id_to_id(user_name, context)
# Finally, we can test whether the user is a member of the curators group.
if user_id in member_ids:
return {'success': True}
else:
return {'success': False,
'msg': 'Only curators are allowed to create groups'}
class ExmapleAuthFunctionsPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IAuthFunctions)
def get_auth_functions(self):
return {'group_create': group_create}
- 實作 IAuthFunctions
- 覆寫 IAuthFunctions 介面的 get_auth_functions 方法
- 呼叫 toolkit.get_action('member_list') 判斷目前使用者是否在 curators 群組
安裝
- 進入Python Virtual Environment:
. /usr/lib/ckan/default/bin/activate - 切換目錄:
cd /usr/lib/ckan/default/src/ckanext-iauthfunctions - 安裝 Plugin:
python setup.py develop - 重啟 CKAN 服務:
sudo supervisorctl restart ckan-uwsgi:*
測試
- 開 Postman 執行 api 呼叫
curl POST 'http://[CKAN web site]/api/3/action/group_create
--header 'Authorization: [測試會員的API Key]'
--header 'Content-Type: application/json'
--data-raw '{
"name": "0506-Group",
"owner_org": "0427-org",
"description": "test ckanext-iauthfunctions"
}'
視是否為 curators group 的帳號,success 回傳 true 或 false:
{
"error": {
"__type": "Authorization Error",
"message": "拒絕存取: Only curators are allowed to create groups[ExampleIAuthFunctionsPlugin]"
},
"help": "...",
"success": false
}
- 以管理員登入 CKAN,建立 curators 群組
- 把測試會員加入這個群組。
- 再次以 Postman 執行以上 api 呼叫
- 即可成功
沒有留言:
張貼留言