mirror of
https://github.com/wassname/flask-security.git
synced 2026-08-07 11:22:21 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ddbcdca06 | ||
|
|
edf41096d7 | ||
|
|
3ce907db79 | ||
|
|
5c9bc541f9 | ||
|
|
f7147648ba | ||
|
|
30b72cb7f4 | ||
|
|
ab08abcaf9 | ||
|
|
0227d987fe | ||
|
|
5df01af720 | ||
|
|
0acf4bca0d |
@@ -3,6 +3,21 @@ 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
|
Version 1.2.1
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -18,7 +18,7 @@ import sys, os
|
|||||||
# 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.insert(0, os.path.abspath('..'))
|
||||||
sys.path.append(os.path.abspath('_themes'))
|
sys.path.append(os.path.abspath('_themes'))
|
||||||
from flask_security import __version__
|
#from setup import __version__
|
||||||
|
|
||||||
# -- General configuration -----------------------------------------------------
|
# -- General configuration -----------------------------------------------------
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ copyright = u'2012, Matt Wright'
|
|||||||
# built documents.
|
# built documents.
|
||||||
#
|
#
|
||||||
# The short X.Y version.
|
# The short X.Y version.
|
||||||
version = __version__
|
version = '1.2.3'
|
||||||
# The full version, including alpha/beta/rc tags.
|
# The full version, including alpha/beta/rc tags.
|
||||||
release = version
|
release = version
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -85,7 +85,7 @@ First thing you'll want to do is setup your application and datastore::
|
|||||||
from flask.ext.sqlalchemy import SQLAlchemy
|
from flask.ext.sqlalchemy import SQLAlchemy
|
||||||
from flask.ext.security import (User, Security, LoginForm, login_required,
|
from flask.ext.security import (User, Security, LoginForm, 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'
|
||||||
@@ -94,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::
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
+52
-39
@@ -10,47 +10,43 @@
|
|||||||
:license: MIT, see LICENSE for more details.
|
:license: MIT, see LICENSE for more details.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = '1.2.1'
|
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from types import StringType
|
|
||||||
|
|
||||||
from flask import (current_app, Blueprint, flash, redirect, request,
|
|
||||||
session, _request_ctx_stack, url_for, abort, g)
|
|
||||||
|
|
||||||
from flask.ext.login import (AnonymousUser as AnonymousUserBase,
|
|
||||||
UserMixin as BaseUserMixin, LoginManager, login_required, login_user,
|
|
||||||
logout_user, current_user, user_logged_in, user_logged_out)
|
|
||||||
|
|
||||||
from flask.ext.principal import (Identity, Principal, RoleNeed, UserNeed,
|
|
||||||
Permission, AnonymousIdentity, identity_changed, identity_loaded)
|
|
||||||
|
|
||||||
from flask.ext.wtf import (Form, TextField, PasswordField, SubmitField,
|
|
||||||
HiddenField, Required, ValidationError, BooleanField, Email)
|
|
||||||
|
|
||||||
from functools import wraps
|
from 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'
|
||||||
@@ -80,34 +76,41 @@ class BadCredentialsError(Exception):
|
|||||||
provided credentials.
|
provided credentials.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class AuthenticationError(Exception):
|
class AuthenticationError(Exception):
|
||||||
"""Raised when an authentication attempt fails due to invalid configuration
|
"""Raised when an authentication attempt fails due to invalid configuration
|
||||||
or an unknown reason.
|
or an unknown reason.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class UserNotFoundError(Exception):
|
class UserNotFoundError(Exception):
|
||||||
"""Raised by a user datastore when there is an attempt to find a user by
|
"""Raised by a user datastore when there is an attempt to find a user by
|
||||||
their identifier, often username or email, and the user is not found.
|
their identifier, often username or email, and the user is not found.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class RoleNotFoundError(Exception):
|
class RoleNotFoundError(Exception):
|
||||||
"""Raised by a user datastore when there is an attempt to find a role and
|
"""Raised by a user datastore when there is an attempt to find a role and
|
||||||
the role cannot be found.
|
the role cannot be found.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class UserIdNotFoundError(Exception):
|
class UserIdNotFoundError(Exception):
|
||||||
"""Raised by a user datastore when there is an attempt to find a user by
|
"""Raised by a user datastore when there is an attempt to find a user by
|
||||||
ID and the user is not found.
|
ID and the user is not found.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class UserDatastoreError(Exception):
|
class UserDatastoreError(Exception):
|
||||||
"""Raised when a user datastore experiences an unexpected error
|
"""Raised when a user datastore experiences an unexpected error
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class UserCreationError(Exception):
|
class UserCreationError(Exception):
|
||||||
"""Raised when an error occurs when creating a user
|
"""Raised when an error occurs when creating a user
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class RoleCreationError(Exception):
|
class RoleCreationError(Exception):
|
||||||
"""Raised when an error occurs when creating a role
|
"""Raised when an error occurs when creating a role
|
||||||
"""
|
"""
|
||||||
@@ -129,6 +132,7 @@ pwd_context = LocalProxy(lambda: current_app.pwd_context)
|
|||||||
user_datastore = LocalProxy(lambda: getattr(current_app,
|
user_datastore = LocalProxy(lambda: getattr(current_app,
|
||||||
current_app.config[USER_DATASTORE_KEY]))
|
current_app.config[USER_DATASTORE_KEY]))
|
||||||
|
|
||||||
|
|
||||||
def roles_required(*args):
|
def roles_required(*args):
|
||||||
"""View decorator which specifies that a user must have all the specified
|
"""View decorator which specifies that a user must have all the specified
|
||||||
roles. Example::
|
roles. Example::
|
||||||
@@ -145,11 +149,13 @@ def roles_required(*args):
|
|||||||
"""
|
"""
|
||||||
roles = args
|
roles = args
|
||||||
perm = Permission(*[RoleNeed(role) for role in roles])
|
perm = Permission(*[RoleNeed(role) for role in roles])
|
||||||
|
|
||||||
def wrapper(fn):
|
def wrapper(fn):
|
||||||
@wraps(fn)
|
@wraps(fn)
|
||||||
def decorated_view(*args, **kwargs):
|
def decorated_view(*args, **kwargs):
|
||||||
if not current_user.is_authenticated():
|
if not current_user.is_authenticated():
|
||||||
return redirect(current_app.config[LOGIN_VIEW_KEY])
|
return redirect(
|
||||||
|
login_url(current_app.config[LOGIN_VIEW_KEY], request.url))
|
||||||
|
|
||||||
if perm.can():
|
if perm.can():
|
||||||
return fn(*args, **kwargs)
|
return fn(*args, **kwargs)
|
||||||
@@ -179,11 +185,13 @@ def roles_accepted(*args):
|
|||||||
"""
|
"""
|
||||||
roles = args
|
roles = args
|
||||||
perms = [Permission(RoleNeed(role)) for role in roles]
|
perms = [Permission(RoleNeed(role)) for role in roles]
|
||||||
|
|
||||||
def wrapper(fn):
|
def wrapper(fn):
|
||||||
@wraps(fn)
|
@wraps(fn)
|
||||||
def decorated_view(*args, **kwargs):
|
def decorated_view(*args, **kwargs):
|
||||||
if not current_user.is_authenticated():
|
if not current_user.is_authenticated():
|
||||||
return redirect(current_app.config[LOGIN_VIEW_KEY])
|
return redirect(
|
||||||
|
login_url(current_app.config[LOGIN_VIEW_KEY], request.url))
|
||||||
|
|
||||||
for perm in perms:
|
for perm in perms:
|
||||||
if perm.can():
|
if perm.can():
|
||||||
@@ -201,10 +209,10 @@ def roles_accepted(*args):
|
|||||||
class RoleMixin(object):
|
class RoleMixin(object):
|
||||||
"""Mixin for `Role` model definitions"""
|
"""Mixin for `Role` model definitions"""
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return self.name == other.name
|
return self.name == other or self.name == getattr(other, 'name', None)
|
||||||
|
|
||||||
def __ne__(self, other):
|
def __ne__(self, other):
|
||||||
return self.name != other.name
|
return self.name != other and self.name != getattr(other, 'name', None)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return '<Role name=%s, description=%s>' % (self.name, self.description)
|
return '<Role name=%s, description=%s>' % (self.name, self.description)
|
||||||
@@ -221,8 +229,6 @@ class UserMixin(BaseUserMixin):
|
|||||||
"""Returns `True` if the user identifies with the specified role.
|
"""Returns `True` if the user identifies with the specified role.
|
||||||
|
|
||||||
:param role: A role name or `Role` instance"""
|
:param role: A role name or `Role` instance"""
|
||||||
if not isinstance(role, Role):
|
|
||||||
role = Role(name=role)
|
|
||||||
return role in self.roles
|
return role in self.roles
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
@@ -233,7 +239,7 @@ 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`"""
|
||||||
@@ -256,7 +262,8 @@ class Security(object):
|
|||||||
:param app: The application.
|
:param app: The application.
|
||||||
:param datastore: An instance of a user datastore.
|
:param datastore: An instance of a user datastore.
|
||||||
"""
|
"""
|
||||||
if app is None or datastore is None: return
|
if app is None or datastore is None:
|
||||||
|
return
|
||||||
|
|
||||||
# TODO: change blueprint name
|
# TODO: change blueprint name
|
||||||
blueprint = Blueprint('auth', __name__)
|
blueprint = Blueprint('auth', __name__)
|
||||||
@@ -308,6 +315,7 @@ class Security(object):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
auth_url = config[AUTH_URL_KEY]
|
auth_url = config[AUTH_URL_KEY]
|
||||||
|
|
||||||
@blueprint.route(auth_url, methods=['POST'], endpoint='authenticate')
|
@blueprint.route(auth_url, methods=['POST'], endpoint='authenticate')
|
||||||
def authenticate():
|
def authenticate():
|
||||||
try:
|
try:
|
||||||
@@ -424,6 +432,7 @@ class AuthenticationProvider(object):
|
|||||||
logger.error(msg)
|
logger.error(msg)
|
||||||
raise AuthenticationError(msg)
|
raise AuthenticationError(msg)
|
||||||
|
|
||||||
|
|
||||||
def do_flash(message, category):
|
def do_flash(message, category):
|
||||||
if current_app.config[FLASH_MESSAGES_KEY]:
|
if current_app.config[FLASH_MESSAGES_KEY]:
|
||||||
flash(message, category)
|
flash(message, category)
|
||||||
@@ -433,11 +442,12 @@ 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:
|
||||||
@@ -447,6 +457,7 @@ def get_class_from_config(key, config):
|
|||||||
"Could not get class '%s' for Auth setting '%s' >> %s" %
|
"Could not get class '%s' for Auth setting '%s' >> %s" %
|
||||||
(config[key], key, e))
|
(config[key], key, e))
|
||||||
|
|
||||||
|
|
||||||
def get_url(endpoint_or_url):
|
def get_url(endpoint_or_url):
|
||||||
"""Returns a URL if a valid endpoint is found. Otherwise, returns the
|
"""Returns a URL if a valid endpoint is found. Otherwise, returns the
|
||||||
provided value."""
|
provided value."""
|
||||||
@@ -455,12 +466,14 @@ def get_url(endpoint_or_url):
|
|||||||
except:
|
except:
|
||||||
return endpoint_or_url
|
return endpoint_or_url
|
||||||
|
|
||||||
|
|
||||||
def get_post_login_redirect():
|
def get_post_login_redirect():
|
||||||
"""Returns the URL to redirect to after a user logs in successfully"""
|
"""Returns the URL to redirect to after a user logs in successfully"""
|
||||||
return (get_url(request.args.get('next')) or
|
return (get_url(request.args.get('next')) or
|
||||||
get_url(request.form.get('next')) or
|
get_url(request.form.get('next')) or
|
||||||
find_redirect(POST_LOGIN_KEY))
|
find_redirect(POST_LOGIN_KEY))
|
||||||
|
|
||||||
|
|
||||||
def find_redirect(key):
|
def find_redirect(key):
|
||||||
"""Returns the URL to redirect to after a user logs in successfully"""
|
"""Returns the URL to redirect to after a user logs in successfully"""
|
||||||
result = (get_url(session.pop(key.lower(), None)) or
|
result = (get_url(session.pop(key.lower(), None)) or
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ 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`,
|
||||||
@@ -127,7 +128,8 @@ class UserDatastore(object):
|
|||||||
|
|
||||||
:param id: User ID"""
|
:param id: User ID"""
|
||||||
user = self._do_with_id(id)
|
user = self._do_with_id(id)
|
||||||
if user: return user
|
if user:
|
||||||
|
return user
|
||||||
raise security.UserIdNotFoundError()
|
raise security.UserIdNotFoundError()
|
||||||
|
|
||||||
def find_user(self, user):
|
def find_user(self, user):
|
||||||
@@ -136,7 +138,8 @@ class UserDatastore(object):
|
|||||||
:param user: User identifier, usually a username or email address
|
:param user: User identifier, usually a username or email address
|
||||||
"""
|
"""
|
||||||
user = self._do_find_user(user)
|
user = self._do_find_user(user)
|
||||||
if user: return user
|
if user:
|
||||||
|
return user
|
||||||
raise security.UserNotFoundError()
|
raise security.UserNotFoundError()
|
||||||
|
|
||||||
def find_role(self, role):
|
def find_role(self, role):
|
||||||
@@ -145,7 +148,8 @@ class UserDatastore(object):
|
|||||||
:param role: Role name
|
:param role: Role name
|
||||||
"""
|
"""
|
||||||
role = self._do_find_role(role)
|
role = self._do_find_role(role)
|
||||||
if role: return role
|
if role:
|
||||||
|
return role
|
||||||
raise security.RoleNotFoundError()
|
raise security.RoleNotFoundError()
|
||||||
|
|
||||||
def create_role(self, **kwargs):
|
def create_role(self, **kwargs):
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from flask.ext import security
|
|||||||
from flask.ext.security import UserMixin, RoleMixin
|
from flask.ext.security import UserMixin, RoleMixin
|
||||||
from flask.ext.security.datastore import UserDatastore
|
from flask.ext.security.datastore import UserDatastore
|
||||||
|
|
||||||
|
|
||||||
class MongoEngineUserDatastore(UserDatastore):
|
class MongoEngineUserDatastore(UserDatastore):
|
||||||
"""A MongoEngine datastore implementation for Flask-Security.
|
"""A MongoEngine datastore implementation for Flask-Security.
|
||||||
Example usage::
|
Example usage::
|
||||||
@@ -48,7 +49,7 @@ class MongoEngineUserDatastore(UserDatastore):
|
|||||||
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()
|
||||||
|
|
||||||
@@ -59,8 +60,10 @@ class MongoEngineUserDatastore(UserDatastore):
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
def _do_with_id(self, id):
|
def _do_with_id(self, id):
|
||||||
try: return security.User.objects.get(id=id)
|
try:
|
||||||
except: return None
|
return security.User.objects.get(id=id)
|
||||||
|
except:
|
||||||
|
return None
|
||||||
|
|
||||||
def _do_find_user(self, user):
|
def _do_find_user(self, user):
|
||||||
return security.User.objects(username=user).first() or \
|
return security.User.objects(username=user).first() or \
|
||||||
@@ -68,4 +71,3 @@ class MongoEngineUserDatastore(UserDatastore):
|
|||||||
|
|
||||||
def _do_find_role(self, role):
|
def _do_find_role(self, role):
|
||||||
return security.Role.objects(name=role).first()
|
return security.Role.objects(name=role).first()
|
||||||
|
|
||||||
@@ -13,6 +13,7 @@ from flask.ext import security
|
|||||||
from flask.ext.security import UserMixin, RoleMixin
|
from flask.ext.security import UserMixin, RoleMixin
|
||||||
from flask.ext.security.datastore import UserDatastore
|
from flask.ext.security.datastore import UserDatastore
|
||||||
|
|
||||||
|
|
||||||
class SQLAlchemyUserDatastore(UserDatastore):
|
class SQLAlchemyUserDatastore(UserDatastore):
|
||||||
"""A SQLAlchemy datastore implementation for Flask-Security.
|
"""A SQLAlchemy datastore implementation for Flask-Security.
|
||||||
Example usage::
|
Example usage::
|
||||||
@@ -59,7 +60,7 @@ class SQLAlchemyUserDatastore(UserDatastore):
|
|||||||
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,
|
||||||
@@ -89,4 +90,3 @@ class SQLAlchemyUserDatastore(UserDatastore):
|
|||||||
|
|
||||||
def _do_find_role(self, role):
|
def _do_find_role(self, role):
|
||||||
return security.Role.query.filter_by(name=role).first()
|
return security.Role.query.filter_by(name=role).first()
|
||||||
|
|
||||||
@@ -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)
|
||||||
@@ -33,7 +35,7 @@ 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'])
|
||||||
@@ -55,7 +57,7 @@ class CreateRoleCommand(Command):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def run(self, **kwargs):
|
def run(self, **kwargs):
|
||||||
role = user_datastore.create_role(**kwargs)
|
user_datastore.create_role(**kwargs)
|
||||||
print 'Role "%(name)s" created successfully.' % kwargs
|
print 'Role "%(name)s" created successfully.' % kwargs
|
||||||
|
|
||||||
|
|
||||||
@@ -87,6 +89,7 @@ class _ToggleActiveCommand(Command):
|
|||||||
Option('-u', '--user', dest='user_identifier'),
|
Option('-u', '--user', dest='user_identifier'),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DeactivateUserCommand(_ToggleActiveCommand):
|
class DeactivateUserCommand(_ToggleActiveCommand):
|
||||||
"""Deactive a user"""
|
"""Deactive a user"""
|
||||||
|
|
||||||
@@ -94,6 +97,7 @@ class DeactivateUserCommand(_ToggleActiveCommand):
|
|||||||
user_datastore.deactivate_user(user_identifier)
|
user_datastore.deactivate_user(user_identifier)
|
||||||
print "User '%s' has been deactivated" % user_identifier
|
print "User '%s' has been deactivated" % user_identifier
|
||||||
|
|
||||||
|
|
||||||
class ActivateUserCommand(_ToggleActiveCommand):
|
class ActivateUserCommand(_ToggleActiveCommand):
|
||||||
"""Deactive a user"""
|
"""Deactive a user"""
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -12,12 +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 flask_security import __version__
|
|
||||||
from setuptools import setup
|
from setuptools import setup
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name='Flask-Security',
|
name='Flask-Security',
|
||||||
version=__version__,
|
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',
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import unittest
|
import unittest
|
||||||
from example import app
|
from example import app
|
||||||
|
|
||||||
|
|
||||||
class SecurityTest(unittest.TestCase):
|
class SecurityTest(unittest.TestCase):
|
||||||
|
|
||||||
AUTH_CONFIG = None
|
AUTH_CONFIG = None
|
||||||
@@ -26,7 +27,6 @@ class SecurityTest(unittest.TestCase):
|
|||||||
follow_redirects=follow_redirects,
|
follow_redirects=follow_redirects,
|
||||||
content_type=content_type or 'text/html')
|
content_type=content_type or 'text/html')
|
||||||
|
|
||||||
|
|
||||||
def authenticate(self, username, password, endpoint=None):
|
def authenticate(self, username, password, endpoint=None):
|
||||||
data = dict(username=username, password=password)
|
data = dict(username=username, password=password)
|
||||||
return self._post(endpoint or '/auth', data=data,
|
return self._post(endpoint or '/auth', data=data,
|
||||||
@@ -35,6 +35,7 @@ class SecurityTest(unittest.TestCase):
|
|||||||
def logout(self, endpoint=None):
|
def logout(self, endpoint=None):
|
||||||
return self._get(endpoint or '/logout', follow_redirects=True)
|
return self._get(endpoint or '/logout', follow_redirects=True)
|
||||||
|
|
||||||
|
|
||||||
class DefaultSecurityTests(SecurityTest):
|
class DefaultSecurityTests(SecurityTest):
|
||||||
|
|
||||||
def test_login_view(self):
|
def test_login_view(self):
|
||||||
@@ -100,6 +101,10 @@ class DefaultSecurityTests(SecurityTest):
|
|||||||
r = self._get("/admin_or_editor", follow_redirects=True)
|
r = self._get("/admin_or_editor", follow_redirects=True)
|
||||||
self.assertIn('Home Page', r.data)
|
self.assertIn('Home Page', r.data)
|
||||||
|
|
||||||
|
def test_unauthenticated_role_required(self):
|
||||||
|
r = self._get('/admin', follow_redirects=True)
|
||||||
|
self.assertIn('<input id="next"', r.data)
|
||||||
|
|
||||||
|
|
||||||
class ConfiguredSecurityTests(SecurityTest):
|
class ConfiguredSecurityTests(SecurityTest):
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import unittest
|
|||||||
import flask_security
|
import flask_security
|
||||||
from flask_security import RoleMixin, UserMixin, AnonymousUser
|
from flask_security import RoleMixin, UserMixin, AnonymousUser
|
||||||
|
|
||||||
|
|
||||||
class Role(RoleMixin):
|
class Role(RoleMixin):
|
||||||
def __init__(self, name, description=None):
|
def __init__(self, name, description=None):
|
||||||
self.name = name
|
self.name = name
|
||||||
@@ -24,6 +25,7 @@ editor = Role('editor')
|
|||||||
|
|
||||||
user = User('matt', 'matt@lp.com', [admin, editor])
|
user = User('matt', 'matt@lp.com', [admin, editor])
|
||||||
|
|
||||||
|
|
||||||
class SecurityEntityTests(unittest.TestCase):
|
class SecurityEntityTests(unittest.TestCase):
|
||||||
|
|
||||||
def test_role_mixin_equal(self):
|
def test_role_mixin_equal(self):
|
||||||
|
|||||||
Reference in New Issue
Block a user