mirror of
https://github.com/wassname/flask-security.git
synced 2026-08-07 11:22:21 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c9bc541f9 | ||
|
|
f7147648ba | ||
|
|
30b72cb7f4 | ||
|
|
ab08abcaf9 | ||
|
|
0227d987fe | ||
|
|
5df01af720 | ||
|
|
0acf4bca0d | ||
|
|
2e37af8c01 | ||
|
|
245914cc9a | ||
|
|
201ee5b708 | ||
|
|
744ded7f1b | ||
|
|
5a7f4dff47 | ||
|
|
dd6ba0995d | ||
|
|
5697f7c953 | ||
|
|
144b22a3b9 | ||
|
|
3c57e169d1 |
@@ -1,6 +1,8 @@
|
||||
.DS_Store
|
||||
*.pyc
|
||||
*.egg
|
||||
*.egg-info
|
||||
.project
|
||||
.pydevproject
|
||||
.settings
|
||||
dist
|
||||
|
||||
@@ -3,6 +3,22 @@ Flask-Security Changelog
|
||||
|
||||
Here you can see the full list of changes between each Flask-Security release.
|
||||
|
||||
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
|
||||
-------------
|
||||
|
||||
|
||||
@@ -2,8 +2,19 @@ MIT License
|
||||
|
||||
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.
|
||||
+4
-3
@@ -16,8 +16,9 @@ import sys, os
|
||||
# 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
|
||||
# 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('..'))
|
||||
#from setup import __version__
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
@@ -49,9 +50,9 @@ copyright = u'2012, Matt Wright'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '1.1'
|
||||
version = '1.2.1'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '1.1.0'
|
||||
release = version
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
+43
-7
@@ -28,6 +28,8 @@ Contents
|
||||
* :ref:`overview`
|
||||
* :ref:`installation`
|
||||
* :ref:`getting-started`
|
||||
* :ref:`additional-user-fields`
|
||||
* :ref:`flask-script-commands`
|
||||
* :ref:`api`
|
||||
* :doc:`Changelog </changelog>`
|
||||
|
||||
@@ -58,7 +60,7 @@ Installation
|
||||
First, install Flask-Security::
|
||||
|
||||
$ mkvirtualenv app-name
|
||||
$ pip install https://github.com/mattupstate/flask-security/tarball/master
|
||||
$ pip install Flask-Security
|
||||
|
||||
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.ext.sqlalchemy import SQLAlchemy
|
||||
from flask.ext.security import User, Security, LoginForm,
|
||||
login_required, roles_accepted, user_datastore
|
||||
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDataStore
|
||||
from flask.ext.security import (User, Security, LoginForm, login_required,
|
||||
roles_accepted, user_datastore)
|
||||
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
|
||||
|
||||
app = Flask(__name__)
|
||||
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)
|
||||
Security(app, SQLAlchemyUserDatastore(db))
|
||||
|
||||
You'll probably want to at least one user to the database to test this out, so
|
||||
you can add something such as the following to quickly add an initial user::
|
||||
You'll probably want to at least one user to the database to test this out.
|
||||
There are many ways to do this, but this is a quick and dirty way to do it::
|
||||
|
||||
@app.before_first_request
|
||||
def before_first_request():
|
||||
user_datastore.create_role(name='admin')
|
||||
user_datastore.create_user(username='matt', email='matt@something.com',
|
||||
password='password', roles['admin'])
|
||||
password='password', roles=['admin'])
|
||||
|
||||
Next you'll want to setup your login screen. Setup your view::
|
||||
|
||||
@@ -150,6 +152,38 @@ specific role::
|
||||
{% if current_user.has_role('admin') %}
|
||||
<a href="{{ url_for('admin.index') }}">Admin Panel</a>
|
||||
{$ 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:
|
||||
@@ -220,9 +254,11 @@ Datastores
|
||||
|
||||
.. autoclass:: flask_security.datastore.sqlalchemy.SQLAlchemyUserDatastore
|
||||
:members:
|
||||
:inherited-members:
|
||||
|
||||
.. autoclass:: flask_security.datastore.mongoengine.MongoEngineUserDatastore
|
||||
:members:
|
||||
:inherited-members:
|
||||
|
||||
|
||||
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'
|
||||
|
||||
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
|
||||
def before_first_request():
|
||||
@@ -101,7 +106,12 @@ def create_mongoengine_app(auth_config=None):
|
||||
app.config['MONGODB_PORT'] = 27017
|
||||
|
||||
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
|
||||
def before_first_request():
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
{{ form.username.label }} {{ form.username }}<br/>
|
||||
{{ form.password.label }} {{ form.password }}<br/>
|
||||
{{ form.remember.label }} {{ form.remember }}<br/>
|
||||
{{ form.next }}
|
||||
{{ form.submit }}
|
||||
</form>
|
||||
<p>{{ content }}</p>
|
||||
|
||||
@@ -20,7 +20,8 @@ from flask import (current_app, Blueprint, flash, redirect, request,
|
||||
|
||||
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)
|
||||
logout_user, current_user, user_logged_in, user_logged_out,
|
||||
login_url)
|
||||
|
||||
from flask.ext.principal import (Identity, Principal, RoleNeed, UserNeed,
|
||||
Permission, AnonymousIdentity, identity_changed, identity_loaded)
|
||||
@@ -147,7 +148,8 @@ def roles_required(*args):
|
||||
@wraps(fn)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if not current_user.is_authenticated():
|
||||
return redirect(current_app.config[LOGIN_VIEW_KEY])
|
||||
return redirect(
|
||||
login_url(current_app.config[LOGIN_VIEW_KEY], request.url))
|
||||
|
||||
if perm.can():
|
||||
return fn(*args, **kwargs)
|
||||
@@ -181,7 +183,8 @@ def roles_accepted(*args):
|
||||
@wraps(fn)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if not current_user.is_authenticated():
|
||||
return redirect(current_app.config[LOGIN_VIEW_KEY])
|
||||
return redirect(
|
||||
login_url(current_app.config[LOGIN_VIEW_KEY], request.url))
|
||||
|
||||
for perm in perms:
|
||||
if perm.can():
|
||||
@@ -256,6 +259,7 @@ class Security(object):
|
||||
"""
|
||||
if app is None or datastore is None: return
|
||||
|
||||
# TODO: change blueprint name
|
||||
blueprint = Blueprint('auth', __name__)
|
||||
|
||||
configured = {}
|
||||
|
||||
@@ -19,10 +19,13 @@ class UserDatastore(object):
|
||||
:attr:`_do_find_user`, and :attr:`_do_find_role` methods.
|
||||
|
||||
:param db: An instance of a configured databse manager from a Flask
|
||||
extension such as Flask-SQLAlchemy or Flask-MongoEngine"""
|
||||
|
||||
def __init__(self, db):
|
||||
extension such as Flask-SQLAlchemy or Flask-MongoEngine
|
||||
:param user_account_mixin: An optional mixin class that specifies additional
|
||||
fields to be added to the user model
|
||||
"""
|
||||
def __init__(self, db, user_account_mixin=None):
|
||||
self.db = db
|
||||
self.user_account_mixin = user_account_mixin or object
|
||||
|
||||
def get_models(self):
|
||||
"""Returns configured `User` and `Role` models for the datastore
|
||||
|
||||
@@ -41,7 +41,7 @@ class MongoEngineUserDatastore(UserDatastore):
|
||||
name = db.StringField(required=True, unique=True, max_length=80)
|
||||
description = db.StringField(max_length=255)
|
||||
|
||||
class User(db.Document, UserMixin):
|
||||
class User(db.Document, UserMixin, self.user_account_mixin):
|
||||
"""MongoEngine User model"""
|
||||
|
||||
username = db.StringField(unique=True, max_length=255)
|
||||
|
||||
@@ -48,7 +48,7 @@ class SQLAlchemyUserDatastore(UserDatastore):
|
||||
self.name = name
|
||||
self.description = description
|
||||
|
||||
class User(db.Model, UserMixin):
|
||||
class User(db.Model, UserMixin, self.user_account_mixin):
|
||||
"""SQLAlchemy User model"""
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
|
||||
@@ -46,6 +46,19 @@ class CreateUserCommand(Command):
|
||||
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):
|
||||
role = user_datastore.create_role(**kwargs)
|
||||
print 'Role "%(name)s" created successfully.' % kwargs
|
||||
|
||||
|
||||
class _RoleCommand(Command):
|
||||
option_list = (
|
||||
Option('-u', '--user', dest='user_identifier'),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Flask-Security
|
||||
--------------
|
||||
|
||||
Flask-Security is a Flask extension that aims to add quick and simple security
|
||||
Flask-Security is a Flask extension that aims to add quick and simple security
|
||||
via Flask-Login, Flask-Principal, Flask-WTF, and passlib.
|
||||
|
||||
Links
|
||||
@@ -12,11 +12,12 @@ Links
|
||||
<https://github.com/mattupstate/flask-security/raw/develop#egg=Flask-Security-dev>`_
|
||||
|
||||
"""
|
||||
|
||||
from setuptools import setup
|
||||
|
||||
setup(
|
||||
name='Flask-Security',
|
||||
version='1.2.0',
|
||||
version='1.2.2',
|
||||
url='https://github.com/mattupstate/flask-security',
|
||||
license='MIT',
|
||||
author='Matthew Wright',
|
||||
|
||||
+39
-34
@@ -1,108 +1,113 @@
|
||||
import unittest
|
||||
from example import app
|
||||
|
||||
|
||||
class SecurityTest(unittest.TestCase):
|
||||
|
||||
|
||||
AUTH_CONFIG = None
|
||||
|
||||
|
||||
def setUp(self):
|
||||
super(SecurityTest, self).setUp()
|
||||
|
||||
|
||||
self.app = self._create_app(self.AUTH_CONFIG or None)
|
||||
self.app.debug = False
|
||||
self.app.config['TESTING'] = True
|
||||
|
||||
|
||||
self.client = self.app.test_client()
|
||||
|
||||
|
||||
def _create_app(self, auth_config):
|
||||
return app.create_sqlalchemy_app(auth_config)
|
||||
|
||||
|
||||
def _get(self, route, content_type=None, follow_redirects=None):
|
||||
return self.client.get(route, follow_redirects=follow_redirects,
|
||||
content_type=content_type or 'text/html')
|
||||
|
||||
|
||||
def _post(self, route, data=None, content_type=None, follow_redirects=True):
|
||||
return self.client.post(route, data=data,
|
||||
return self.client.post(route, data=data,
|
||||
follow_redirects=follow_redirects,
|
||||
content_type=content_type or 'text/html')
|
||||
|
||||
|
||||
|
||||
def authenticate(self, username, password, endpoint=None):
|
||||
data = dict(username=username, password=password)
|
||||
return self._post(endpoint or '/auth', data=data,
|
||||
return self._post(endpoint or '/auth', data=data,
|
||||
content_type='application/x-www-form-urlencoded')
|
||||
|
||||
|
||||
def logout(self, endpoint=None):
|
||||
return self._get(endpoint or '/logout', follow_redirects=True)
|
||||
|
||||
|
||||
class DefaultSecurityTests(SecurityTest):
|
||||
|
||||
|
||||
def test_login_view(self):
|
||||
r = self._get('/login')
|
||||
assert 'Login Page' in r.data
|
||||
|
||||
|
||||
def test_authenticate(self):
|
||||
r = self.authenticate("matt", "password")
|
||||
assert 'Home Page' in r.data
|
||||
|
||||
|
||||
def test_unprovided_username(self):
|
||||
r = self.authenticate("", "password")
|
||||
assert "Username not provided" in r.data
|
||||
|
||||
|
||||
def test_unprovided_password(self):
|
||||
r = self.authenticate("matt", "")
|
||||
assert "Password not provided" in r.data
|
||||
|
||||
|
||||
def test_invalid_user(self):
|
||||
r = self.authenticate("bogus", "password")
|
||||
assert "Specified user does not exist" in r.data
|
||||
|
||||
|
||||
def test_bad_password(self):
|
||||
r = self.authenticate("matt", "bogus")
|
||||
assert "Password does not match" in r.data
|
||||
|
||||
|
||||
def test_inactive_user(self):
|
||||
r = self.authenticate("tiya", "password")
|
||||
assert "Inactive user" in r.data
|
||||
|
||||
|
||||
def test_logout(self):
|
||||
self.authenticate("matt", "password")
|
||||
r = self.logout()
|
||||
assert 'Home Page' in r.data
|
||||
|
||||
|
||||
def test_unauthorized_access(self):
|
||||
r = self._get('/profile', follow_redirects=True)
|
||||
assert 'Please log in to access this page' in r.data
|
||||
|
||||
|
||||
def test_authorized_access(self):
|
||||
self.authenticate("matt", "password")
|
||||
r = self._get("/profile")
|
||||
assert 'profile' in r.data
|
||||
|
||||
|
||||
def test_valid_admin_role(self):
|
||||
self.authenticate("matt", "password")
|
||||
r = self._get("/admin")
|
||||
assert 'Admin Page' in r.data
|
||||
|
||||
|
||||
def test_invalid_admin_role(self):
|
||||
self.authenticate("joe", "password")
|
||||
r = self._get("/admin", follow_redirects=True)
|
||||
assert 'Home Page' in r.data
|
||||
|
||||
|
||||
def test_roles_accepted(self):
|
||||
for user in ("matt", "joe"):
|
||||
self.authenticate(user, "password")
|
||||
r = self._get("/admin_or_editor")
|
||||
self.assertIn('Admin or Editor Page', r.data)
|
||||
self.logout()
|
||||
|
||||
|
||||
self.authenticate("jill", "password")
|
||||
r = self._get("/admin_or_editor", follow_redirects=True)
|
||||
self.assertIn('Home Page', r.data)
|
||||
|
||||
def test_unauthenticated_role_required(self):
|
||||
r = self._get('/admin', follow_redirects=True)
|
||||
self.assertIn('<input id="next"', r.data)
|
||||
|
||||
|
||||
class ConfiguredSecurityTests(SecurityTest):
|
||||
|
||||
class ConfiguredSecurityTests(SecurityTest):
|
||||
|
||||
AUTH_CONFIG = {
|
||||
'SECURITY_PASSWORD_HASH': 'bcrypt',
|
||||
'SECURITY_USER_DATASTORE': 'custom_datastore_name',
|
||||
@@ -112,22 +117,22 @@ class ConfiguredSecurityTests(SecurityTest):
|
||||
'SECURITY_POST_LOGIN': '/post_login',
|
||||
'SECURITY_POST_LOGOUT': '/post_logout'
|
||||
}
|
||||
|
||||
|
||||
def test_login_view(self):
|
||||
r = self._get('/custom_login')
|
||||
assert "Custom Login Page" in r.data
|
||||
|
||||
|
||||
def test_authenticate(self):
|
||||
r = self.authenticate("matt", "password", endpoint="/custom_auth")
|
||||
assert 'Post Login' in r.data
|
||||
|
||||
|
||||
def test_logout(self):
|
||||
self.authenticate("matt", "password", endpoint="/custom_auth")
|
||||
r = self.logout(endpoint="/custom_logout")
|
||||
assert 'Post Logout' in r.data
|
||||
|
||||
|
||||
|
||||
class MongoEngineSecurityTests(DefaultSecurityTests):
|
||||
|
||||
|
||||
def _create_app(self, auth_config):
|
||||
return app.create_mongoengine_app(auth_config)
|
||||
return app.create_mongoengine_app(auth_config)
|
||||
|
||||
Reference in New Issue
Block a user