Compare commits

...
19 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
Matt Wright 2e37af8c01 Adjust path so version can get imported properly 2012-03-28 11:51:18 -04:00
Matt Wright 245914cc9a Doc polish and such 2012-03-28 11:44:48 -04:00
Matt Wright 201ee5b708 Merged user-account-mixin branch 2012-03-28 11:08:41 -04:00
Matt Wright 744ded7f1b Consolidate version number in one place 2012-03-27 18:49:01 -04:00
Matt Wright 5a7f4dff47 Initial idea for specifying a user account mixin for user model 2012-03-27 14:27:12 -04:00
Matt Wright dd6ba0995d Random fixes 2012-03-27 14:26:45 -04:00
Matt Wright 5697f7c953 Update install instructions since its on pypi 2012-03-13 20:28:50 -04:00
Matt Wright 144b22a3b9 Minimal README. No need to maintain a README when online docs do the trick 2012-03-13 20:23:07 -04:00
Matt Wright 3c57e169d1 Update version number 2012-03-12 22:21:00 -04:00
18 changed files with 466 additions and 435 deletions
+2
View File
@@ -1,6 +1,8 @@
.DS_Store .DS_Store
*.pyc *.pyc
*.egg *.egg
*.egg-info
.project .project
.pydevproject .pydevproject
.settings .settings
dist
+23
View File
@@ -3,6 +3,29 @@ Flask-Security Changelog
Here you can see the full list of changes between each Flask-Security release. 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
-------------
Released March 28th, 2012
- Added optional user model mixin parameter for datastores
- Added CreateRoleCommand to available Flask-Script commands
Version 1.2.0 Version 1.2.0
------------- -------------
+14 -3
View File
@@ -2,8 +2,19 @@ MIT License
Copyright (C) 2012 by Matt Wright Copyright (C) 2012 by Matt Wright
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+11
View File
@@ -0,0 +1,11 @@
Flask-Security
==============
Simple security for Flask applications combining Flask-Login, Flask-Principal,
Flask-WTF, passlib, and your choice of datastore. Currently SQLAlchemy via
Flask-SQLAlchemy and MongoEngine via Flask-MongoEngine are supported out of the
box. You will need to install the necessary Flask extensions that you'll be
using. Additionally, you may need to install an encryption library such as
py-bcrypt to support bcrypt passwords.
Documentation: http://packages.python.org/Flask-Security/
-120
View File
@@ -1,120 +0,0 @@
# Flask-Security
Simple security for Flask applications combining [Flask-Login](http://packages.python.org/Flask-Login/), [Flask-Principal](http://packages.python.org/Flask-Principal/), [Flask-WTF](http://packages.python.org/Flask-WTF/), [passlib](http://packages.python.org/passlib/), and your choice of datastore. Currently [SQLAlchemy](http://www.sqlalchemy.org) via [Flask-SQLAlchemy](http://packages.python.org/Flask-SQLAlchemy/) and [MongoEngine](http://www.mongoengine.org) via [Flask-MongoEngine](https://github.com/sbook/flask-mongoengine) are supported out of the box. You will need to install the necessary Flask extensions that you'll be using. Additionally, you may need to install an encryption library such as [py-bcrypt](http://www.mindrot.org/projects/py-bcrypt/) to support bcrypt passwords.
## Overview
Flask-Security does a few things that Flask-Login and Flask-Principal don't provide out of the box. They are:
1. Setting up login and logout endpoints
2. Authenticating users based on username or email
3. Limiting access based on user 'roles'
4. User and role creation
5. Password encryption
That being said, you can still hook into things such as the Flask-Login and Flask-Principal signals if need be.
## Getting Started
First, install Flask-Security:
$ mkvirtualenv app-name
$ pip install https://github.com/mattupstate/flask-security/tarball/master
Then install your datastore requirement.
SQLAlchemy:
$ pip install Flask-SQLAlchemy
MongoEngine:
$ pip install https://github.com/sbook/flask-mongoengine/tarball/master
Beyond this, the best place to get started at the moment is to look at the example application(s) and corresponding tests. The example apps are currently used to test Flask-Security as well so they are solid examples of most, if not all, features. Configuration options are illustrated in the tests as well. To run the example run do the following:
$ mkvirtualenv flask-security
$ git clone git://github.com/mattupstate/flask-security.git
$ cd flask-security
$ pip install Flask Flask-Login Flask-Principal Flask-SQLALchemy passlib
$ pip install https://github.com/sbook/flask-mongoengine/tarball/master
$ python example/app.py
## Code Examples
If you don't want to checkout the example quite yet, here are some hypothetical examples to give you a sense of how Flask-Security works:
### Setup SQLAlchemy
from flask import Flask
from flask.ext.security import Security
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyDatastore
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'something'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLALchemy(app)
Security(app, SQLAlchemyDatastore(db))
### Require a logged in user:
from flask import render_template
from flask.ext.security import login_required
… application setup …
@app.route('/profile')
@login_required
def profile():
return render_template('profile.html')
### Require an admin:
from flask import render_template
from flask.ext.security import roles_required
… application setup …
@app.route('/admin')
@roles_required('admin')
def admin():
return render_template('admin/index.html')
### Require any of the specified roles:
from flask import render_template
from flask.ext.security import roles_accepted
… application setup …
@app.route('/admin')
@roles_accepted('admin', 'editor', 'author')
def admin():
return render_template('admin/index.html')
### Showing a link in a template only for an admin:
{% if current_user.has_role('admin') %}
<a href="{{ url_for('admin.index') }}">Admin Panel</a>
{$ endif %}
## Flask-Script Commands
Flask-Security comes packed with a few Flask-Script commands. They are:
* `flask.ext.security.script.CreateUserCommand`
* `flask.ext.security.script.AddRoleCommand`
* `flask.ext.security.script.RemoveRoleCommand`
* `flask.ext.security.script.DeactivateUserCommand`
* `flask.ext.security.script.ActivateUserCommand`
Register these on your script manager for pure convenience.
## Contributing
Feel free to fork and contribute. If you decided to do so, just be sure to include relevant tests that you feel are necessary. To run the tests, please provide instructions for any requirements. For instance, if you write a new datastore implementation, please provide instructions on how best to setup a connection when testing.
If you plan on running all the provided tests you'll need a local installation of MongoDB running on the standard port 27017 without username/password protection.
+4 -3
View File
@@ -16,8 +16,9 @@ import sys, os
# If extensions (or modules to document with autodoc) are in another directory, # If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the # add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here. # 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')) sys.path.append(os.path.abspath('_themes'))
sys.path.append(os.path.abspath('..')) #from setup import __version__
# -- General configuration ----------------------------------------------------- # -- General configuration -----------------------------------------------------
@@ -49,9 +50,9 @@ copyright = u'2012, Matt Wright'
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
version = '1.1' version = '1.2.3'
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = '1.1.0' release = version
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
+43 -7
View File
@@ -28,6 +28,8 @@ Contents
* :ref:`overview` * :ref:`overview`
* :ref:`installation` * :ref:`installation`
* :ref:`getting-started` * :ref:`getting-started`
* :ref:`additional-user-fields`
* :ref:`flask-script-commands`
* :ref:`api` * :ref:`api`
* :doc:`Changelog </changelog>` * :doc:`Changelog </changelog>`
@@ -58,7 +60,7 @@ Installation
First, install Flask-Security:: First, install Flask-Security::
$ mkvirtualenv app-name $ mkvirtualenv app-name
$ pip install https://github.com/mattupstate/flask-security/tarball/master $ pip install Flask-Security
Then install your datastore requirement. Then install your datastore requirement.
@@ -81,9 +83,9 @@ First thing you'll want to do is setup your application and datastore::
from flask import Flask, render_template from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import User, Security, LoginForm, from flask.ext.security import (User, Security, LoginForm, login_required,
login_required, roles_accepted, user_datastore roles_accepted, user_datastore)
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDataStore from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
app = Flask(__name__) app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret' app.config['SECRET_KEY'] = 'secret'
@@ -92,14 +94,14 @@ First thing you'll want to do is setup your application and datastore::
db = SQLAlchemy(app) db = SQLAlchemy(app)
Security(app, SQLAlchemyUserDatastore(db)) Security(app, SQLAlchemyUserDatastore(db))
You'll probably want to at least one user to the database to test this out, so You'll probably want to at least one user to the database to test this out.
you can add something such as the following to quickly add an initial user:: There are many ways to do this, but this is a quick and dirty way to do it::
@app.before_first_request @app.before_first_request
def before_first_request(): def before_first_request():
user_datastore.create_role(name='admin') user_datastore.create_role(name='admin')
user_datastore.create_user(username='matt', email='matt@something.com', 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:: Next you'll want to setup your login screen. Setup your view::
@@ -152,6 +154,38 @@ specific role::
{$ endif %} {$ endif %}
.. _additional-user-fields:
Additional User Fields
----------------------
If you'd like to add additional fields to the user model you can use a mixin
class that specifies your additional fields. The following is an example of
how you might do this::
db = SQLAlchemy(app)
class UserAccountMixin():
first_name = db.Column(db.String(120))
last_name = db.Column(db.String(120))
Security(app, SQLAlchemyUserDatastore(db, UserAccountMixin))
.. _flask-script-commands:
Flask-Script Commands
---------------------
Flask-Security comes packed with a few Flask-Script commands. They are:
* :class:`flask.ext.security.script.CreateUserCommand`
* :class:`flask.ext.security.script.CreateRoleCommand`
* :class:`flask.ext.security.script.AddRoleCommand`
* :class:`flask.ext.security.script.RemoveRoleCommand`
* :class:`flask.ext.security.script.DeactivateUserCommand`
* :class:`flask.ext.security.script.ActivateUserCommand`
Register these on your script manager for pure convenience.
.. _configuration: .. _configuration:
Configuration Values Configuration Values
@@ -220,9 +254,11 @@ Datastores
.. autoclass:: flask_security.datastore.sqlalchemy.SQLAlchemyUserDatastore .. autoclass:: flask_security.datastore.sqlalchemy.SQLAlchemyUserDatastore
:members: :members:
:inherited-members:
.. autoclass:: flask_security.datastore.mongoengine.MongoEngineUserDatastore .. autoclass:: flask_security.datastore.mongoengine.MongoEngineUserDatastore
:members: :members:
:inherited-members:
Models Models
+12 -2
View File
@@ -84,7 +84,12 @@ def create_sqlalchemy_app(auth_config=None):
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/flask_security_example.sqlite' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/flask_security_example.sqlite'
db = SQLAlchemy(app) db = SQLAlchemy(app)
Security(app, SQLAlchemyUserDatastore(db))
class UserAccountMixin():
first_name = db.Column(db.String(120))
last_name = db.Column(db.String(120))
Security(app, SQLAlchemyUserDatastore(db, UserAccountMixin))
@app.before_first_request @app.before_first_request
def before_first_request(): def before_first_request():
@@ -101,7 +106,12 @@ def create_mongoengine_app(auth_config=None):
app.config['MONGODB_PORT'] = 27017 app.config['MONGODB_PORT'] = 27017
db = MongoEngine(app) db = MongoEngine(app)
Security(app, MongoEngineUserDatastore(db))
class UserAccountMixin():
first_name = db.StringField(max_length=120)
last_name = db.StringField(max_length=120)
Security(app, MongoEngineUserDatastore(db, UserAccountMixin))
@app.before_first_request @app.before_first_request
def before_first_request(): def before_first_request():
+1
View File
@@ -5,6 +5,7 @@
{{ form.username.label }} {{ form.username }}<br/> {{ form.username.label }} {{ form.username }}<br/>
{{ form.password.label }} {{ form.password }}<br/> {{ form.password.label }} {{ form.password }}<br/>
{{ form.remember.label }} {{ form.remember }}<br/> {{ form.remember.label }} {{ form.remember }}<br/>
{{ form.next }}
{{ form.submit }} {{ form.submit }}
</form> </form>
<p>{{ content }}</p> <p>{{ content }}</p>
+42 -26
View File
@@ -10,32 +10,30 @@
:license: MIT, see LICENSE for more details. :license: MIT, see LICENSE for more details.
""" """
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 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 passlib.context import CryptContext
from werkzeug.utils import import_string
from werkzeug.local import LocalProxy from werkzeug.local import LocalProxy
class User(object): class User(object):
"""User model""" """User model"""
class Role(object): class Role(object):
"""Role model""" """Role model"""
@@ -78,34 +76,41 @@ class BadCredentialsError(Exception):
provided credentials. provided credentials.
""" """
class AuthenticationError(Exception): class AuthenticationError(Exception):
"""Raised when an authentication attempt fails due to invalid configuration """Raised when an authentication attempt fails due to invalid configuration
or an unknown reason. or an unknown reason.
""" """
class UserNotFoundError(Exception): 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. their identifier, often username or email, and the user is not found.
""" """
class RoleNotFoundError(Exception): class RoleNotFoundError(Exception):
"""Raised by a user datastore when there is an attempt to find a role and """Raised by a user datastore when there is an attempt to find a role and
the role cannot be found. the role cannot be found.
""" """
class UserIdNotFoundError(Exception): 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. ID and the user is not found.
""" """
class UserDatastoreError(Exception): class UserDatastoreError(Exception):
"""Raised when a user datastore experiences an unexpected error """Raised when a user datastore experiences an unexpected error
""" """
class UserCreationError(Exception): class UserCreationError(Exception):
"""Raised when an error occurs when creating a user """Raised when an error occurs when creating a user
""" """
class RoleCreationError(Exception): class RoleCreationError(Exception):
"""Raised when an error occurs when creating a role """Raised when an error occurs when creating a role
""" """
@@ -127,6 +132,7 @@ pwd_context = LocalProxy(lambda: current_app.pwd_context)
user_datastore = LocalProxy(lambda: getattr(current_app, user_datastore = LocalProxy(lambda: getattr(current_app,
current_app.config[USER_DATASTORE_KEY])) current_app.config[USER_DATASTORE_KEY]))
def roles_required(*args): def roles_required(*args):
"""View decorator which specifies that a user must have all the specified """View decorator which specifies that a user must have all the specified
roles. Example:: roles. Example::
@@ -143,11 +149,13 @@ def roles_required(*args):
""" """
roles = args roles = args
perm = Permission(*[RoleNeed(role) for role in roles]) perm = Permission(*[RoleNeed(role) for role in roles])
def wrapper(fn): def wrapper(fn):
@wraps(fn) @wraps(fn)
def decorated_view(*args, **kwargs): def decorated_view(*args, **kwargs):
if not current_user.is_authenticated(): 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(): if perm.can():
return fn(*args, **kwargs) return fn(*args, **kwargs)
@@ -177,11 +185,13 @@ def roles_accepted(*args):
""" """
roles = args roles = args
perms = [Permission(RoleNeed(role)) for role in roles] perms = [Permission(RoleNeed(role)) for role in roles]
def wrapper(fn): def wrapper(fn):
@wraps(fn) @wraps(fn)
def decorated_view(*args, **kwargs): def decorated_view(*args, **kwargs):
if not current_user.is_authenticated(): 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: for perm in perms:
if perm.can(): if perm.can():
@@ -199,10 +209,10 @@ def roles_accepted(*args):
class RoleMixin(object): class RoleMixin(object):
"""Mixin for `Role` model definitions""" """Mixin for `Role` model definitions"""
def __eq__(self, other): def __eq__(self, other):
return self.name == other.name return self.name == other or self.name == getattr(other, 'name', None)
def __ne__(self, other): def __ne__(self, other):
return self.name != other.name return self.name != other and self.name != getattr(other, 'name', None)
def __str__(self): def __str__(self):
return '<Role name=%s, description=%s>' % (self.name, self.description) return '<Role name=%s, description=%s>' % (self.name, self.description)
@@ -219,8 +229,6 @@ class UserMixin(BaseUserMixin):
"""Returns `True` if the user identifies with the specified role. """Returns `True` if the user identifies with the specified role.
:param role: A role name or `Role` instance""" :param role: A role name or `Role` instance"""
if not isinstance(role, Role):
role = Role(name=role)
return role in self.roles return role in self.roles
def __str__(self): def __str__(self):
@@ -254,8 +262,10 @@ class Security(object):
:param app: The application. :param app: The application.
:param datastore: An instance of a user datastore. :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__) blueprint = Blueprint('auth', __name__)
configured = {} configured = {}
@@ -305,6 +315,7 @@ class Security(object):
return None return None
auth_url = config[AUTH_URL_KEY] auth_url = config[AUTH_URL_KEY]
@blueprint.route(auth_url, methods=['POST'], endpoint='authenticate') @blueprint.route(auth_url, methods=['POST'], endpoint='authenticate')
def authenticate(): def authenticate():
try: try:
@@ -421,6 +432,7 @@ class AuthenticationProvider(object):
logger.error(msg) logger.error(msg)
raise AuthenticationError(msg) raise AuthenticationError(msg)
def do_flash(message, category): def do_flash(message, category):
if current_app.config[FLASH_MESSAGES_KEY]: if current_app.config[FLASH_MESSAGES_KEY]:
flash(message, category) flash(message, category)
@@ -435,6 +447,7 @@ def get_class_by_name(clazz):
m = getattr(m, comp) m = getattr(m, comp)
return m return m
def get_class_from_config(key, config): def get_class_from_config(key, config):
"""Get a reference to a class by its configuration key name.""" """Get a reference to a class by its configuration key name."""
try: try:
@@ -444,6 +457,7 @@ def get_class_from_config(key, config):
"Could not get class '%s' for Auth setting '%s' >> %s" % "Could not get class '%s' for Auth setting '%s' >> %s" %
(config[key], key, e)) (config[key], key, e))
def get_url(endpoint_or_url): 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.""" provided value."""
@@ -452,12 +466,14 @@ def get_url(endpoint_or_url):
except: except:
return endpoint_or_url return endpoint_or_url
def get_post_login_redirect(): def get_post_login_redirect():
"""Returns the URL to redirect to after a user logs in successfully""" """Returns the URL to redirect to after a user logs in successfully"""
return (get_url(request.args.get('next')) or return (get_url(request.args.get('next')) or
get_url(request.form.get('next')) or get_url(request.form.get('next')) or
find_redirect(POST_LOGIN_KEY)) find_redirect(POST_LOGIN_KEY))
def find_redirect(key): def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully""" """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
+13 -6
View File
@@ -13,16 +13,20 @@ from datetime import datetime
from flask.ext import security from flask.ext import security
from flask.ext.security import UserCreationError, RoleCreationError, pwd_context from flask.ext.security import UserCreationError, RoleCreationError, pwd_context
class UserDatastore(object): class UserDatastore(object):
"""Abstracted user datastore. Always extend this class and implement the """Abstracted user datastore. Always extend this class and implement the
:attr:`get_models`, :attr:`_save_model`, :attr:`_do_with_id`, :attr:`get_models`, :attr:`_save_model`, :attr:`_do_with_id`,
:attr:`_do_find_user`, and :attr:`_do_find_role` methods. :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""" extension such as Flask-SQLAlchemy or Flask-MongoEngine
:param user_account_mixin: An optional mixin class that specifies additional
def __init__(self, db): fields to be added to the user model
"""
def __init__(self, db, user_account_mixin=None):
self.db = db self.db = db
self.user_account_mixin = user_account_mixin or object
def get_models(self): def get_models(self):
"""Returns configured `User` and `Role` models for the datastore """Returns configured `User` and `Role` models for the datastore
@@ -124,7 +128,8 @@ class UserDatastore(object):
:param id: User ID""" :param id: User ID"""
user = self._do_with_id(id) user = self._do_with_id(id)
if user: return user if user:
return user
raise security.UserIdNotFoundError() raise security.UserIdNotFoundError()
def find_user(self, user): def find_user(self, user):
@@ -133,7 +138,8 @@ class UserDatastore(object):
:param user: User identifier, usually a username or email address :param user: User identifier, usually a username or email address
""" """
user = self._do_find_user(user) user = self._do_find_user(user)
if user: return user if user:
return user
raise security.UserNotFoundError() raise security.UserNotFoundError()
def find_role(self, role): def find_role(self, role):
@@ -142,7 +148,8 @@ class UserDatastore(object):
:param role: Role name :param role: Role name
""" """
role = self._do_find_role(role) role = self._do_find_role(role)
if role: return role if role:
return role
raise security.RoleNotFoundError() raise security.RoleNotFoundError()
def create_role(self, **kwargs): def create_role(self, **kwargs):
+6 -4
View File
@@ -13,6 +13,7 @@ from flask.ext import security
from flask.ext.security import UserMixin, RoleMixin from flask.ext.security import UserMixin, RoleMixin
from flask.ext.security.datastore import UserDatastore from flask.ext.security.datastore import UserDatastore
class MongoEngineUserDatastore(UserDatastore): class MongoEngineUserDatastore(UserDatastore):
"""A MongoEngine datastore implementation for Flask-Security. """A MongoEngine datastore implementation for Flask-Security.
Example usage:: Example usage::
@@ -41,7 +42,7 @@ class MongoEngineUserDatastore(UserDatastore):
name = db.StringField(required=True, unique=True, max_length=80) name = db.StringField(required=True, unique=True, max_length=80)
description = db.StringField(max_length=255) description = db.StringField(max_length=255)
class User(db.Document, UserMixin): class User(db.Document, UserMixin, self.user_account_mixin):
"""MongoEngine User model""" """MongoEngine User model"""
username = db.StringField(unique=True, max_length=255) username = db.StringField(unique=True, max_length=255)
@@ -59,8 +60,10 @@ class MongoEngineUserDatastore(UserDatastore):
return model return model
def _do_with_id(self, id): def _do_with_id(self, id):
try: return security.User.objects.get(id=id) try:
except: return None return security.User.objects.get(id=id)
except:
return None
def _do_find_user(self, user): def _do_find_user(self, user):
return security.User.objects(username=user).first() or \ return security.User.objects(username=user).first() or \
@@ -68,4 +71,3 @@ class MongoEngineUserDatastore(UserDatastore):
def _do_find_role(self, role): def _do_find_role(self, role):
return security.Role.objects(name=role).first() return security.Role.objects(name=role).first()
+2 -2
View File
@@ -13,6 +13,7 @@ from flask.ext import security
from flask.ext.security import UserMixin, RoleMixin from flask.ext.security import UserMixin, RoleMixin
from flask.ext.security.datastore import UserDatastore from flask.ext.security.datastore import UserDatastore
class SQLAlchemyUserDatastore(UserDatastore): class SQLAlchemyUserDatastore(UserDatastore):
"""A SQLAlchemy datastore implementation for Flask-Security. """A SQLAlchemy datastore implementation for Flask-Security.
Example usage:: Example usage::
@@ -48,7 +49,7 @@ class SQLAlchemyUserDatastore(UserDatastore):
self.name = name self.name = name
self.description = description self.description = description
class User(db.Model, UserMixin): class User(db.Model, UserMixin, self.user_account_mixin):
"""SQLAlchemy User model""" """SQLAlchemy User model"""
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
@@ -89,4 +90,3 @@ class SQLAlchemyUserDatastore(UserDatastore):
def _do_find_role(self, role): def _do_find_role(self, role):
return security.Role.query.filter_by(name=role).first() return security.Role.query.filter_by(name=role).first()
+19 -2
View File
@@ -11,9 +11,11 @@
import json import json
import re import re
from flask.ext.script import Command, Option 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): def pprint(obj):
print json.dumps(obj, sort_keys=True, indent=4) print json.dumps(obj, sort_keys=True, indent=4)
@@ -46,6 +48,19 @@ class CreateUserCommand(Command):
pprint(kwargs) pprint(kwargs)
class CreateRoleCommand(Command):
"""Create a role"""
option_list = (
Option('-n', '--name', dest='name', default=None),
Option('-d', '--desc', dest='description', default=None),
)
def run(self, **kwargs):
user_datastore.create_role(**kwargs)
print 'Role "%(name)s" created successfully.' % kwargs
class _RoleCommand(Command): class _RoleCommand(Command):
option_list = ( option_list = (
Option('-u', '--user', dest='user_identifier'), Option('-u', '--user', dest='user_identifier'),
@@ -74,6 +89,7 @@ class _ToggleActiveCommand(Command):
Option('-u', '--user', dest='user_identifier'), Option('-u', '--user', dest='user_identifier'),
) )
class DeactivateUserCommand(_ToggleActiveCommand): class DeactivateUserCommand(_ToggleActiveCommand):
"""Deactive a user""" """Deactive a user"""
@@ -81,6 +97,7 @@ class DeactivateUserCommand(_ToggleActiveCommand):
user_datastore.deactivate_user(user_identifier) user_datastore.deactivate_user(user_identifier)
print "User '%s' has been deactivated" % user_identifier print "User '%s' has been deactivated" % user_identifier
class ActivateUserCommand(_ToggleActiveCommand): class ActivateUserCommand(_ToggleActiveCommand):
"""Deactive a user""" """Deactive a user"""
+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
+2 -1
View File
@@ -12,11 +12,12 @@ Links
<https://github.com/mattupstate/flask-security/raw/develop#egg=Flask-Security-dev>`_ <https://github.com/mattupstate/flask-security/raw/develop#egg=Flask-Security-dev>`_
""" """
from setuptools import setup from setuptools import setup
setup( setup(
name='Flask-Security', name='Flask-Security',
version='1.2.0', version='1.2.3',
url='https://github.com/mattupstate/flask-security', url='https://github.com/mattupstate/flask-security',
license='MIT', license='MIT',
author='Matthew Wright', author='Matthew Wright',
+6 -1
View File
@@ -1,6 +1,7 @@
import unittest import unittest
from example import app from example import app
class SecurityTest(unittest.TestCase): class SecurityTest(unittest.TestCase):
AUTH_CONFIG = None AUTH_CONFIG = None
@@ -26,7 +27,6 @@ class SecurityTest(unittest.TestCase):
follow_redirects=follow_redirects, follow_redirects=follow_redirects,
content_type=content_type or 'text/html') content_type=content_type or 'text/html')
def authenticate(self, username, password, endpoint=None): def authenticate(self, username, password, endpoint=None):
data = dict(username=username, password=password) data = dict(username=username, password=password)
return self._post(endpoint or '/auth', data=data, return self._post(endpoint or '/auth', data=data,
@@ -35,6 +35,7 @@ class SecurityTest(unittest.TestCase):
def logout(self, endpoint=None): def logout(self, endpoint=None):
return self._get(endpoint or '/logout', follow_redirects=True) return self._get(endpoint or '/logout', follow_redirects=True)
class DefaultSecurityTests(SecurityTest): class DefaultSecurityTests(SecurityTest):
def test_login_view(self): def test_login_view(self):
@@ -100,6 +101,10 @@ class DefaultSecurityTests(SecurityTest):
r = self._get("/admin_or_editor", follow_redirects=True) r = self._get("/admin_or_editor", follow_redirects=True)
self.assertIn('Home Page', r.data) 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):
+2
View File
@@ -2,6 +2,7 @@ import unittest
import flask_security import flask_security
from flask_security import RoleMixin, UserMixin, AnonymousUser from flask_security import RoleMixin, UserMixin, AnonymousUser
class Role(RoleMixin): class Role(RoleMixin):
def __init__(self, name, description=None): def __init__(self, name, description=None):
self.name = name self.name = name
@@ -24,6 +25,7 @@ editor = Role('editor')
user = User('matt', 'matt@lp.com', [admin, editor]) user = User('matt', 'matt@lp.com', [admin, editor])
class SecurityEntityTests(unittest.TestCase): class SecurityEntityTests(unittest.TestCase):
def test_role_mixin_equal(self): def test_role_mixin_equal(self):