Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
userid, hmac_hash = auth.split(":")
self.set_user_or_token(userid)
except:
auth = None
return auth and self.check_auth(
userid,
hmac_hash,
request.headers,
request.get_data(),
allowed_roles,
resource,
method,
)
class TokenAuth(BasicAuth):
""" Implements Token AUTH logic. Should be subclassed to implement custom
authentication checking.
.. versionchanged:: 0.7
Add support for get_user_or_token()/set_user_or_token(). This allows for
easy retrieval of active user information. See #846.
.. versionchanged:: 0.4
Ensure all errors returns a parseable body #366.
.. versionchanged:: 0.0.7
Support for 'resource' argument.
.. versionadded:: 0.0.5
"""
def authorized(self, allowed_roles, resource, method):
""" Validates the the current request is allowed to pass through.
:param allowed_roles: allowed roles for the current request, can be a
string or a list of roles.
:param resource: resource being requested.
"""
auth = request.authorization
if auth:
self.set_user_or_token(auth.username)
return auth and self.check_auth(
auth.username, auth.password, allowed_roles, resource, method
)
class HMACAuth(BasicAuth):
""" Hash Message Authentication Code (HMAC) authentication logic. Must be
subclassed to implement custom authorization checking.
.. versionchanged:: 0.7
Add support for get_user_or_token()/set_user_or_token(). This allows for
easy retrieval of active user information. See #846.
.. versionchanged:: 0.4
Ensure all errors returns a parseable body #366.
.. versionchanged:: 0.0.9
Replaced the now deprecated request.data with request.get_data().
.. versionchanged:: 0.0.7
Support for 'resource' argument.
#!/usr/bin/env python
from eve import Eve
from eve.auth import BasicAuth
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource, method):
return username == 'admin' and password == 'Fby1XyweBNR6g'
def run():
app = Eve(auth=MyBasicAuth)
app.run()
if __name__ == '__main__':
run()
from eve import Eve
from eve.auth import BasicAuth
class Authenticate(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
print resource
print method
if resource == 'user' and method == 'GET':
user = app.data.driver.db['user']
user = user.find_one({'username': username,'password':password})
if user:
return True
else:
return False
elif resource == 'user' and method == 'POST':
print username
print password
return username == 'admin' and password == 'password'
Active tokens are stored in redis via the Flask-Sentinel extension. When
a request hits a API endpoint all we need to do is verify that a token
is provided with the request and that said token is active.
See https://github.com/pyeve/flask-sentinel
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from eve.auth import BasicAuth
from flask import request
from redis import StrictRedis
class BearerAuth(BasicAuth):
""" Overrides Eve's built-in basic authorization scheme and uses Redis to
validate bearer token
"""
def __init__(self):
super(BearerAuth, self).__init__()
self.redis = StrictRedis()
self.redis.connection_pool = ConnectionPool.from_url(os.environ.get(
'REDIS_URL',
'redis://localhost:6379'))
def check_auth(self, token, allowed_roles, resource, method):
""" Check if API request is authorized.
Examines token in header and checks Redis cache to see if token is
valid. If so, request is allowed.
Applicable only to fields with type `list`.
"""
if not isinstance(value, list):
self._error(field, '`unique_elements` rule allowed only for `list` fields')
if unique_elements and len(value) > 1:
if isinstance(value[0], dict):
uniqified = set(frozenset(element.items()) for element in value)
else:
uniqified = set(frozenset(element) for element in value)
if len(uniqified) < len(value):
self._error(field,
'elements within the list `%s` are not unique' %
value)
class VpapiBasicAuth(BasicAuth):
"""Authentication used for write access to the API."""
def check_auth(self, username, password, allowed_roles, resource, method):
return [username, password] in config.AUTHORIZED_USERS
def create_app(country_code, parliament):
# Merge parliament specific settings on top of common settings.
instance_settings = settings.common
instance_settings.update({
'URL_PREFIX': country_code + '/' + parliament['code'],
'MONGO_DBNAME': country_code + '_' + parliament['code'].replace('-', '_'),
'AUTHORIZED_USERS': parliament['authorized_users'],
})
app = Eve(
settings=instance_settings,
You will need to install py-bcrypt: ``pip install py-bcrypt``
Eve @ https://github.com/pyeve/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
from settings_security import SETTINGS
class BCryptAuth(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"]
account = accounts.find_one({"username": username})
return (
account
and bcrypt.hashpw(password, account["password"]) == account["password"]
)
if __name__ == "__main__":
app = Eve(auth=BCryptAuth, settings=SETTINGS)
app.run()
from eve import Eve
from eve.auth import BasicAuth, TokenAuth
from eve.io.base import BaseJSONEncoder
from eve.io.mongo import Validator
from flask import abort, url_for, current_app
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
from models import User
SENTRY_URL = os.environ.get('SENTRY_URL', '')
class MockBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
if not len(username):
return False
user = None
if len(password):
# FIXME: restrict login+password access for a minimal amount of
# resources
try:
username = urllib.unquote(username)
except:
pass
users = User.search(username, full_object=True)
if users:
"type": "oauth2",
"description": "oAuth2 password credentials.",
"flows": {
"password": {
# TODO why does this not work with a relative path?
"tokenUrl": url
+ app.config["SENTINEL_ROUTE_PREFIX"]
+ app.config["SENTINEL_TOKEN_URL"],
"scopes": {},
}
},
}
}
elif isinstance(app.auth, TokenAuth):
return {"BearerAuth": {"type": "http", "scheme": "bearer"}}
elif isinstance(app.auth, BasicAuth):
return {"BasicAuth": {"type": "http", "scheme": "basic"}}
else:
pass # FIXME
# TODO use app.auth to build the security scheme
from notification import MAIL_LOG_FROM_DEFAULT, Notification, TEMPLATES_DIR
import requests
from jinja2 import Environment, FileSystemLoader
except ImportError as e:
print('Needed pip modules not found. Please make sure your virtualenv is '
'activated and pip requirements well installed.')
raise
import argparse
import os
ACCOUNTS_FILE = 'accounts.yml'
ONE_TIME_SECRET_URL = 'https://onetimesecret.com/api/v1/share'
class BCryptAuth(BasicAuth):
_accounts = {'api': '$2a$12$HHKaH4pKaz1iiv2lmqQXmuF1./zWsFIDphpU9JXOFHRrBIkhbF.si'}
def __init__(self):
read_accounts(self._accounts)
def check_auth(self, username, password, allowed_roles, resource, method):
stored_password = self._accounts.get(username, None)
return (stored_password and
bcrypt.hashpw(password, stored_password) == stored_password)
def load_conf(user, password, email):
rootdir = os.path.dirname(os.path.realpath(__file__))
conf_file_path = rootdir + '/config.yml'
with open(conf_file_path, 'r') as conf_file: