1

設定.py:

RESOURCE_METHODS = ['GET', 'POST', 'DELETE']

ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']

schema = {
    'username': {
        'type': 'string',
        'required': True,
    },
    'password': {
        'type': 'string',
        'required': True,
    },
    'roles': {
        'type': 'list',
        'allowed': ['user', 'admin'],
        'required': True,
    },
    'token': {
        'type': 'string',
        'required': True,
    }
}

accounts = {
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'username'
    },
    'cache_control': '',
    'cache_expires': 0,
    'allowed_roles': ['sudo', 'admin', 'user'],
    'extra_response_fields': ['token'],
    'schema': schema
}

DOMAIN = {
    'accounts': accounts,
}

run.py:

from eve import Eve
from eve.auth import TokenAuth
import random
import string


class RolesAuth(TokenAuth):
     def check_auth(self, token, allowed_roles, resource, method):
         # use Eve's own db driver; no additional connections/resources are used
         accounts = app.data.driver.db['accounts']
         lookup = {'token': token}
         if allowed_roles:
             #only retrieve a user if his roles match ``allowed_roles``
             lookup['roles'] = {'$in': allowed_roles}
         account = accounts.find_one(lookup)
         return account


def add_token(documents):
     # Don't use this in production:
     # You should at least make sure that the token is unique.
     for document in documents:
         document["token"] = (''.join(random.choice(string.ascii_uppercase)
                                      for x in range(10)))


if __name__ == '__main__':
     app = Eve(auth=RolesAuth)
     app.on_insert_accounts += add_token
     app.run()

mongodb (アカウント コレクション):

db.accounts.find({username:"prova"})
{ "_id" : ObjectId("num"), "username" : "prova", "password" : "prova", "roles" : "admin", "token" : "blabla" }

コマンド (cHJvdmE6YmxhYmxhprova:blabla):

curl -X GET "http://localhost:5000/accounts" -H "Content-Type: application/json" -H "Authorization: Basic cHJvdmE6YmxhYmxh"

私の問題は、認証が間違っていることを示す 401 エラーが発生することです。
また、base64 でエンコードされたトークンのみを使用してみましたが、何も変わりませんでした。何か案は?
私は Eve-0.4 と Eve-0.5 を使用しています。

4

1 に答える 1