mirror of
https://github.com/wassname/flask-security.git
synced 2026-08-08 11:19:18 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ddbcdca06 | ||
|
|
edf41096d7 | ||
|
|
3ce907db79 | ||
|
|
5c9bc541f9 | ||
|
|
f7147648ba | ||
|
|
30b72cb7f4 | ||
|
|
ab08abcaf9 | ||
|
|
0227d987fe | ||
|
|
5df01af720 | ||
|
|
0acf4bca0d | ||
|
|
2e37af8c01 | ||
|
|
245914cc9a | ||
|
|
201ee5b708 | ||
|
|
744ded7f1b | ||
|
|
5a7f4dff47 | ||
|
|
dd6ba0995d | ||
|
|
5697f7c953 | ||
|
|
144b22a3b9 | ||
|
|
3c57e169d1 |
@@ -1,6 +1,8 @@
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
*.pyc
|
*.pyc
|
||||||
*.egg
|
*.egg
|
||||||
|
*.egg-info
|
||||||
.project
|
.project
|
||||||
.pydevproject
|
.pydevproject
|
||||||
.settings
|
.settings
|
||||||
|
dist
|
||||||
|
|||||||
@@ -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
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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/
|
||||||
@@ -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.
|
|
||||||
+5
-4
@@ -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.
|
||||||
@@ -98,7 +99,7 @@ html_theme = 'flask_small'
|
|||||||
# further. For a list of options available for each theme, see the
|
# further. For a list of options available for each theme, see the
|
||||||
# documentation.
|
# documentation.
|
||||||
html_theme_options = {
|
html_theme_options = {
|
||||||
'github_fork': 'mattupstate/flask-security',
|
'github_fork': 'mattupstate/flask-security',
|
||||||
'index_logo': False
|
'index_logo': False
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+43
-7
@@ -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::
|
||||||
|
|
||||||
@@ -150,6 +152,38 @@ specific role::
|
|||||||
{% if current_user.has_role('admin') %}
|
{% if current_user.has_role('admin') %}
|
||||||
<a href="{{ url_for('admin.index') }}">Admin Panel</a>
|
<a href="{{ url_for('admin.index') }}">Admin Panel</a>
|
||||||
{$ 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:
|
||||||
@@ -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
@@ -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():
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
+148
-132
@@ -3,52 +3,50 @@
|
|||||||
flask.ext.security
|
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.
|
security via Flask-Login, Flask-Principal, Flask-WTF, and passlib.
|
||||||
|
|
||||||
:copyright: (c) 2012 by Matt Wright.
|
:copyright: (c) 2012 by Matt Wright.
|
||||||
: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"""
|
||||||
|
|
||||||
URL_PREFIX_KEY = 'SECURITY_URL_PREFIX'
|
URL_PREFIX_KEY = 'SECURITY_URL_PREFIX'
|
||||||
AUTH_PROVIDER_KEY = 'SECURITY_AUTH_PROVIDER'
|
AUTH_PROVIDER_KEY = 'SECURITY_AUTH_PROVIDER'
|
||||||
PASSWORD_HASH_KEY = 'SECURITY_PASSWORD_HASH'
|
PASSWORD_HASH_KEY = 'SECURITY_PASSWORD_HASH'
|
||||||
USER_DATASTORE_KEY = 'SECURITY_USER_DATASTORE'
|
USER_DATASTORE_KEY = 'SECURITY_USER_DATASTORE'
|
||||||
LOGIN_FORM_KEY = 'SECURITY_LOGIN_FORM'
|
LOGIN_FORM_KEY = 'SECURITY_LOGIN_FORM'
|
||||||
AUTH_URL_KEY = 'SECURITY_AUTH_URL'
|
AUTH_URL_KEY = 'SECURITY_AUTH_URL'
|
||||||
LOGOUT_URL_KEY = 'SECURITY_LOGOUT_URL'
|
LOGOUT_URL_KEY = 'SECURITY_LOGOUT_URL'
|
||||||
LOGIN_VIEW_KEY = 'SECURITY_LOGIN_VIEW'
|
LOGIN_VIEW_KEY = 'SECURITY_LOGIN_VIEW'
|
||||||
POST_LOGIN_KEY = 'SECURITY_POST_LOGIN'
|
POST_LOGIN_KEY = 'SECURITY_POST_LOGIN'
|
||||||
POST_LOGOUT_KEY = 'SECURITY_POST_LOGOUT'
|
POST_LOGOUT_KEY = 'SECURITY_POST_LOGOUT'
|
||||||
FLASH_MESSAGES_KEY = 'SECURITY_FLASH_MESSAGES'
|
FLASH_MESSAGES_KEY = 'SECURITY_FLASH_MESSAGES'
|
||||||
|
|
||||||
DEBUG_LOGIN = 'User %s logged in. Redirecting to: %s'
|
DEBUG_LOGIN = 'User %s logged in. Redirecting to: %s'
|
||||||
@@ -77,40 +75,47 @@ class BadCredentialsError(Exception):
|
|||||||
"""Raised when an authentication attempt fails due to an error with the
|
"""Raised when an authentication attempt fails due to an error with the
|
||||||
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
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
#: App logger for convenience
|
#: App logger for convenience
|
||||||
logger = LocalProxy(lambda: current_app.logger)
|
logger = LocalProxy(lambda: current_app.logger)
|
||||||
|
|
||||||
@@ -124,37 +129,40 @@ login_manager = LocalProxy(lambda: current_app.login_manager)
|
|||||||
pwd_context = LocalProxy(lambda: current_app.pwd_context)
|
pwd_context = LocalProxy(lambda: current_app.pwd_context)
|
||||||
|
|
||||||
#: User datastore
|
#: User datastore
|
||||||
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::
|
||||||
|
|
||||||
@app.route('/dashboard')
|
@app.route('/dashboard')
|
||||||
@roles_required('admin', 'editor')
|
@roles_required('admin', 'editor')
|
||||||
def dashboard():
|
def dashboard():
|
||||||
return 'Dashboard'
|
return 'Dashboard'
|
||||||
|
|
||||||
The current user must have both the `admin` role and `editor` role in order
|
The current user must have both the `admin` role and `editor` role in order
|
||||||
to view the page.
|
to view the page.
|
||||||
|
|
||||||
:param args: The required roles.
|
:param args: The required roles.
|
||||||
"""
|
"""
|
||||||
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)
|
||||||
|
|
||||||
logger.debug('Identity does not provide all of the '
|
logger.debug('Identity does not provide all of the '
|
||||||
'following roles: %s' % [r for r in roles])
|
'following roles: %s' % [r for r in roles])
|
||||||
|
|
||||||
do_flash(FLASH_PERMISSIONS, 'error')
|
do_flash(FLASH_PERMISSIONS, 'error')
|
||||||
return redirect(request.referrer or '/')
|
return redirect(request.referrer or '/')
|
||||||
return decorated_view
|
return decorated_view
|
||||||
@@ -162,34 +170,36 @@ def roles_required(*args):
|
|||||||
|
|
||||||
|
|
||||||
def roles_accepted(*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::
|
specified roles. Example::
|
||||||
|
|
||||||
@app.route('/create_post')
|
@app.route('/create_post')
|
||||||
@roles_accepted('editor', 'author')
|
@roles_accepted('editor', 'author')
|
||||||
def create_post():
|
def create_post():
|
||||||
return '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.
|
order to view the page.
|
||||||
|
|
||||||
:param args: The possible roles.
|
:param args: The possible roles.
|
||||||
"""
|
"""
|
||||||
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():
|
||||||
return fn(*args, **kwargs)
|
return fn(*args, **kwargs)
|
||||||
|
|
||||||
logger.debug('Identity does not provide at least one of '
|
logger.debug('Identity does not provide at least one of '
|
||||||
'the following roles: %s' % [r for r in roles])
|
'the following roles: %s' % [r for r in roles])
|
||||||
|
|
||||||
do_flash(FLASH_PERMISSIONS, 'error')
|
do_flash(FLASH_PERMISSIONS, 'error')
|
||||||
return redirect(request.referrer or '/')
|
return redirect(request.referrer or '/')
|
||||||
return decorated_view
|
return decorated_view
|
||||||
@@ -199,30 +209,28 @@ 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)
|
||||||
|
|
||||||
|
|
||||||
class UserMixin(BaseUserMixin):
|
class UserMixin(BaseUserMixin):
|
||||||
"""Mixin for `User` model definitions"""
|
"""Mixin for `User` model definitions"""
|
||||||
|
|
||||||
def is_active(self):
|
def is_active(self):
|
||||||
"""Returns `True` if the user is active."""
|
"""Returns `True` if the user is active."""
|
||||||
return self.active
|
return self.active
|
||||||
|
|
||||||
def has_role(self, role):
|
def has_role(self, role):
|
||||||
"""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):
|
||||||
ctx = (str(self.id), self.username, self.email)
|
ctx = (str(self.id), self.username, self.email)
|
||||||
return '<User id=%s, username=%s, email=%s>' % ctx
|
return '<User id=%s, username=%s, email=%s>' % ctx
|
||||||
@@ -231,8 +239,8 @@ class UserMixin(BaseUserMixin):
|
|||||||
class AnonymousUser(AnonymousUserBase):
|
class AnonymousUser(AnonymousUserBase):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super(AnonymousUser, self).__init__()
|
super(AnonymousUser, self).__init__()
|
||||||
self.roles = [] # TODO: Make this immutable?
|
self.roles = [] # TODO: Make this immutable?
|
||||||
|
|
||||||
def has_role(self, *args):
|
def has_role(self, *args):
|
||||||
"""Returns `False`"""
|
"""Returns `False`"""
|
||||||
return False
|
return False
|
||||||
@@ -240,77 +248,80 @@ class AnonymousUser(AnonymousUserBase):
|
|||||||
|
|
||||||
class Security(object):
|
class Security(object):
|
||||||
"""The :class:`Security` class initializes the Flask-Security extension.
|
"""The :class:`Security` class initializes the Flask-Security extension.
|
||||||
|
|
||||||
:param app: The application.
|
:param app: The application.
|
||||||
:param datastore: An instance of a user datastore.
|
:param datastore: An instance of a user datastore.
|
||||||
"""
|
"""
|
||||||
def __init__(self, app=None, datastore=None):
|
def __init__(self, app=None, datastore=None):
|
||||||
self.init_app(app, datastore)
|
self.init_app(app, datastore)
|
||||||
|
|
||||||
def init_app(self, 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.
|
application and datastore implentation.
|
||||||
|
|
||||||
: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 = {}
|
||||||
|
|
||||||
for key, value in default_config.items():
|
for key, value in default_config.items():
|
||||||
configured[key] = app.config.get(key, value)
|
configured[key] = app.config.get(key, value)
|
||||||
|
|
||||||
app.config.update(configured)
|
app.config.update(configured)
|
||||||
config = app.config
|
config = app.config
|
||||||
|
|
||||||
# setup the login manager extension
|
# setup the login manager extension
|
||||||
login_manager = LoginManager()
|
login_manager = LoginManager()
|
||||||
login_manager.anonymous_user = AnonymousUser
|
login_manager.anonymous_user = AnonymousUser
|
||||||
login_manager.login_view = config[LOGIN_VIEW_KEY]
|
login_manager.login_view = config[LOGIN_VIEW_KEY]
|
||||||
login_manager.setup_app(app)
|
login_manager.setup_app(app)
|
||||||
app.login_manager = login_manager
|
app.login_manager = login_manager
|
||||||
|
|
||||||
Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
|
Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
|
||||||
Form = get_class_from_config(LOGIN_FORM_KEY, config)
|
Form = get_class_from_config(LOGIN_FORM_KEY, config)
|
||||||
pw_hash = config[PASSWORD_HASH_KEY]
|
pw_hash = config[PASSWORD_HASH_KEY]
|
||||||
|
|
||||||
app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash)
|
app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash)
|
||||||
app.auth_provider = Provider(Form)
|
app.auth_provider = Provider(Form)
|
||||||
app.principal = Principal(app)
|
app.principal = Principal(app)
|
||||||
|
|
||||||
from flask.ext import security as s
|
from flask.ext import security as s
|
||||||
s.User, s.Role = datastore.get_models()
|
s.User, s.Role = datastore.get_models()
|
||||||
|
|
||||||
setattr(app, config[USER_DATASTORE_KEY], datastore)
|
setattr(app, config[USER_DATASTORE_KEY], datastore)
|
||||||
|
|
||||||
@identity_loaded.connect_via(app)
|
@identity_loaded.connect_via(app)
|
||||||
def on_identity_loaded(sender, identity):
|
def on_identity_loaded(sender, identity):
|
||||||
if hasattr(current_user, 'id'):
|
if hasattr(current_user, 'id'):
|
||||||
identity.provides.add(UserNeed(current_user.id))
|
identity.provides.add(UserNeed(current_user.id))
|
||||||
|
|
||||||
for role in current_user.roles:
|
for role in current_user.roles:
|
||||||
identity.provides.add(RoleNeed(role.name))
|
identity.provides.add(RoleNeed(role.name))
|
||||||
|
|
||||||
identity.user = current_user
|
identity.user = current_user
|
||||||
|
|
||||||
@login_manager.user_loader
|
@login_manager.user_loader
|
||||||
def load_user(user_id):
|
def load_user(user_id):
|
||||||
try:
|
try:
|
||||||
return datastore.with_id(user_id)
|
return datastore.with_id(user_id)
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
logger.error('Error getting user: %s' % e)
|
logger.error('Error getting user: %s' % e)
|
||||||
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:
|
||||||
form = Form()
|
form = Form()
|
||||||
user = auth_provider.authenticate(form)
|
user = auth_provider.authenticate(form)
|
||||||
|
|
||||||
if login_user(user, remember=form.remember.data):
|
if login_user(user, remember=form.remember.data):
|
||||||
redirect_url = get_post_login_redirect()
|
redirect_url = get_post_login_redirect()
|
||||||
identity_changed.send(app, identity=Identity(user.id))
|
identity_changed.send(app, identity=Identity(user.id))
|
||||||
@@ -318,66 +329,66 @@ class Security(object):
|
|||||||
return redirect(redirect_url)
|
return redirect(redirect_url)
|
||||||
|
|
||||||
raise BadCredentialsError(FLASH_INACTIVE)
|
raise BadCredentialsError(FLASH_INACTIVE)
|
||||||
|
|
||||||
except BadCredentialsError, e:
|
except BadCredentialsError, e:
|
||||||
message = '%s' % e
|
message = '%s' % e
|
||||||
do_flash(message, 'error')
|
do_flash(message, 'error')
|
||||||
redirect_url = request.referrer or login_manager.login_view
|
redirect_url = request.referrer or login_manager.login_view
|
||||||
logger.error(ERROR_LOGIN % (message, redirect_url))
|
logger.error(ERROR_LOGIN % (message, redirect_url))
|
||||||
return redirect(redirect_url)
|
return redirect(redirect_url)
|
||||||
|
|
||||||
@blueprint.route(config[LOGOUT_URL_KEY], endpoint='logout')
|
@blueprint.route(config[LOGOUT_URL_KEY], endpoint='logout')
|
||||||
@login_required
|
@login_required
|
||||||
def logout():
|
def logout():
|
||||||
for value in ('identity.name', 'identity.auth_type'):
|
for value in ('identity.name', 'identity.auth_type'):
|
||||||
session.pop(value, None)
|
session.pop(value, None)
|
||||||
|
|
||||||
identity_changed.send(app, identity=AnonymousIdentity())
|
identity_changed.send(app, identity=AnonymousIdentity())
|
||||||
logout_user()
|
logout_user()
|
||||||
|
|
||||||
redirect_url = find_redirect(POST_LOGOUT_KEY)
|
redirect_url = find_redirect(POST_LOGOUT_KEY)
|
||||||
logger.debug(DEBUG_LOGOUT % redirect_url)
|
logger.debug(DEBUG_LOGOUT % redirect_url)
|
||||||
return redirect(redirect_url)
|
return redirect(redirect_url)
|
||||||
|
|
||||||
app.register_blueprint(blueprint, url_prefix=config[URL_PREFIX_KEY])
|
app.register_blueprint(blueprint, url_prefix=config[URL_PREFIX_KEY])
|
||||||
|
|
||||||
|
|
||||||
class LoginForm(Form):
|
class LoginForm(Form):
|
||||||
"""The default login form"""
|
"""The default login form"""
|
||||||
|
|
||||||
username = TextField("Username or Email",
|
username = TextField("Username or Email",
|
||||||
validators=[Required(message="Username not provided")])
|
validators=[Required(message="Username not provided")])
|
||||||
password = PasswordField("Password",
|
password = PasswordField("Password",
|
||||||
validators=[Required(message="Password not provided")])
|
validators=[Required(message="Password not provided")])
|
||||||
remember = BooleanField("Remember Me")
|
remember = BooleanField("Remember Me")
|
||||||
next = HiddenField()
|
next = HiddenField()
|
||||||
submit = SubmitField("Login")
|
submit = SubmitField("Login")
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super(LoginForm, self).__init__(*args, **kwargs)
|
super(LoginForm, self).__init__(*args, **kwargs)
|
||||||
self.next.data = request.args.get('next', None)
|
self.next.data = request.args.get('next', None)
|
||||||
|
|
||||||
|
|
||||||
class AuthenticationProvider(object):
|
class AuthenticationProvider(object):
|
||||||
"""The default authentication provider implementation.
|
"""The default authentication provider implementation.
|
||||||
|
|
||||||
:param login_form_class: The login form class to use when authenticating a
|
:param login_form_class: The login form class to use when authenticating a
|
||||||
user
|
user
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, login_form_class=None):
|
def __init__(self, login_form_class=None):
|
||||||
self.login_form_class = login_form_class or LoginForm
|
self.login_form_class = login_form_class or LoginForm
|
||||||
|
|
||||||
def login_form(self, formdata=None):
|
def login_form(self, formdata=None):
|
||||||
"""Returns an instance of the login form with the provided form.
|
"""Returns an instance of the login form with the provided form.
|
||||||
|
|
||||||
:param formdata: The incoming form data"""
|
:param formdata: The incoming form data"""
|
||||||
return self.login_form_class(formdata)
|
return self.login_form_class(formdata)
|
||||||
|
|
||||||
def authenticate(self, form):
|
def authenticate(self, form):
|
||||||
"""Processes an authentication request and returns a user instance if
|
"""Processes an authentication request and returns a user instance if
|
||||||
authentication is successful.
|
authentication is successful.
|
||||||
|
|
||||||
:param form: An instance of a populated login form
|
:param form: An instance of a populated login form
|
||||||
"""
|
"""
|
||||||
if not form.validate():
|
if not form.validate():
|
||||||
@@ -385,13 +396,13 @@ class AuthenticationProvider(object):
|
|||||||
raise BadCredentialsError(form.username.errors[0])
|
raise BadCredentialsError(form.username.errors[0])
|
||||||
if form.password.errors:
|
if form.password.errors:
|
||||||
raise BadCredentialsError(form.password.errors[0])
|
raise BadCredentialsError(form.password.errors[0])
|
||||||
|
|
||||||
return self.do_authenticate(form.username.data, form.password.data)
|
return self.do_authenticate(form.username.data, form.password.data)
|
||||||
|
|
||||||
def do_authenticate(self, user_identifier, password):
|
def do_authenticate(self, user_identifier, password):
|
||||||
"""Returns the authenticated user if authentication is successfull. If
|
"""Returns the authenticated user if authentication is successfull. If
|
||||||
authentication fails an appropriate error is raised
|
authentication fails an appropriate error is raised
|
||||||
|
|
||||||
:param user_identifier: The user's identifier, either an email address
|
:param user_identifier: The user's identifier, either an email address
|
||||||
or username
|
or username
|
||||||
:param password: The user's unencrypted password
|
:param password: The user's unencrypted password
|
||||||
@@ -406,21 +417,22 @@ class AuthenticationProvider(object):
|
|||||||
self.auth_error('Invalid user service: %s' % e)
|
self.auth_error('Invalid user service: %s' % e)
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
self.auth_error('Unexpected authentication error: %s' % e)
|
self.auth_error('Unexpected authentication error: %s' % e)
|
||||||
|
|
||||||
# compare passwords
|
# compare passwords
|
||||||
if pwd_context.verify(password, user.password):
|
if pwd_context.verify(password, user.password):
|
||||||
return user
|
return user
|
||||||
|
|
||||||
# bad match
|
# bad match
|
||||||
raise BadCredentialsError("Password does not match")
|
raise BadCredentialsError("Password does not match")
|
||||||
|
|
||||||
def auth_error(self, msg):
|
def auth_error(self, msg):
|
||||||
"""Sends an error log message and raises an authentication error.
|
"""Sends an error log message and raises an authentication error.
|
||||||
|
|
||||||
:param msg: An authentication error message"""
|
:param msg: An authentication error message"""
|
||||||
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)
|
||||||
@@ -430,41 +442,45 @@ def get_class_by_name(clazz):
|
|||||||
"""Get a reference to a class by its string representation."""
|
"""Get a reference to a class by its string representation."""
|
||||||
parts = clazz.split('.')
|
parts = clazz.split('.')
|
||||||
module = ".".join(parts[:-1])
|
module = ".".join(parts[:-1])
|
||||||
m = __import__( module )
|
m = __import__(module)
|
||||||
for comp in parts[1:]:
|
for comp in parts[1:]:
|
||||||
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:
|
||||||
return get_class_by_name(config[key])
|
return get_class_by_name(config[key])
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
raise AttributeError(
|
raise AttributeError(
|
||||||
"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."""
|
||||||
try:
|
try:
|
||||||
return url_for(endpoint_or_url)
|
return url_for(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
|
||||||
get_url(current_app.config[key.upper()] or None) or '/')
|
get_url(current_app.config[key.upper()] or None) or '/')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
del session[key.lower()]
|
del session[key.lower()]
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
flask.ext.security.datastore
|
flask.ext.security.datastore
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
This module contains an abstracted user datastore.
|
This module contains an abstracted user datastore.
|
||||||
|
|
||||||
:copyright: (c) 2012 by Matt Wright.
|
:copyright: (c) 2012 by Matt Wright.
|
||||||
:license: MIT, see LICENSE for more details.
|
:license: MIT, see LICENSE for more details.
|
||||||
@@ -13,51 +13,55 @@ 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
|
||||||
implementation"""
|
implementation"""
|
||||||
raise NotImplementedError(
|
raise NotImplementedError(
|
||||||
"User datastore does not implement get_models method")
|
"User datastore does not implement get_models method")
|
||||||
|
|
||||||
def _save_model(self, model, **kwargs):
|
def _save_model(self, model, **kwargs):
|
||||||
raise NotImplementedError(
|
raise NotImplementedError(
|
||||||
"User datastore does not implement _save_model method")
|
"User datastore does not implement _save_model method")
|
||||||
|
|
||||||
def _do_with_id(self, id):
|
def _do_with_id(self, id):
|
||||||
raise NotImplementedError(
|
raise NotImplementedError(
|
||||||
"User datastore does not implement _do_with_id method")
|
"User datastore does not implement _do_with_id method")
|
||||||
|
|
||||||
def _do_find_user(self):
|
def _do_find_user(self):
|
||||||
raise NotImplementedError(
|
raise NotImplementedError(
|
||||||
"User datastore does not implement _do_find_user method")
|
"User datastore does not implement _do_find_user method")
|
||||||
|
|
||||||
def _do_find_role(self):
|
def _do_find_role(self):
|
||||||
raise NotImplementedError(
|
raise NotImplementedError(
|
||||||
"User datastore does not implement _do_find_role method")
|
"User datastore does not implement _do_find_role method")
|
||||||
|
|
||||||
def _do_add_role(self, user, role):
|
def _do_add_role(self, user, role):
|
||||||
user, role = self._prepare_role_modify_args(user, role)
|
user, role = self._prepare_role_modify_args(user, role)
|
||||||
if role not in user.roles:
|
if role not in user.roles:
|
||||||
user.roles.append(role)
|
user.roles.append(role)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
def _do_remove_role(self, user, role):
|
def _do_remove_role(self, user, role):
|
||||||
user, role = self._prepare_role_modify_args(user, role)
|
user, role = self._prepare_role_modify_args(user, role)
|
||||||
if role in user.roles:
|
if role in user.roles:
|
||||||
user.roles.remove(role)
|
user.roles.remove(role)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
def _do_toggle_active(self, user, active=None):
|
def _do_toggle_active(self, user, active=None):
|
||||||
user = self.find_user(user)
|
user = self.find_user(user)
|
||||||
if active is None:
|
if active is None:
|
||||||
@@ -65,98 +69,101 @@ class UserDatastore(object):
|
|||||||
elif active != user.active:
|
elif active != user.active:
|
||||||
user.active = active
|
user.active = active
|
||||||
return user
|
return user
|
||||||
|
|
||||||
def _do_deactive_user(self, user):
|
def _do_deactive_user(self, user):
|
||||||
return self._do_toggle_active(user, False)
|
return self._do_toggle_active(user, False)
|
||||||
|
|
||||||
def _do_active_user(self, user):
|
def _do_active_user(self, user):
|
||||||
return self._do_toggle_active(user, True)
|
return self._do_toggle_active(user, True)
|
||||||
|
|
||||||
def _prepare_role_modify_args(self, user, role):
|
def _prepare_role_modify_args(self, user, role):
|
||||||
if isinstance(user, security.User):
|
if isinstance(user, security.User):
|
||||||
user = user.username or user.email
|
user = user.username or user.email
|
||||||
|
|
||||||
if isinstance(role, security.Role):
|
if isinstance(role, security.Role):
|
||||||
role = role.name
|
role = role.name
|
||||||
|
|
||||||
return self.find_user(user), self.find_role(role)
|
return self.find_user(user), self.find_role(role)
|
||||||
|
|
||||||
def _prepare_create_role_args(self, kwargs):
|
def _prepare_create_role_args(self, kwargs):
|
||||||
for key in ('name', 'description'):
|
for key in ('name', 'description'):
|
||||||
kwargs[key] = kwargs.get(key, None)
|
kwargs[key] = kwargs.get(key, None)
|
||||||
|
|
||||||
if kwargs['name'] is None:
|
if kwargs['name'] is None:
|
||||||
raise RoleCreationError("Missing name argument")
|
raise RoleCreationError("Missing name argument")
|
||||||
|
|
||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
def _prepare_create_user_args(self, kwargs):
|
def _prepare_create_user_args(self, kwargs):
|
||||||
username = kwargs.get('username', None)
|
username = kwargs.get('username', None)
|
||||||
email = kwargs.get('email', None)
|
email = kwargs.get('email', None)
|
||||||
password = kwargs.get('password', None)
|
password = kwargs.get('password', None)
|
||||||
|
|
||||||
if username is None and email is None:
|
if username is None and email is None:
|
||||||
raise UserCreationError('Missing username and/or email arguments')
|
raise UserCreationError('Missing username and/or email arguments')
|
||||||
|
|
||||||
if password is None:
|
if password is None:
|
||||||
raise UserCreationError('Missing password argument')
|
raise UserCreationError('Missing password argument')
|
||||||
|
|
||||||
roles = kwargs.get('roles', [])
|
roles = kwargs.get('roles', [])
|
||||||
|
|
||||||
for i, role in enumerate(roles):
|
for i, role in enumerate(roles):
|
||||||
rn = role.name if isinstance(role, security.Role) else role
|
rn = role.name if isinstance(role, security.Role) else role
|
||||||
# see if the role exists
|
# see if the role exists
|
||||||
roles[i] = self.find_role(rn)
|
roles[i] = self.find_role(rn)
|
||||||
|
|
||||||
kwargs['roles'] = roles
|
kwargs['roles'] = roles
|
||||||
|
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
kwargs['created_at'], kwargs['modified_at'] = now, now
|
kwargs['created_at'], kwargs['modified_at'] = now, now
|
||||||
|
|
||||||
pw = kwargs['password']
|
pw = kwargs['password']
|
||||||
if not pwd_context.identify(pw):
|
if not pwd_context.identify(pw):
|
||||||
kwargs['password'] = pwd_context.encrypt(pw)
|
kwargs['password'] = pwd_context.encrypt(pw)
|
||||||
|
|
||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
def with_id(self, id):
|
def with_id(self, id):
|
||||||
"""Returns a user with the specified ID.
|
"""Returns a user with the specified ID.
|
||||||
|
|
||||||
: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):
|
||||||
"""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
|
: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):
|
||||||
"""Returns a role based on its name.
|
"""Returns a role based on its name.
|
||||||
|
|
||||||
: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):
|
||||||
"""Creates and returns a new role.
|
"""Creates and returns a new role.
|
||||||
|
|
||||||
:param name: Role name
|
:param name: Role name
|
||||||
:param description: Role description
|
:param description: Role description
|
||||||
"""
|
"""
|
||||||
role = security.Role(**self._prepare_create_role_args(kwargs))
|
role = security.Role(**self._prepare_create_role_args(kwargs))
|
||||||
return self._save_model(role)
|
return self._save_model(role)
|
||||||
|
|
||||||
def create_user(self, **kwargs):
|
def create_user(self, **kwargs):
|
||||||
"""Creates and returns a new user.
|
"""Creates and returns a new user.
|
||||||
|
|
||||||
:param username: Username
|
:param username: Username
|
||||||
:param email: Email address
|
:param email: Email address
|
||||||
:param password: Unencrypted password
|
:param password: Unencrypted password
|
||||||
@@ -164,35 +171,35 @@ class UserDatastore(object):
|
|||||||
"""
|
"""
|
||||||
user = security.User(**self._prepare_create_user_args(kwargs))
|
user = security.User(**self._prepare_create_user_args(kwargs))
|
||||||
return self._save_model(user)
|
return self._save_model(user)
|
||||||
|
|
||||||
def add_role_to_user(self, user, role):
|
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.
|
the modified user.
|
||||||
|
|
||||||
:param user: A User instance or a user identifier
|
:param user: A User instance or a user identifier
|
||||||
:param role: A Role instance or a role name
|
:param role: A Role instance or a role name
|
||||||
"""
|
"""
|
||||||
return self._save_model(self._do_add_role(user, role))
|
return self._save_model(self._do_add_role(user, role))
|
||||||
|
|
||||||
def remove_role_from_user(self, user, role, commit=True):
|
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.
|
modified user.
|
||||||
|
|
||||||
:param user: A User instance or a user identifier
|
:param user: A User instance or a user identifier
|
||||||
:param role: A Role instance or a role name
|
:param role: A Role instance or a role name
|
||||||
"""
|
"""
|
||||||
return self._save_model(self._do_remove_role(user, role))
|
return self._save_model(self._do_remove_role(user, role))
|
||||||
|
|
||||||
def deactivate_user(self, user):
|
def deactivate_user(self, user):
|
||||||
"""Deactivates a user and returns the modified user.
|
"""Deactivates a user and returns the modified user.
|
||||||
|
|
||||||
:param user: A User instance or a user identifier
|
:param user: A User instance or a user identifier
|
||||||
"""
|
"""
|
||||||
return self._save_model(self._do_deactive_user(user))
|
return self._save_model(self._do_deactive_user(user))
|
||||||
|
|
||||||
def activate_user(self, user, commit=True):
|
def activate_user(self, user, commit=True):
|
||||||
"""Activates a user and returns the modified user.
|
"""Activates a user and returns the modified user.
|
||||||
|
|
||||||
:param user: A User instance or a user identifier
|
: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))
|
||||||
|
|||||||
@@ -12,60 +12,62 @@
|
|||||||
from flask.ext import security
|
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::
|
||||||
|
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
from flask.ext.mongoengine import MongoEngine
|
from flask.ext.mongoengine import MongoEngine
|
||||||
from flask.ext.security import Security
|
from flask.ext.security import Security
|
||||||
from flask.ext.security.datastore.mongoengine import MongoEngineUserDatastore
|
from flask.ext.security.datastore.mongoengine import MongoEngineUserDatastore
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config['SECRET_KEY'] = 'secret'
|
app.config['SECRET_KEY'] = 'secret'
|
||||||
app.config['MONGODB_DB'] = 'flask_security_example'
|
app.config['MONGODB_DB'] = 'flask_security_example'
|
||||||
app.config['MONGODB_HOST'] = 'localhost'
|
app.config['MONGODB_HOST'] = 'localhost'
|
||||||
app.config['MONGODB_PORT'] = 27017
|
app.config['MONGODB_PORT'] = 27017
|
||||||
|
|
||||||
db = MongoEngine(app)
|
db = MongoEngine(app)
|
||||||
Security(app, MongoEngineUserDatastore(db))
|
Security(app, MongoEngineUserDatastore(db))
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def get_models(self):
|
def get_models(self):
|
||||||
db = self.db
|
db = self.db
|
||||||
|
|
||||||
class Role(db.Document, RoleMixin):
|
class Role(db.Document, RoleMixin):
|
||||||
"""MongoEngine Role model"""
|
"""MongoEngine Role model"""
|
||||||
|
|
||||||
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)
|
||||||
email = db.StringField(unique=True, max_length=255)
|
email = db.StringField(unique=True, max_length=255)
|
||||||
password = db.StringField(required=True, max_length=120)
|
password = db.StringField(required=True, max_length=120)
|
||||||
active = db.BooleanField(default=True)
|
active = db.BooleanField(default=True)
|
||||||
roles= db.ListField(db.ReferenceField(Role), default=[])
|
roles = db.ListField(db.ReferenceField(Role), default=[])
|
||||||
created_at = db.DateTimeField()
|
created_at = db.DateTimeField()
|
||||||
modified_at = db.DateTimeField()
|
modified_at = db.DateTimeField()
|
||||||
|
|
||||||
return User, Role
|
return User, Role
|
||||||
|
|
||||||
def _save_model(self, model):
|
def _save_model(self, model):
|
||||||
model.save()
|
model.save()
|
||||||
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 \
|
||||||
security.User.objects(email=user).first()
|
security.User.objects(email=user).first()
|
||||||
|
|
||||||
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()
|
||||||
|
|
||||||
@@ -12,45 +12,46 @@
|
|||||||
from flask.ext import security
|
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::
|
||||||
|
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
from flask.ext.security import Security
|
from flask.ext.security import Security
|
||||||
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
|
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
|
||||||
from flask.ext.sqlalchemy import SQLAlchemy
|
from flask.ext.sqlalchemy import SQLAlchemy
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config['SECRET_KEY'] = 'secret'
|
app.config['SECRET_KEY'] = 'secret'
|
||||||
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))
|
Security(app, SQLAlchemyUserDatastore(db))
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def get_models(self):
|
def get_models(self):
|
||||||
db = self.db
|
db = self.db
|
||||||
|
|
||||||
roles_users = db.Table('roles_users',
|
roles_users = db.Table('roles_users',
|
||||||
db.Column('user_id', db.Integer(), db.ForeignKey('role.id')),
|
db.Column('user_id', db.Integer(), db.ForeignKey('role.id')),
|
||||||
db.Column('role_id', db.Integer(), db.ForeignKey('user.id')))
|
db.Column('role_id', db.Integer(), db.ForeignKey('user.id')))
|
||||||
|
|
||||||
class Role(db.Model, RoleMixin):
|
class Role(db.Model, RoleMixin):
|
||||||
"""SQLAlchemy Role model"""
|
"""SQLAlchemy Role model"""
|
||||||
|
|
||||||
id = db.Column(db.Integer(), primary_key=True)
|
id = db.Column(db.Integer(), primary_key=True)
|
||||||
name = db.Column(db.String(80), unique=True)
|
name = db.Column(db.String(80), unique=True)
|
||||||
description = db.Column(db.String(255))
|
description = db.Column(db.String(255))
|
||||||
|
|
||||||
def __init__(self, name=None, description=None):
|
def __init__(self, name=None, description=None):
|
||||||
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)
|
||||||
username = db.Column(db.String(255), unique=True)
|
username = db.Column(db.String(255), unique=True)
|
||||||
email = 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())
|
active = db.Column(db.Boolean())
|
||||||
created_at = db.Column(db.DateTime())
|
created_at = db.Column(db.DateTime())
|
||||||
modified_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'))
|
backref=db.backref('users', lazy='dynamic'))
|
||||||
|
|
||||||
def __init__(self, username=None, email=None, password=None,
|
def __init__(self, username=None, email=None, password=None,
|
||||||
active=True, roles=None,
|
active=True, roles=None,
|
||||||
created_at=None, modified_at=None):
|
created_at=None, modified_at=None):
|
||||||
self.username = username
|
self.username = username
|
||||||
self.email = email
|
self.email = email
|
||||||
@@ -72,21 +73,20 @@ class SQLAlchemyUserDatastore(UserDatastore):
|
|||||||
self.roles = roles or []
|
self.roles = roles or []
|
||||||
self.created_at = created_at
|
self.created_at = created_at
|
||||||
self.modified_at = modified_at
|
self.modified_at = modified_at
|
||||||
|
|
||||||
return User, Role
|
return User, Role
|
||||||
|
|
||||||
def _save_model(self, model):
|
def _save_model(self, model):
|
||||||
self.db.session.add(model)
|
self.db.session.add(model)
|
||||||
self.db.session.commit()
|
self.db.session.commit()
|
||||||
return model
|
return model
|
||||||
|
|
||||||
def _do_with_id(self, id):
|
def _do_with_id(self, id):
|
||||||
return security.User.query.get(id)
|
return security.User.query.get(id)
|
||||||
|
|
||||||
def _do_find_user(self, user):
|
def _do_find_user(self, user):
|
||||||
return security.User.query.filter_by(username=user).first() or \
|
return security.User.query.filter_by(username=user).first() or \
|
||||||
security.User.query.filter_by(email=user).first()
|
security.User.query.filter_by(email=user).first()
|
||||||
|
|
||||||
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()
|
||||||
|
|
||||||
+33
-16
@@ -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)
|
||||||
@@ -21,7 +23,7 @@ def pprint(obj):
|
|||||||
|
|
||||||
class CreateUserCommand(Command):
|
class CreateUserCommand(Command):
|
||||||
"""Create a user"""
|
"""Create a user"""
|
||||||
|
|
||||||
option_list = (
|
option_list = (
|
||||||
Option('-u', '--username', dest='username', default=None),
|
Option('-u', '--username', dest='username', default=None),
|
||||||
Option('-e', '--email', dest='email', default=None),
|
Option('-e', '--email', dest='email', default=None),
|
||||||
@@ -33,20 +35,33 @@ class CreateUserCommand(Command):
|
|||||||
def run(self, **kwargs):
|
def run(self, **kwargs):
|
||||||
# sanitize active input
|
# sanitize active input
|
||||||
ai = re.sub(r'\s', '', str(kwargs['active']))
|
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
|
# sanitize role input a bit
|
||||||
ri = re.sub(r'\s', '', kwargs['roles'])
|
ri = re.sub(r'\s', '', kwargs['roles'])
|
||||||
kwargs['roles'] = [] if ri == '' else ri.split(',')
|
kwargs['roles'] = [] if ri == '' else ri.split(',')
|
||||||
|
|
||||||
user_datastore.create_user(**kwargs)
|
user_datastore.create_user(**kwargs)
|
||||||
|
|
||||||
print 'User created successfully.'
|
print 'User created successfully.'
|
||||||
kwargs['password'] = '****'
|
kwargs['password'] = '****'
|
||||||
pprint(kwargs)
|
pprint(kwargs)
|
||||||
|
|
||||||
|
|
||||||
class _RoleCommand(Command):
|
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):
|
||||||
option_list = (
|
option_list = (
|
||||||
Option('-u', '--user', dest='user_identifier'),
|
Option('-u', '--user', dest='user_identifier'),
|
||||||
Option('-r', '--role', dest='role_name'),
|
Option('-r', '--role', dest='role_name'),
|
||||||
@@ -55,7 +70,7 @@ class _RoleCommand(Command):
|
|||||||
|
|
||||||
class AddRoleCommand(_RoleCommand):
|
class AddRoleCommand(_RoleCommand):
|
||||||
"""Add a role to a user"""
|
"""Add a role to a user"""
|
||||||
|
|
||||||
def run(self, user_identifier, role_name):
|
def run(self, user_identifier, role_name):
|
||||||
user_datastore.add_role_to_user(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)
|
print "Role '%s' added to user '%s' successfully" % (role_name, user_identifier)
|
||||||
@@ -63,27 +78,29 @@ class AddRoleCommand(_RoleCommand):
|
|||||||
|
|
||||||
class RemoveRoleCommand(_RoleCommand):
|
class RemoveRoleCommand(_RoleCommand):
|
||||||
"""Add a role to a user"""
|
"""Add a role to a user"""
|
||||||
|
|
||||||
def run(self, user_identifier, role_name):
|
def run(self, user_identifier, role_name):
|
||||||
user_datastore.remove_role_from_user(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)
|
print "Role '%s' removed from user '%s' successfully" % (role_name, user_identifier)
|
||||||
|
|
||||||
|
|
||||||
class _ToggleActiveCommand(Command):
|
class _ToggleActiveCommand(Command):
|
||||||
option_list = (
|
option_list = (
|
||||||
Option('-u', '--user', dest='user_identifier'),
|
Option('-u', '--user', dest='user_identifier'),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DeactivateUserCommand(_ToggleActiveCommand):
|
class DeactivateUserCommand(_ToggleActiveCommand):
|
||||||
"""Deactive a user"""
|
"""Deactive a user"""
|
||||||
|
|
||||||
def run(self, user_identifier):
|
def run(self, user_identifier):
|
||||||
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"""
|
||||||
|
|
||||||
def run(self, user_identifier):
|
def run(self, user_identifier):
|
||||||
user_datastore.activate_user(user_identifier)
|
user_datastore.activate_user(user_identifier)
|
||||||
print "User '%s' has been activated" % user_identifier
|
print "User '%s' has been activated" % user_identifier
|
||||||
|
|||||||
@@ -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,7 +2,7 @@
|
|||||||
Flask-Security
|
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.
|
via Flask-Login, Flask-Principal, Flask-WTF, and passlib.
|
||||||
|
|
||||||
Links
|
Links
|
||||||
@@ -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',
|
||||||
|
|||||||
+39
-34
@@ -1,108 +1,113 @@
|
|||||||
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
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
super(SecurityTest, self).setUp()
|
super(SecurityTest, self).setUp()
|
||||||
|
|
||||||
self.app = self._create_app(self.AUTH_CONFIG or None)
|
self.app = self._create_app(self.AUTH_CONFIG or None)
|
||||||
self.app.debug = False
|
self.app.debug = False
|
||||||
self.app.config['TESTING'] = True
|
self.app.config['TESTING'] = True
|
||||||
|
|
||||||
self.client = self.app.test_client()
|
self.client = self.app.test_client()
|
||||||
|
|
||||||
def _create_app(self, auth_config):
|
def _create_app(self, auth_config):
|
||||||
return app.create_sqlalchemy_app(auth_config)
|
return app.create_sqlalchemy_app(auth_config)
|
||||||
|
|
||||||
def _get(self, route, content_type=None, follow_redirects=None):
|
def _get(self, route, content_type=None, follow_redirects=None):
|
||||||
return self.client.get(route, follow_redirects=follow_redirects,
|
return self.client.get(route, follow_redirects=follow_redirects,
|
||||||
content_type=content_type or 'text/html')
|
content_type=content_type or 'text/html')
|
||||||
|
|
||||||
def _post(self, route, data=None, content_type=None, follow_redirects=True):
|
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,
|
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,
|
||||||
content_type='application/x-www-form-urlencoded')
|
content_type='application/x-www-form-urlencoded')
|
||||||
|
|
||||||
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):
|
||||||
r = self._get('/login')
|
r = self._get('/login')
|
||||||
assert 'Login Page' in r.data
|
assert 'Login Page' in r.data
|
||||||
|
|
||||||
def test_authenticate(self):
|
def test_authenticate(self):
|
||||||
r = self.authenticate("matt", "password")
|
r = self.authenticate("matt", "password")
|
||||||
assert 'Home Page' in r.data
|
assert 'Home Page' in r.data
|
||||||
|
|
||||||
def test_unprovided_username(self):
|
def test_unprovided_username(self):
|
||||||
r = self.authenticate("", "password")
|
r = self.authenticate("", "password")
|
||||||
assert "Username not provided" in r.data
|
assert "Username not provided" in r.data
|
||||||
|
|
||||||
def test_unprovided_password(self):
|
def test_unprovided_password(self):
|
||||||
r = self.authenticate("matt", "")
|
r = self.authenticate("matt", "")
|
||||||
assert "Password not provided" in r.data
|
assert "Password not provided" in r.data
|
||||||
|
|
||||||
def test_invalid_user(self):
|
def test_invalid_user(self):
|
||||||
r = self.authenticate("bogus", "password")
|
r = self.authenticate("bogus", "password")
|
||||||
assert "Specified user does not exist" in r.data
|
assert "Specified user does not exist" in r.data
|
||||||
|
|
||||||
def test_bad_password(self):
|
def test_bad_password(self):
|
||||||
r = self.authenticate("matt", "bogus")
|
r = self.authenticate("matt", "bogus")
|
||||||
assert "Password does not match" in r.data
|
assert "Password does not match" in r.data
|
||||||
|
|
||||||
def test_inactive_user(self):
|
def test_inactive_user(self):
|
||||||
r = self.authenticate("tiya", "password")
|
r = self.authenticate("tiya", "password")
|
||||||
assert "Inactive user" in r.data
|
assert "Inactive user" in r.data
|
||||||
|
|
||||||
def test_logout(self):
|
def test_logout(self):
|
||||||
self.authenticate("matt", "password")
|
self.authenticate("matt", "password")
|
||||||
r = self.logout()
|
r = self.logout()
|
||||||
assert 'Home Page' in r.data
|
assert 'Home Page' in r.data
|
||||||
|
|
||||||
def test_unauthorized_access(self):
|
def test_unauthorized_access(self):
|
||||||
r = self._get('/profile', follow_redirects=True)
|
r = self._get('/profile', follow_redirects=True)
|
||||||
assert 'Please log in to access this page' in r.data
|
assert 'Please log in to access this page' in r.data
|
||||||
|
|
||||||
def test_authorized_access(self):
|
def test_authorized_access(self):
|
||||||
self.authenticate("matt", "password")
|
self.authenticate("matt", "password")
|
||||||
r = self._get("/profile")
|
r = self._get("/profile")
|
||||||
assert 'profile' in r.data
|
assert 'profile' in r.data
|
||||||
|
|
||||||
def test_valid_admin_role(self):
|
def test_valid_admin_role(self):
|
||||||
self.authenticate("matt", "password")
|
self.authenticate("matt", "password")
|
||||||
r = self._get("/admin")
|
r = self._get("/admin")
|
||||||
assert 'Admin Page' in r.data
|
assert 'Admin Page' in r.data
|
||||||
|
|
||||||
def test_invalid_admin_role(self):
|
def test_invalid_admin_role(self):
|
||||||
self.authenticate("joe", "password")
|
self.authenticate("joe", "password")
|
||||||
r = self._get("/admin", follow_redirects=True)
|
r = self._get("/admin", follow_redirects=True)
|
||||||
assert 'Home Page' in r.data
|
assert 'Home Page' in r.data
|
||||||
|
|
||||||
def test_roles_accepted(self):
|
def test_roles_accepted(self):
|
||||||
for user in ("matt", "joe"):
|
for user in ("matt", "joe"):
|
||||||
self.authenticate(user, "password")
|
self.authenticate(user, "password")
|
||||||
r = self._get("/admin_or_editor")
|
r = self._get("/admin_or_editor")
|
||||||
self.assertIn('Admin or Editor Page', r.data)
|
self.assertIn('Admin or Editor Page', r.data)
|
||||||
self.logout()
|
self.logout()
|
||||||
|
|
||||||
self.authenticate("jill", "password")
|
self.authenticate("jill", "password")
|
||||||
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):
|
|
||||||
|
|
||||||
AUTH_CONFIG = {
|
AUTH_CONFIG = {
|
||||||
'SECURITY_PASSWORD_HASH': 'bcrypt',
|
'SECURITY_PASSWORD_HASH': 'bcrypt',
|
||||||
'SECURITY_USER_DATASTORE': 'custom_datastore_name',
|
'SECURITY_USER_DATASTORE': 'custom_datastore_name',
|
||||||
@@ -112,22 +117,22 @@ class ConfiguredSecurityTests(SecurityTest):
|
|||||||
'SECURITY_POST_LOGIN': '/post_login',
|
'SECURITY_POST_LOGIN': '/post_login',
|
||||||
'SECURITY_POST_LOGOUT': '/post_logout'
|
'SECURITY_POST_LOGOUT': '/post_logout'
|
||||||
}
|
}
|
||||||
|
|
||||||
def test_login_view(self):
|
def test_login_view(self):
|
||||||
r = self._get('/custom_login')
|
r = self._get('/custom_login')
|
||||||
assert "Custom Login Page" in r.data
|
assert "Custom Login Page" in r.data
|
||||||
|
|
||||||
def test_authenticate(self):
|
def test_authenticate(self):
|
||||||
r = self.authenticate("matt", "password", endpoint="/custom_auth")
|
r = self.authenticate("matt", "password", endpoint="/custom_auth")
|
||||||
assert 'Post Login' in r.data
|
assert 'Post Login' in r.data
|
||||||
|
|
||||||
def test_logout(self):
|
def test_logout(self):
|
||||||
self.authenticate("matt", "password", endpoint="/custom_auth")
|
self.authenticate("matt", "password", endpoint="/custom_auth")
|
||||||
r = self.logout(endpoint="/custom_logout")
|
r = self.logout(endpoint="/custom_logout")
|
||||||
assert 'Post Logout' in r.data
|
assert 'Post Logout' in r.data
|
||||||
|
|
||||||
|
|
||||||
class MongoEngineSecurityTests(DefaultSecurityTests):
|
class MongoEngineSecurityTests(DefaultSecurityTests):
|
||||||
|
|
||||||
def _create_app(self, auth_config):
|
def _create_app(self, auth_config):
|
||||||
return app.create_mongoengine_app(auth_config)
|
return app.create_mongoengine_app(auth_config)
|
||||||
|
|||||||
+12
-10
@@ -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
|
||||||
@@ -13,32 +14,33 @@ class User(UserMixin):
|
|||||||
self.username = username
|
self.username = username
|
||||||
self.email = email
|
self.email = email
|
||||||
self.roles = roles
|
self.roles = roles
|
||||||
|
|
||||||
# set the models or we'll get errors
|
# set the models or we'll get errors
|
||||||
flask_security.User = User
|
flask_security.User = User
|
||||||
flask_security.Role = Role
|
flask_security.Role = Role
|
||||||
|
|
||||||
admin = Role('admin')
|
admin = Role('admin')
|
||||||
admin2 = Role('admin')
|
admin2 = Role('admin')
|
||||||
editor = Role('editor')
|
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):
|
||||||
self.assertEqual(admin, admin2)
|
self.assertEqual(admin, admin2)
|
||||||
|
|
||||||
def test_role_mixin_not_equal(self):
|
def test_role_mixin_not_equal(self):
|
||||||
self.assertNotEqual(admin, editor)
|
self.assertNotEqual(admin, editor)
|
||||||
|
|
||||||
def test_user_mixin_has_role_with_string(self):
|
def test_user_mixin_has_role_with_string(self):
|
||||||
self.assertTrue(user.has_role('admin'))
|
self.assertTrue(user.has_role('admin'))
|
||||||
|
|
||||||
def test_user_mixin_has_role_with_role_obj(self):
|
def test_user_mixin_has_role_with_role_obj(self):
|
||||||
self.assertTrue(user.has_role(Role('admin')))
|
self.assertTrue(user.has_role(Role('admin')))
|
||||||
|
|
||||||
def test_anonymous_user_has_no_roles(self):
|
def test_anonymous_user_has_no_roles(self):
|
||||||
au = AnonymousUser()
|
au = AnonymousUser()
|
||||||
self.assertEqual(0, len(au.roles))
|
self.assertEqual(0, len(au.roles))
|
||||||
self.assertFalse(au.has_role('admin'))
|
self.assertFalse(au.has_role('admin'))
|
||||||
|
|||||||
Reference in New Issue
Block a user