flask_peeweeのRestAPIでadminユーザーのみに更新を許可する
flask_peeweeのRestAPIで、adminユーザーのみに更新を許可するにはAdminAuthenticationを使用します。
from flaskext.rest import AdminAuthentication auth = Auth(app, db, user_model=User) # ユーザー認証をRestAPIに設定する user_auth = UserAuthentication(auth) api = RestAPI(app, default_auth=user_auth) # Userへのアクセスはadminユーザー認証を使用する admin_auth = AdminAuthentication(auth) api.register(User, UserResource, auth=admin_auth)
admin=Trueなadminユーザーとadmin=Falseなguestユーザーを用意して、requestsでAPIにアクセスしてみます。
{
"meta": {
"model": "user",
"next": "",
"page": 1,
"previous": ""
},
"objects": [
{
"username": "admin",
"created": "2011-11-15 17:22:50",
"admin": true,
"email": "admin@mail.com",
"active": true,
"id": 1
},
{
"username": "guest",
"created": "2011-11-16 17:22:38",
"admin": false,
"email": "guest@mail.com",
"active": true,
"id": 2
}
]
}import requests res = requests.put('http://localhost:5000/api/user/2/', data='{"email": "modified@mail.com"}', auth=("guest","guest"), headers={'Content-Type': 'application/json'}) res # => <Response [401]> res.content # => u'Authentication failed'
guestユーザーでユーザー情報のemailを更新しようとすると、401が返されることがわかります。
adminユーザーだとどうでしょうか
res = requests.put('http://localhost:5000/api/user/2/', data='{"email": "modified2@mail.com"}', auth=("admin","admin"), headers={'Content-Type': 'application/json'}) res # => <Response [200]> # => res.content '{\n "username": "test",\n "created": "2011-11-15 17:23:30",\n "admin": false,\n "email": "modified@mail.com",\n "active": true,\n "id": 2\n}'
adminユーザーはユーザー情報の更新ができました。
蛇足
APIでデータ更新するのに、Content-Typeをわざわざ指定しているのは、requestsでは何も指定しないとapplication/x-www-form-urlencodedが設定され
BadRequestエラーになったためです。
以下はPUTに対応するflask-peeweeのRestAPIのソースですが、request.dataが空文字になってしまい、結果ValueErrorになります
flaskext/rest.py
def edit(self, obj): try: data = json.loads(request.data) except ValueError: return self.response_bad_request()