Skip to content

Instantly share code, notes, and snippets.

@nicolaiarocci
Last active December 13, 2015 21:38
Show Gist options
  • Save nicolaiarocci/4978611 to your computer and use it in GitHub Desktop.
Save nicolaiarocci/4978611 to your computer and use it in GitHub Desktop.
Securing a Eve-powered REST API, bcrypt-style
# -*- coding: utf-8 -*-
"""
Auth-BCrypt
~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617).
This script assumes that user accounts are stored in a MongoDB collection
('accounts'), and that passwords are stored as BCrypt hashes. All API
resources/methods will be secured unless they are made explicitly public
(you can open to public access one or more resources and/or methods by
toggling some API settings - see docs).
You will need to install py-bcrypt: ``pip install py-bcrypt``
Eve @ https://github.com/nicolaiarocci/eve
This snippet by Nicola Iarocci can be used freely for anything you like.
Consider it public domain.
"""
import bcrypt
from eve import Eve
from eve.auth import BasicAuth
class BCryptAuth(BasicAuth):
def check_auth(self, username, password):
# use Eve's own db driver; no additional connections/resources are used
accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username})
return account and \
bcrypt.hashpw(password, account['password']) == account['password']
if __name__ == '__main__':
app = Eve(auth=BCryptAuth)
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment