Repository navigation
Expand file tree
/
Copy pathroles.py
More file actions
47 lines (35 loc) · 1.6 KB
/
Copy pathroles.py
File metadata and controls
47 lines (35 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# -*- coding: utf-8 -*-
"""
Auth-SHA1/HMAC-Roles
~~~~~~~~~~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617) and user
roles.
This script assumes that user accounts are stored in an 'accounts' MongoDB
collection, that passwords are stored as SHA1/HMAC hashes and that user
roles are stored in a 'roles' array. All API resources/methods will be
secured unless they are made explicitly public (by fiddling with some
settings you can open one or more resources and/or methods to public access
-see docs).
Since we are using werkzeug we don't need any extra import (werkzeug being
one of Flask/Eve prerequisites).
Checkout Eve at https://github.com/nicolaiarocci/eve
This snippet by Nicola Iarocci can be used freely for anything you like.
Consider it public domain.
"""
from eve import Eve
from eve.auth import BasicAuth
from werkzeug.security import check_password_hash
from settings_security import SETTINGS
class RolesAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource, method):
# use Eve's own db driver; no additional connections/resources are used
accounts = app.data.driver.db['accounts']
lookup = {'username': username}
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 and check_password_hash(account['password'], password)
if __name__ == '__main__':
app = Eve(auth=RolesAuth, settings=SETTINGS)
app.run()