Compare commits

..
10 Commits
Author SHA1 Message Date
Matt Wright 0ddbcdca06 PEP 8 2012-06-12 12:28:59 -04:00
Matt Wright edf41096d7 Fix #13 2012-06-12 12:03:54 -04:00
Matt Wright 3ce907db79 Add requirements.txt 2012-05-03 17:34:46 -04:00
Matt Wright 5c9bc541f9 1.2.2 release, includes a minor bug fix 2012-04-27 13:48:03 -04:00
Matt Wright f7147648ba Add change note 2012-04-27 13:44:14 -04:00
Matt Wright 30b72cb7f4 Merge branch 'develop' of github.com:mattupstate/flask-security into develop 2012-04-27 13:39:15 -04:00
Matt Wright ab08abcaf9 Fix #4 2012-04-27 13:37:50 -04:00
Matt Wright 0227d987fe Fix #3 2012-04-26 11:35:24 -03:00
Matt Wright 5df01af720 Fix bad code example 2012-04-26 11:20:34 -03:00
Matt Wright 0acf4bca0d remove __version__ because it was causing problems with installation from pypi 2012-04-04 12:16:00 -04:00
13 changed files with 357 additions and 305 deletions
+15
View File
@@ -3,6 +3,21 @@ Flask-Security Changelog
Here you can see the full list of changes between each Flask-Security release.
Version 1.2.3
-------------
Released June 12th, 2012
- Fixed a bug in the RoleMixin eq/ne functions
Version 1.2.2
-------------
Released April 27th, 2012
- Fixed bug where `roles_required` and `roles_accepted` did not pass the next
argument to the login view
Version 1.2.1
-------------
+3 -3
View File
@@ -18,7 +18,7 @@ import sys, os
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
sys.path.append(os.path.abspath('_themes'))
from flask_security import __version__
#from setup import __version__
# -- General configuration -----------------------------------------------------
@@ -50,7 +50,7 @@ copyright = u'2012, Matt Wright'
# built documents.
#
# The short X.Y version.
version = __version__
version = '1.2.3'
# The full version, including alpha/beta/rc tags.
release = version
@@ -99,7 +99,7 @@ html_theme = 'flask_small'
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'github_fork': 'mattupstate/flask-security',
'github_fork': 'mattupstate/flask-security',
'index_logo': False
}
+4 -4
View File
@@ -85,7 +85,7 @@ First thing you'll want to do is setup your application and datastore::
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import (User, Security, LoginForm, login_required,
roles_accepted, user_datastore)
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDataStore
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
@@ -94,14 +94,14 @@ First thing you'll want to do is setup your application and datastore::
db = SQLAlchemy(app)
Security(app, SQLAlchemyUserDatastore(db))
You'll probably want to at least one user to the database to test this out, so
you can add something such as the following to quickly add an initial user::
You'll probably want to at least one user to the database to test this out.
There are many ways to do this, but this is a quick and dirty way to do it::
@app.before_first_request
def before_first_request():
user_datastore.create_role(name='admin')
user_datastore.create_user(username='matt', email='matt@something.com',
password='password', roles['admin'])
password='password', roles=['admin'])
Next you'll want to setup your login screen. Setup your view::
+1
View File
@@ -5,6 +5,7 @@
{{ form.username.label }} {{ form.username }}<br/>
{{ form.password.label }} {{ form.password }}<br/>
{{ form.remember.label }} {{ form.remember }}<br/>
{{ form.next }}
{{ form.submit }}
</form>
<p>{{ content }}</p>
+147 -134
View File
@@ -3,54 +3,50 @@
flask.ext.security
~~~~~~~~~~~~~~~~~~
Flask-Security is a Flask extension that aims to add quick and simple
Flask-Security is a Flask extension that aims to add quick and simple
security via Flask-Login, Flask-Principal, Flask-WTF, and passlib.
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
__version__ = '1.2.1'
import sys
from datetime import datetime
from types import StringType
from flask import (current_app, Blueprint, flash, redirect, request,
session, _request_ctx_stack, url_for, abort, g)
from flask.ext.login import (AnonymousUser as AnonymousUserBase,
UserMixin as BaseUserMixin, LoginManager, login_required, login_user,
logout_user, current_user, user_logged_in, user_logged_out)
from flask.ext.principal import (Identity, Principal, RoleNeed, UserNeed,
Permission, AnonymousIdentity, identity_changed, identity_loaded)
from flask.ext.wtf import (Form, TextField, PasswordField, SubmitField,
HiddenField, Required, ValidationError, BooleanField, Email)
from functools import wraps
from flask import current_app, Blueprint, flash, redirect, request, \
session, url_for
from flask.ext.login import AnonymousUser as AnonymousUserBase, \
UserMixin as BaseUserMixin, LoginManager, login_required, login_user, \
logout_user, current_user, login_url
from flask.ext.principal import Identity, Principal, RoleNeed, UserNeed, \
Permission, AnonymousIdentity, identity_changed, identity_loaded
from flask.ext.wtf import Form, TextField, PasswordField, SubmitField, \
HiddenField, Required, BooleanField
from passlib.context import CryptContext
from werkzeug.utils import import_string
from werkzeug.local import LocalProxy
class User(object):
"""User model"""
class Role(object):
"""Role model"""
URL_PREFIX_KEY = 'SECURITY_URL_PREFIX'
AUTH_PROVIDER_KEY = 'SECURITY_AUTH_PROVIDER'
PASSWORD_HASH_KEY = 'SECURITY_PASSWORD_HASH'
URL_PREFIX_KEY = 'SECURITY_URL_PREFIX'
AUTH_PROVIDER_KEY = 'SECURITY_AUTH_PROVIDER'
PASSWORD_HASH_KEY = 'SECURITY_PASSWORD_HASH'
USER_DATASTORE_KEY = 'SECURITY_USER_DATASTORE'
LOGIN_FORM_KEY = 'SECURITY_LOGIN_FORM'
AUTH_URL_KEY = 'SECURITY_AUTH_URL'
LOGOUT_URL_KEY = 'SECURITY_LOGOUT_URL'
LOGIN_VIEW_KEY = 'SECURITY_LOGIN_VIEW'
POST_LOGIN_KEY = 'SECURITY_POST_LOGIN'
POST_LOGOUT_KEY = 'SECURITY_POST_LOGOUT'
LOGIN_FORM_KEY = 'SECURITY_LOGIN_FORM'
AUTH_URL_KEY = 'SECURITY_AUTH_URL'
LOGOUT_URL_KEY = 'SECURITY_LOGOUT_URL'
LOGIN_VIEW_KEY = 'SECURITY_LOGIN_VIEW'
POST_LOGIN_KEY = 'SECURITY_POST_LOGIN'
POST_LOGOUT_KEY = 'SECURITY_POST_LOGOUT'
FLASH_MESSAGES_KEY = 'SECURITY_FLASH_MESSAGES'
DEBUG_LOGIN = 'User %s logged in. Redirecting to: %s'
@@ -79,40 +75,47 @@ class BadCredentialsError(Exception):
"""Raised when an authentication attempt fails due to an error with the
provided credentials.
"""
class AuthenticationError(Exception):
"""Raised when an authentication attempt fails due to invalid configuration
or an unknown reason.
"""
"""
class UserNotFoundError(Exception):
"""Raised by a user datastore when there is an attempt to find a user by
"""Raised by a user datastore when there is an attempt to find a user by
their identifier, often username or email, and the user is not found.
"""
class RoleNotFoundError(Exception):
"""Raised by a user datastore when there is an attempt to find a role and
the role cannot be found.
"""
class UserIdNotFoundError(Exception):
"""Raised by a user datastore when there is an attempt to find a user by
"""Raised by a user datastore when there is an attempt to find a user by
ID and the user is not found.
"""
class UserDatastoreError(Exception):
"""Raised when a user datastore experiences an unexpected error
"""
class UserCreationError(Exception):
"""Raised when an error occurs when creating a user
"""
class RoleCreationError(Exception):
"""Raised when an error occurs when creating a role
"""
#: App logger for convenience
logger = LocalProxy(lambda: current_app.logger)
@@ -126,37 +129,40 @@ login_manager = LocalProxy(lambda: current_app.login_manager)
pwd_context = LocalProxy(lambda: current_app.pwd_context)
#: User datastore
user_datastore = LocalProxy(lambda: getattr(current_app,
user_datastore = LocalProxy(lambda: getattr(current_app,
current_app.config[USER_DATASTORE_KEY]))
def roles_required(*args):
"""View decorator which specifies that a user must have all the specified
roles. Example::
@app.route('/dashboard')
@roles_required('admin', 'editor')
def dashboard():
return 'Dashboard'
The current user must have both the `admin` role and `editor` role in order
to view the page.
:param args: The required roles.
:param args: The required roles.
"""
roles = args
perm = Permission(*[RoleNeed(role) for role in roles])
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated():
return redirect(current_app.config[LOGIN_VIEW_KEY])
return redirect(
login_url(current_app.config[LOGIN_VIEW_KEY], request.url))
if perm.can():
return fn(*args, **kwargs)
logger.debug('Identity does not provide all of the '
'following roles: %s' % [r for r in roles])
do_flash(FLASH_PERMISSIONS, 'error')
return redirect(request.referrer or '/')
return decorated_view
@@ -164,34 +170,36 @@ def roles_required(*args):
def roles_accepted(*args):
"""View decorator which specifies that a user must have at least one of the
"""View decorator which specifies that a user must have at least one of the
specified roles. Example::
@app.route('/create_post')
@roles_accepted('editor', 'author')
def create_post():
return 'Create Post'
The current user must have either the `editor` role or `author` role in
The current user must have either the `editor` role or `author` role in
order to view the page.
:param args: The possible roles.
:param args: The possible roles.
"""
roles = args
perms = [Permission(RoleNeed(role)) for role in roles]
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated():
return redirect(current_app.config[LOGIN_VIEW_KEY])
return redirect(
login_url(current_app.config[LOGIN_VIEW_KEY], request.url))
for perm in perms:
if perm.can():
return fn(*args, **kwargs)
logger.debug('Identity does not provide at least one of '
'the following roles: %s' % [r for r in roles])
do_flash(FLASH_PERMISSIONS, 'error')
return redirect(request.referrer or '/')
return decorated_view
@@ -201,30 +209,28 @@ def roles_accepted(*args):
class RoleMixin(object):
"""Mixin for `Role` model definitions"""
def __eq__(self, other):
return self.name == other.name
return self.name == other or self.name == getattr(other, 'name', None)
def __ne__(self, other):
return self.name != other.name
return self.name != other and self.name != getattr(other, 'name', None)
def __str__(self):
return '<Role name=%s, description=%s>' % (self.name, self.description)
class UserMixin(BaseUserMixin):
"""Mixin for `User` model definitions"""
def is_active(self):
"""Returns `True` if the user is active."""
"""Returns `True` if the user is active."""
return self.active
def has_role(self, role):
"""Returns `True` if the user identifies with the specified role.
:param role: A role name or `Role` instance"""
if not isinstance(role, Role):
role = Role(name=role)
return role in self.roles
def __str__(self):
ctx = (str(self.id), self.username, self.email)
return '<User id=%s, username=%s, email=%s>' % ctx
@@ -233,8 +239,8 @@ class UserMixin(BaseUserMixin):
class AnonymousUser(AnonymousUserBase):
def __init__(self):
super(AnonymousUser, self).__init__()
self.roles = [] # TODO: Make this immutable?
self.roles = [] # TODO: Make this immutable?
def has_role(self, *args):
"""Returns `False`"""
return False
@@ -242,78 +248,80 @@ class AnonymousUser(AnonymousUserBase):
class Security(object):
"""The :class:`Security` class initializes the Flask-Security extension.
:param app: The application.
:param datastore: An instance of a user datastore.
"""
def __init__(self, app=None, datastore=None):
self.init_app(app, datastore)
def init_app(self, app, datastore):
"""Initializes the Flask-Security extension for the specified
"""Initializes the Flask-Security extension for the specified
application and datastore implentation.
:param app: The application.
:param datastore: An instance of a user datastore.
"""
if app is None or datastore is None: return
if app is None or datastore is None:
return
# TODO: change blueprint name
blueprint = Blueprint('auth', __name__)
configured = {}
for key, value in default_config.items():
configured[key] = app.config.get(key, value)
app.config.update(configured)
config = app.config
# setup the login manager extension
login_manager = LoginManager()
login_manager.anonymous_user = AnonymousUser
login_manager.login_view = config[LOGIN_VIEW_KEY]
login_manager.setup_app(app)
app.login_manager = login_manager
Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
Form = get_class_from_config(LOGIN_FORM_KEY, config)
pw_hash = config[PASSWORD_HASH_KEY]
app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash)
app.auth_provider = Provider(Form)
app.principal = Principal(app)
from flask.ext import security as s
s.User, s.Role = datastore.get_models()
setattr(app, config[USER_DATASTORE_KEY], datastore)
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
if hasattr(current_user, 'id'):
identity.provides.add(UserNeed(current_user.id))
for role in current_user.roles:
identity.provides.add(RoleNeed(role.name))
identity.user = current_user
@login_manager.user_loader
def load_user(user_id):
try:
try:
return datastore.with_id(user_id)
except Exception, e:
logger.error('Error getting user: %s' % e)
logger.error('Error getting user: %s' % e)
return None
auth_url = config[AUTH_URL_KEY]
@blueprint.route(auth_url, methods=['POST'], endpoint='authenticate')
def authenticate():
try:
form = Form()
user = auth_provider.authenticate(form)
if login_user(user, remember=form.remember.data):
redirect_url = get_post_login_redirect()
identity_changed.send(app, identity=Identity(user.id))
@@ -321,66 +329,66 @@ class Security(object):
return redirect(redirect_url)
raise BadCredentialsError(FLASH_INACTIVE)
except BadCredentialsError, e:
message = '%s' % e
do_flash(message, 'error')
redirect_url = request.referrer or login_manager.login_view
logger.error(ERROR_LOGIN % (message, redirect_url))
return redirect(redirect_url)
@blueprint.route(config[LOGOUT_URL_KEY], endpoint='logout')
@login_required
def logout():
for value in ('identity.name', 'identity.auth_type'):
session.pop(value, None)
identity_changed.send(app, identity=AnonymousIdentity())
logout_user()
redirect_url = find_redirect(POST_LOGOUT_KEY)
logger.debug(DEBUG_LOGOUT % redirect_url)
return redirect(redirect_url)
app.register_blueprint(blueprint, url_prefix=config[URL_PREFIX_KEY])
class LoginForm(Form):
"""The default login form"""
username = TextField("Username or Email",
username = TextField("Username or Email",
validators=[Required(message="Username not provided")])
password = PasswordField("Password",
password = PasswordField("Password",
validators=[Required(message="Password not provided")])
remember = BooleanField("Remember Me")
next = HiddenField()
submit = SubmitField("Login")
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.next.data = request.args.get('next', None)
class AuthenticationProvider(object):
"""The default authentication provider implementation.
:param login_form_class: The login form class to use when authenticating a
user
"""
def __init__(self, login_form_class=None):
self.login_form_class = login_form_class or LoginForm
def login_form(self, formdata=None):
"""Returns an instance of the login form with the provided form.
:param formdata: The incoming form data"""
return self.login_form_class(formdata)
def authenticate(self, form):
"""Processes an authentication request and returns a user instance if
authentication is successful.
:param form: An instance of a populated login form
"""
if not form.validate():
@@ -388,13 +396,13 @@ class AuthenticationProvider(object):
raise BadCredentialsError(form.username.errors[0])
if form.password.errors:
raise BadCredentialsError(form.password.errors[0])
return self.do_authenticate(form.username.data, form.password.data)
def do_authenticate(self, user_identifier, password):
"""Returns the authenticated user if authentication is successfull. If
authentication fails an appropriate error is raised
:param user_identifier: The user's identifier, either an email address
or username
:param password: The user's unencrypted password
@@ -409,21 +417,22 @@ class AuthenticationProvider(object):
self.auth_error('Invalid user service: %s' % e)
except Exception, e:
self.auth_error('Unexpected authentication error: %s' % e)
# compare passwords
if pwd_context.verify(password, user.password):
return user
# bad match
raise BadCredentialsError("Password does not match")
def auth_error(self, msg):
"""Sends an error log message and raises an authentication error.
:param msg: An authentication error message"""
logger.error(msg)
raise AuthenticationError(msg)
def do_flash(message, category):
if current_app.config[FLASH_MESSAGES_KEY]:
flash(message, category)
@@ -433,41 +442,45 @@ def get_class_by_name(clazz):
"""Get a reference to a class by its string representation."""
parts = clazz.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
m = getattr(m, comp)
return m
def get_class_from_config(key, config):
"""Get a reference to a class by its configuration key name."""
try:
return get_class_by_name(config[key])
except Exception, e:
raise AttributeError(
"Could not get class '%s' for Auth setting '%s' >> %s" %
(config[key], key, e))
"Could not get class '%s' for Auth setting '%s' >> %s" %
(config[key], key, e))
def get_url(endpoint_or_url):
"""Returns a URL if a valid endpoint is found. Otherwise, returns the
"""Returns a URL if a valid endpoint is found. Otherwise, returns the
provided value."""
try:
try:
return url_for(endpoint_or_url)
except:
except:
return endpoint_or_url
def get_post_login_redirect():
"""Returns the URL to redirect to after a user logs in successfully"""
return (get_url(request.args.get('next')) or
get_url(request.form.get('next')) or
return (get_url(request.args.get('next')) or
get_url(request.form.get('next')) or
find_redirect(POST_LOGIN_KEY))
def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully"""
result = (get_url(session.pop(key.lower(), None)) or
result = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
try:
try:
del session[key.lower()]
except:
except:
pass
return result
+60 -56
View File
@@ -3,7 +3,7 @@
flask.ext.security.datastore
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains an abstracted user datastore.
This module contains an abstracted user datastore.
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
@@ -13,12 +13,13 @@ from datetime import datetime
from flask.ext import security
from flask.ext.security import UserCreationError, RoleCreationError, pwd_context
class UserDatastore(object):
"""Abstracted user datastore. Always extend this class and implement the
:attr:`get_models`, :attr:`_save_model`, :attr:`_do_with_id`,
"""Abstracted user datastore. Always extend this class and implement the
:attr:`get_models`, :attr:`_save_model`, :attr:`_do_with_id`,
:attr:`_do_find_user`, and :attr:`_do_find_role` methods.
:param db: An instance of a configured databse manager from a Flask
:param db: An instance of a configured databse manager from a Flask
extension such as Flask-SQLAlchemy or Flask-MongoEngine
:param user_account_mixin: An optional mixin class that specifies additional
fields to be added to the user model
@@ -26,41 +27,41 @@ class UserDatastore(object):
def __init__(self, db, user_account_mixin=None):
self.db = db
self.user_account_mixin = user_account_mixin or object
def get_models(self):
"""Returns configured `User` and `Role` models for the datastore
"""Returns configured `User` and `Role` models for the datastore
implementation"""
raise NotImplementedError(
"User datastore does not implement get_models method")
def _save_model(self, model, **kwargs):
raise NotImplementedError(
"User datastore does not implement _save_model method")
def _do_with_id(self, id):
raise NotImplementedError(
"User datastore does not implement _do_with_id method")
def _do_find_user(self):
raise NotImplementedError(
"User datastore does not implement _do_find_user method")
def _do_find_role(self):
raise NotImplementedError(
"User datastore does not implement _do_find_role method")
def _do_add_role(self, user, role):
user, role = self._prepare_role_modify_args(user, role)
if role not in user.roles:
user.roles.append(role)
return user
def _do_remove_role(self, user, role):
user, role = self._prepare_role_modify_args(user, role)
if role in user.roles:
user.roles.remove(role)
return user
def _do_toggle_active(self, user, active=None):
user = self.find_user(user)
if active is None:
@@ -68,98 +69,101 @@ class UserDatastore(object):
elif active != user.active:
user.active = active
return user
def _do_deactive_user(self, user):
return self._do_toggle_active(user, False)
def _do_active_user(self, user):
return self._do_toggle_active(user, True)
def _prepare_role_modify_args(self, user, role):
if isinstance(user, security.User):
user = user.username or user.email
if isinstance(role, security.Role):
role = role.name
return self.find_user(user), self.find_role(role)
def _prepare_create_role_args(self, kwargs):
for key in ('name', 'description'):
kwargs[key] = kwargs.get(key, None)
if kwargs['name'] is None:
raise RoleCreationError("Missing name argument")
return kwargs
def _prepare_create_user_args(self, kwargs):
username = kwargs.get('username', None)
email = kwargs.get('email', None)
password = kwargs.get('password', None)
if username is None and email is None:
raise UserCreationError('Missing username and/or email arguments')
if password is None:
raise UserCreationError('Missing password argument')
roles = kwargs.get('roles', [])
for i, role in enumerate(roles):
rn = role.name if isinstance(role, security.Role) else role
# see if the role exists
roles[i] = self.find_role(rn)
kwargs['roles'] = roles
now = datetime.utcnow()
kwargs['created_at'], kwargs['modified_at'] = now, now
pw = kwargs['password']
if not pwd_context.identify(pw):
kwargs['password'] = pwd_context.encrypt(pw)
return kwargs
def with_id(self, id):
"""Returns a user with the specified ID.
:param id: User ID"""
user = self._do_with_id(id)
if user: return user
if user:
return user
raise security.UserIdNotFoundError()
def find_user(self, user):
"""Returns a user based on the specified identifier.
"""Returns a user based on the specified identifier.
:param user: User identifier, usually a username or email address
"""
user = self._do_find_user(user)
if user: return user
if user:
return user
raise security.UserNotFoundError()
def find_role(self, role):
"""Returns a role based on its name.
:param role: Role name
"""
role = self._do_find_role(role)
if role: return role
if role:
return role
raise security.RoleNotFoundError()
def create_role(self, **kwargs):
"""Creates and returns a new role.
:param name: Role name
:param description: Role description
"""
role = security.Role(**self._prepare_create_role_args(kwargs))
return self._save_model(role)
def create_user(self, **kwargs):
"""Creates and returns a new user.
:param username: Username
:param email: Email address
:param password: Unencrypted password
@@ -167,35 +171,35 @@ class UserDatastore(object):
"""
user = security.User(**self._prepare_create_user_args(kwargs))
return self._save_model(user)
def add_role_to_user(self, user, role):
"""Adds a role to a user if the user does not have it already. Returns
"""Adds a role to a user if the user does not have it already. Returns
the modified user.
:param user: A User instance or a user identifier
:param role: A Role instance or a role name
"""
return self._save_model(self._do_add_role(user, role))
def remove_role_from_user(self, user, role, commit=True):
"""Removes a role from a user if the user has the role. Returns the
"""Removes a role from a user if the user has the role. Returns the
modified user.
:param user: A User instance or a user identifier
:param role: A Role instance or a role name
"""
return self._save_model(self._do_remove_role(user, role))
def deactivate_user(self, user):
"""Deactivates a user and returns the modified user.
:param user: A User instance or a user identifier
"""
return self._save_model(self._do_deactive_user(user))
def activate_user(self, user, commit=True):
"""Activates a user and returns the modified user.
:param user: A User instance or a user identifier
"""
return self._save_model(self._do_active_user(user))
return self._save_model(self._do_active_user(user))
+22 -20
View File
@@ -12,60 +12,62 @@
from flask.ext import security
from flask.ext.security import UserMixin, RoleMixin
from flask.ext.security.datastore import UserDatastore
class MongoEngineUserDatastore(UserDatastore):
"""A MongoEngine datastore implementation for Flask-Security.
Example usage::
"""A MongoEngine datastore implementation for Flask-Security.
Example usage::
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.security import Security
from flask.ext.security.datastore.mongoengine import MongoEngineUserDatastore
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['MONGODB_DB'] = 'flask_security_example'
app.config['MONGODB_HOST'] = 'localhost'
app.config['MONGODB_PORT'] = 27017
db = MongoEngine(app)
Security(app, MongoEngineUserDatastore(db))
"""
def get_models(self):
db = self.db
class Role(db.Document, RoleMixin):
"""MongoEngine Role model"""
name = db.StringField(required=True, unique=True, max_length=80)
description = db.StringField(max_length=255)
class User(db.Document, UserMixin, self.user_account_mixin):
"""MongoEngine User model"""
username = db.StringField(unique=True, max_length=255)
email = db.StringField(unique=True, max_length=255)
password = db.StringField(required=True, max_length=120)
active = db.BooleanField(default=True)
roles= db.ListField(db.ReferenceField(Role), default=[])
roles = db.ListField(db.ReferenceField(Role), default=[])
created_at = db.DateTimeField()
modified_at = db.DateTimeField()
return User, Role
def _save_model(self, model):
model.save()
return model
def _do_with_id(self, id):
try: return security.User.objects.get(id=id)
except: return None
try:
return security.User.objects.get(id=id)
except:
return None
def _do_find_user(self, user):
return security.User.objects(username=user).first() or \
security.User.objects(email=user).first()
def _do_find_role(self, role):
return security.Role.objects(name=role).first()
+24 -24
View File
@@ -12,45 +12,46 @@
from flask.ext import security
from flask.ext.security import UserMixin, RoleMixin
from flask.ext.security.datastore import UserDatastore
class SQLAlchemyUserDatastore(UserDatastore):
"""A SQLAlchemy datastore implementation for Flask-Security.
Example usage::
"""A SQLAlchemy datastore implementation for Flask-Security.
Example usage::
from flask import Flask
from flask.ext.security import Security
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/flask_security_example.sqlite'
db = SQLAlchemy(app)
Security(app, SQLAlchemyUserDatastore(db))
"""
def get_models(self):
db = self.db
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('role.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('user.id')))
class Role(db.Model, RoleMixin):
"""SQLAlchemy Role model"""
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
def __init__(self, name=None, description=None):
self.name = name
self.description = description
class User(db.Model, UserMixin, self.user_account_mixin):
"""SQLAlchemy User model"""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), unique=True)
email = db.Column(db.String(255), unique=True)
@@ -58,12 +59,12 @@ class SQLAlchemyUserDatastore(UserDatastore):
active = db.Column(db.Boolean())
created_at = db.Column(db.DateTime())
modified_at = db.Column(db.DateTime())
roles= db.relationship('Role', secondary=roles_users,
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
def __init__(self, username=None, email=None, password=None,
active=True, roles=None,
def __init__(self, username=None, email=None, password=None,
active=True, roles=None,
created_at=None, modified_at=None):
self.username = username
self.email = email
@@ -72,21 +73,20 @@ class SQLAlchemyUserDatastore(UserDatastore):
self.roles = roles or []
self.created_at = created_at
self.modified_at = modified_at
return User, Role
def _save_model(self, model):
self.db.session.add(model)
self.db.session.commit()
return model
def _do_with_id(self, id):
return security.User.query.get(id)
def _do_find_user(self, user):
return security.User.query.filter_by(username=user).first() or \
security.User.query.filter_by(email=user).first()
def _do_find_role(self, role):
return security.Role.query.filter_by(name=role).first()
+21 -17
View File
@@ -11,9 +11,11 @@
import json
import re
from flask.ext.script import Command, Option
from flask.ext.security import (UserCreationError, UserNotFoundError,
RoleNotFoundError, user_datastore)
from flask.ext.security import user_datastore
def pprint(obj):
print json.dumps(obj, sort_keys=True, indent=4)
@@ -21,7 +23,7 @@ def pprint(obj):
class CreateUserCommand(Command):
"""Create a user"""
option_list = (
Option('-u', '--username', dest='username', default=None),
Option('-e', '--email', dest='email', default=None),
@@ -33,14 +35,14 @@ class CreateUserCommand(Command):
def run(self, **kwargs):
# sanitize active input
ai = re.sub(r'\s', '', str(kwargs['active']))
kwargs['active'] = ai.lower() in ['', 'y','yes', '1', 'active']
kwargs['active'] = ai.lower() in ['', 'y', 'yes', '1', 'active']
# sanitize role input a bit
ri = re.sub(r'\s', '', kwargs['roles'])
kwargs['roles'] = [] if ri == '' else ri.split(',')
user_datastore.create_user(**kwargs)
print 'User created successfully.'
kwargs['password'] = '****'
pprint(kwargs)
@@ -55,11 +57,11 @@ class CreateRoleCommand(Command):
)
def run(self, **kwargs):
role = user_datastore.create_role(**kwargs)
user_datastore.create_role(**kwargs)
print 'Role "%(name)s" created successfully.' % kwargs
class _RoleCommand(Command):
class _RoleCommand(Command):
option_list = (
Option('-u', '--user', dest='user_identifier'),
Option('-r', '--role', dest='role_name'),
@@ -68,7 +70,7 @@ class _RoleCommand(Command):
class AddRoleCommand(_RoleCommand):
"""Add a role to a user"""
def run(self, user_identifier, role_name):
user_datastore.add_role_to_user(user_identifier, role_name)
print "Role '%s' added to user '%s' successfully" % (role_name, user_identifier)
@@ -76,27 +78,29 @@ class AddRoleCommand(_RoleCommand):
class RemoveRoleCommand(_RoleCommand):
"""Add a role to a user"""
def run(self, user_identifier, role_name):
user_datastore.remove_role_from_user(user_identifier, role_name)
print "Role '%s' removed from user '%s' successfully" % (role_name, user_identifier)
class _ToggleActiveCommand(Command):
option_list = (
Option('-u', '--user', dest='user_identifier'),
)
class DeactivateUserCommand(_ToggleActiveCommand):
"""Deactive a user"""
def run(self, user_identifier):
user_datastore.deactivate_user(user_identifier)
print "User '%s' has been deactivated" % user_identifier
class ActivateUserCommand(_ToggleActiveCommand):
"""Deactive a user"""
def run(self, user_identifier):
user_datastore.activate_user(user_identifier)
print "User '%s' has been activated" % user_identifier
print "User '%s' has been activated" % user_identifier
+6
View File
@@ -0,0 +1,6 @@
Flask==0.8
Flask-Login==0.1
Flask-Principal==0.2
Flask-Script==0.3.2
Flask-WTF==0.5.4
passlib=1.5.3
+3 -3
View File
@@ -2,7 +2,7 @@
Flask-Security
--------------
Flask-Security is a Flask extension that aims to add quick and simple security
Flask-Security is a Flask extension that aims to add quick and simple security
via Flask-Login, Flask-Principal, Flask-WTF, and passlib.
Links
@@ -12,12 +12,12 @@ Links
<https://github.com/mattupstate/flask-security/raw/develop#egg=Flask-Security-dev>`_
"""
from flask_security import __version__
from setuptools import setup
setup(
name='Flask-Security',
version=__version__,
version='1.2.3',
url='https://github.com/mattupstate/flask-security',
license='MIT',
author='Matthew Wright',
+39 -34
View File
@@ -1,108 +1,113 @@
import unittest
from example import app
class SecurityTest(unittest.TestCase):
AUTH_CONFIG = None
def setUp(self):
super(SecurityTest, self).setUp()
self.app = self._create_app(self.AUTH_CONFIG or None)
self.app.debug = False
self.app.config['TESTING'] = True
self.client = self.app.test_client()
def _create_app(self, auth_config):
return app.create_sqlalchemy_app(auth_config)
def _get(self, route, content_type=None, follow_redirects=None):
return self.client.get(route, follow_redirects=follow_redirects,
content_type=content_type or 'text/html')
def _post(self, route, data=None, content_type=None, follow_redirects=True):
return self.client.post(route, data=data,
return self.client.post(route, data=data,
follow_redirects=follow_redirects,
content_type=content_type or 'text/html')
def authenticate(self, username, password, endpoint=None):
data = dict(username=username, password=password)
return self._post(endpoint or '/auth', data=data,
return self._post(endpoint or '/auth', data=data,
content_type='application/x-www-form-urlencoded')
def logout(self, endpoint=None):
return self._get(endpoint or '/logout', follow_redirects=True)
class DefaultSecurityTests(SecurityTest):
def test_login_view(self):
r = self._get('/login')
assert 'Login Page' in r.data
def test_authenticate(self):
r = self.authenticate("matt", "password")
assert 'Home Page' in r.data
def test_unprovided_username(self):
r = self.authenticate("", "password")
assert "Username not provided" in r.data
def test_unprovided_password(self):
r = self.authenticate("matt", "")
assert "Password not provided" in r.data
def test_invalid_user(self):
r = self.authenticate("bogus", "password")
assert "Specified user does not exist" in r.data
def test_bad_password(self):
r = self.authenticate("matt", "bogus")
assert "Password does not match" in r.data
def test_inactive_user(self):
r = self.authenticate("tiya", "password")
assert "Inactive user" in r.data
def test_logout(self):
self.authenticate("matt", "password")
r = self.logout()
assert 'Home Page' in r.data
def test_unauthorized_access(self):
r = self._get('/profile', follow_redirects=True)
assert 'Please log in to access this page' in r.data
def test_authorized_access(self):
self.authenticate("matt", "password")
r = self._get("/profile")
assert 'profile' in r.data
def test_valid_admin_role(self):
self.authenticate("matt", "password")
r = self._get("/admin")
assert 'Admin Page' in r.data
def test_invalid_admin_role(self):
self.authenticate("joe", "password")
r = self._get("/admin", follow_redirects=True)
assert 'Home Page' in r.data
def test_roles_accepted(self):
for user in ("matt", "joe"):
self.authenticate(user, "password")
r = self._get("/admin_or_editor")
self.assertIn('Admin or Editor Page', r.data)
self.logout()
self.authenticate("jill", "password")
r = self._get("/admin_or_editor", follow_redirects=True)
self.assertIn('Home Page', r.data)
def test_unauthenticated_role_required(self):
r = self._get('/admin', follow_redirects=True)
self.assertIn('<input id="next"', r.data)
class ConfiguredSecurityTests(SecurityTest):
class ConfiguredSecurityTests(SecurityTest):
AUTH_CONFIG = {
'SECURITY_PASSWORD_HASH': 'bcrypt',
'SECURITY_USER_DATASTORE': 'custom_datastore_name',
@@ -112,22 +117,22 @@ class ConfiguredSecurityTests(SecurityTest):
'SECURITY_POST_LOGIN': '/post_login',
'SECURITY_POST_LOGOUT': '/post_logout'
}
def test_login_view(self):
r = self._get('/custom_login')
assert "Custom Login Page" in r.data
def test_authenticate(self):
r = self.authenticate("matt", "password", endpoint="/custom_auth")
assert 'Post Login' in r.data
def test_logout(self):
self.authenticate("matt", "password", endpoint="/custom_auth")
r = self.logout(endpoint="/custom_logout")
assert 'Post Logout' in r.data
class MongoEngineSecurityTests(DefaultSecurityTests):
def _create_app(self, auth_config):
return app.create_mongoengine_app(auth_config)
return app.create_mongoengine_app(auth_config)
+12 -10
View File
@@ -2,6 +2,7 @@ import unittest
import flask_security
from flask_security import RoleMixin, UserMixin, AnonymousUser
class Role(RoleMixin):
def __init__(self, name, description=None):
self.name = name
@@ -13,32 +14,33 @@ class User(UserMixin):
self.username = username
self.email = email
self.roles = roles
# set the models or we'll get errors
flask_security.User = User
flask_security.Role = Role
admin = Role('admin')
admin2 = Role('admin')
editor = Role('editor')
user = User('matt', 'matt@lp.com', [admin, editor])
class SecurityEntityTests(unittest.TestCase):
def test_role_mixin_equal(self):
def test_role_mixin_equal(self):
self.assertEqual(admin, admin2)
def test_role_mixin_not_equal(self):
def test_role_mixin_not_equal(self):
self.assertNotEqual(admin, editor)
def test_user_mixin_has_role_with_string(self):
self.assertTrue(user.has_role('admin'))
def test_user_mixin_has_role_with_role_obj(self):
self.assertTrue(user.has_role(Role('admin')))
def test_anonymous_user_has_no_roles(self):
au = AnonymousUser()
self.assertEqual(0, len(au.roles))
self.assertFalse(au.has_role('admin'))
self.assertFalse(au.has_role('admin'))