mirror of
https://github.com/wassname/flask-security.git
synced 2026-08-07 11:22:21 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e37af8c01 | ||
|
|
245914cc9a | ||
|
|
201ee5b708 | ||
|
|
744ded7f1b | ||
|
|
5a7f4dff47 | ||
|
|
dd6ba0995d | ||
|
|
5697f7c953 | ||
|
|
144b22a3b9 | ||
|
|
3c57e169d1 | ||
|
|
d8f760092a | ||
|
|
d11ac8e977 | ||
|
|
0cdb43e167 | ||
|
|
6c44625945 | ||
|
|
5e59ee5c0c | ||
|
|
5f5b140db2 | ||
|
|
86f072628a | ||
|
|
3515eb0762 | ||
|
|
65eac687b7 | ||
|
|
e8d41ad4b5 |
@@ -1,6 +1,8 @@
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
*.pyc
|
*.pyc
|
||||||
*.egg
|
*.egg
|
||||||
|
*.egg-info
|
||||||
.project
|
.project
|
||||||
.pydevproject
|
.pydevproject
|
||||||
.settings
|
.settings
|
||||||
|
dist
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[submodule "docs/_themes"]
|
||||||
|
path = docs/_themes
|
||||||
|
url = git://github.com/mitsuhiko/flask-sphinx-themes.git
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
Flask-Security Changelog
|
||||||
|
========================
|
||||||
|
|
||||||
|
Here you can see the full list of changes between each Flask-Security release.
|
||||||
|
|
||||||
|
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
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Released March 12th, 2012
|
||||||
|
|
||||||
|
- Added configuration option `SECURITY_FLASH_MESSAGES` which can be set to a
|
||||||
|
boolean value to specify if Flask-Security should flash messages or not.
|
||||||
|
|
||||||
|
Version 1.1.0
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Initial release
|
||||||
@@ -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.
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
_build
|
||||||
+153
@@ -0,0 +1,153 @@
|
|||||||
|
# Makefile for Sphinx documentation
|
||||||
|
#
|
||||||
|
|
||||||
|
# You can set these variables from the command line.
|
||||||
|
SPHINXOPTS =
|
||||||
|
SPHINXBUILD = sphinx-build
|
||||||
|
PAPER =
|
||||||
|
BUILDDIR = _build
|
||||||
|
|
||||||
|
# Internal variables.
|
||||||
|
PAPEROPT_a4 = -D latex_paper_size=a4
|
||||||
|
PAPEROPT_letter = -D latex_paper_size=letter
|
||||||
|
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||||
|
# the i18n builder cannot share the environment and doctrees with the others
|
||||||
|
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||||
|
|
||||||
|
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Please use \`make <target>' where <target> is one of"
|
||||||
|
@echo " html to make standalone HTML files"
|
||||||
|
@echo " dirhtml to make HTML files named index.html in directories"
|
||||||
|
@echo " singlehtml to make a single large HTML file"
|
||||||
|
@echo " pickle to make pickle files"
|
||||||
|
@echo " json to make JSON files"
|
||||||
|
@echo " htmlhelp to make HTML files and a HTML help project"
|
||||||
|
@echo " qthelp to make HTML files and a qthelp project"
|
||||||
|
@echo " devhelp to make HTML files and a Devhelp project"
|
||||||
|
@echo " epub to make an epub"
|
||||||
|
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
||||||
|
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
||||||
|
@echo " text to make text files"
|
||||||
|
@echo " man to make manual pages"
|
||||||
|
@echo " texinfo to make Texinfo files"
|
||||||
|
@echo " info to make Texinfo files and run them through makeinfo"
|
||||||
|
@echo " gettext to make PO message catalogs"
|
||||||
|
@echo " changes to make an overview of all changed/added/deprecated items"
|
||||||
|
@echo " linkcheck to check all external links for integrity"
|
||||||
|
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
||||||
|
|
||||||
|
clean:
|
||||||
|
-rm -rf $(BUILDDIR)/*
|
||||||
|
|
||||||
|
html:
|
||||||
|
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||||
|
|
||||||
|
dirhtml:
|
||||||
|
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
||||||
|
|
||||||
|
singlehtml:
|
||||||
|
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
||||||
|
|
||||||
|
pickle:
|
||||||
|
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
||||||
|
@echo
|
||||||
|
@echo "Build finished; now you can process the pickle files."
|
||||||
|
|
||||||
|
json:
|
||||||
|
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
||||||
|
@echo
|
||||||
|
@echo "Build finished; now you can process the JSON files."
|
||||||
|
|
||||||
|
htmlhelp:
|
||||||
|
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
||||||
|
@echo
|
||||||
|
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
||||||
|
".hhp project file in $(BUILDDIR)/htmlhelp."
|
||||||
|
|
||||||
|
qthelp:
|
||||||
|
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
||||||
|
@echo
|
||||||
|
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
||||||
|
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
||||||
|
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-Security.qhcp"
|
||||||
|
@echo "To view the help file:"
|
||||||
|
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-Security.qhc"
|
||||||
|
|
||||||
|
devhelp:
|
||||||
|
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
||||||
|
@echo
|
||||||
|
@echo "Build finished."
|
||||||
|
@echo "To view the help file:"
|
||||||
|
@echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-Security"
|
||||||
|
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-Security"
|
||||||
|
@echo "# devhelp"
|
||||||
|
|
||||||
|
epub:
|
||||||
|
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
||||||
|
|
||||||
|
latex:
|
||||||
|
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||||
|
@echo
|
||||||
|
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
||||||
|
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
||||||
|
"(use \`make latexpdf' here to do that automatically)."
|
||||||
|
|
||||||
|
latexpdf:
|
||||||
|
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||||
|
@echo "Running LaTeX files through pdflatex..."
|
||||||
|
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
||||||
|
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||||
|
|
||||||
|
text:
|
||||||
|
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
||||||
|
|
||||||
|
man:
|
||||||
|
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
||||||
|
|
||||||
|
texinfo:
|
||||||
|
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
||||||
|
@echo "Run \`make' in that directory to run these through makeinfo" \
|
||||||
|
"(use \`make info' here to do that automatically)."
|
||||||
|
|
||||||
|
info:
|
||||||
|
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||||
|
@echo "Running Texinfo files through makeinfo..."
|
||||||
|
make -C $(BUILDDIR)/texinfo info
|
||||||
|
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
||||||
|
|
||||||
|
gettext:
|
||||||
|
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
||||||
|
@echo
|
||||||
|
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
||||||
|
|
||||||
|
changes:
|
||||||
|
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
||||||
|
@echo
|
||||||
|
@echo "The overview file is in $(BUILDDIR)/changes."
|
||||||
|
|
||||||
|
linkcheck:
|
||||||
|
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
||||||
|
@echo
|
||||||
|
@echo "Link check complete; look for any errors in the above output " \
|
||||||
|
"or in $(BUILDDIR)/linkcheck/output.txt."
|
||||||
|
|
||||||
|
doctest:
|
||||||
|
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
||||||
|
@echo "Testing of doctests in the sources finished, look at the " \
|
||||||
|
"results in $(BUILDDIR)/doctest/output.txt."
|
||||||
Submodule
+1
Submodule docs/_themes added at 0269f3d188
@@ -0,0 +1 @@
|
|||||||
|
.. include:: ../CHANGES
|
||||||
+311
@@ -0,0 +1,311 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Flask-Security documentation build configuration file, created by
|
||||||
|
# sphinx-quickstart on Mon Mar 12 15:35:21 2012.
|
||||||
|
#
|
||||||
|
# This file is execfile()d with the current directory set to its containing dir.
|
||||||
|
#
|
||||||
|
# Note that not all possible configuration values are present in this
|
||||||
|
# autogenerated file.
|
||||||
|
#
|
||||||
|
# All configuration values have a default; values that are commented out
|
||||||
|
# serve to show the default.
|
||||||
|
|
||||||
|
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'))
|
||||||
|
from flask_security import __version__
|
||||||
|
|
||||||
|
# -- General configuration -----------------------------------------------------
|
||||||
|
|
||||||
|
# If your documentation needs a minimal Sphinx version, state it here.
|
||||||
|
#needs_sphinx = '1.0'
|
||||||
|
|
||||||
|
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||||
|
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||||
|
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
|
||||||
|
|
||||||
|
# Add any paths that contain templates here, relative to this directory.
|
||||||
|
templates_path = ['_templates']
|
||||||
|
|
||||||
|
# The suffix of source filenames.
|
||||||
|
source_suffix = '.rst'
|
||||||
|
|
||||||
|
# The encoding of source files.
|
||||||
|
#source_encoding = 'utf-8-sig'
|
||||||
|
|
||||||
|
# The master toctree document.
|
||||||
|
master_doc = 'index'
|
||||||
|
|
||||||
|
# General information about the project.
|
||||||
|
project = u'Flask-Security'
|
||||||
|
copyright = u'2012, Matt Wright'
|
||||||
|
|
||||||
|
# The version info for the project you're documenting, acts as replacement for
|
||||||
|
# |version| and |release|, also used in various other places throughout the
|
||||||
|
# built documents.
|
||||||
|
#
|
||||||
|
# The short X.Y version.
|
||||||
|
version = __version__
|
||||||
|
# The full version, including alpha/beta/rc tags.
|
||||||
|
release = version
|
||||||
|
|
||||||
|
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||||
|
# for a list of supported languages.
|
||||||
|
#language = None
|
||||||
|
|
||||||
|
# There are two options for replacing |today|: either, you set today to some
|
||||||
|
# non-false value, then it is used:
|
||||||
|
#today = ''
|
||||||
|
# Else, today_fmt is used as the format for a strftime call.
|
||||||
|
#today_fmt = '%B %d, %Y'
|
||||||
|
|
||||||
|
# List of patterns, relative to source directory, that match files and
|
||||||
|
# directories to ignore when looking for source files.
|
||||||
|
exclude_patterns = ['_build']
|
||||||
|
|
||||||
|
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||||
|
#default_role = None
|
||||||
|
|
||||||
|
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||||
|
#add_function_parentheses = True
|
||||||
|
|
||||||
|
# If true, the current module name will be prepended to all description
|
||||||
|
# unit titles (such as .. function::).
|
||||||
|
#add_module_names = True
|
||||||
|
|
||||||
|
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||||
|
# output. They are ignored by default.
|
||||||
|
#show_authors = False
|
||||||
|
|
||||||
|
# The name of the Pygments (syntax highlighting) style to use.
|
||||||
|
pygments_style = 'sphinx'
|
||||||
|
|
||||||
|
# A list of ignored prefixes for module index sorting.
|
||||||
|
#modindex_common_prefix = []
|
||||||
|
|
||||||
|
|
||||||
|
# -- Options for HTML output ---------------------------------------------------
|
||||||
|
|
||||||
|
# The theme to use for HTML and HTML Help pages. Major themes that come with
|
||||||
|
# Sphinx are currently 'default' and 'sphinxdoc'.
|
||||||
|
html_theme = 'flask_small'
|
||||||
|
|
||||||
|
# Theme options are theme-specific and customize the look and feel of a theme
|
||||||
|
# further. For a list of options available for each theme, see the
|
||||||
|
# documentation.
|
||||||
|
html_theme_options = {
|
||||||
|
'github_fork': 'mattupstate/flask-security',
|
||||||
|
'index_logo': False
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add any paths that contain custom themes here, relative to this directory.
|
||||||
|
html_theme_path = ['_themes']
|
||||||
|
|
||||||
|
# The name for this set of Sphinx documents. If None, it defaults to
|
||||||
|
# "<project> v<release> documentation".
|
||||||
|
#html_title = None
|
||||||
|
|
||||||
|
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||||
|
#html_short_title = None
|
||||||
|
|
||||||
|
# The name of an image file (relative to this directory) to place at the top
|
||||||
|
# of the sidebar.
|
||||||
|
#html_logo = None
|
||||||
|
|
||||||
|
# The name of an image file (within the static path) to use as favicon of the
|
||||||
|
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||||
|
# pixels large.
|
||||||
|
#html_favicon = None
|
||||||
|
|
||||||
|
# Add any paths that contain custom static files (such as style sheets) here,
|
||||||
|
# relative to this directory. They are copied after the builtin static files,
|
||||||
|
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||||
|
html_static_path = ['_static']
|
||||||
|
|
||||||
|
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||||
|
# using the given strftime format.
|
||||||
|
#html_last_updated_fmt = '%b %d, %Y'
|
||||||
|
|
||||||
|
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||||
|
# typographically correct entities.
|
||||||
|
#html_use_smartypants = True
|
||||||
|
|
||||||
|
# Custom sidebar templates, maps document names to template names.
|
||||||
|
#html_sidebars = {}
|
||||||
|
|
||||||
|
# Additional templates that should be rendered to pages, maps page names to
|
||||||
|
# template names.
|
||||||
|
#html_additional_pages = {}
|
||||||
|
|
||||||
|
# If false, no module index is generated.
|
||||||
|
#html_domain_indices = True
|
||||||
|
|
||||||
|
# If false, no index is generated.
|
||||||
|
#html_use_index = True
|
||||||
|
|
||||||
|
# If true, the index is split into individual pages for each letter.
|
||||||
|
#html_split_index = False
|
||||||
|
|
||||||
|
# If true, links to the reST sources are added to the pages.
|
||||||
|
#html_show_sourcelink = True
|
||||||
|
|
||||||
|
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||||
|
#html_show_sphinx = True
|
||||||
|
|
||||||
|
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||||
|
#html_show_copyright = True
|
||||||
|
|
||||||
|
# If true, an OpenSearch description file will be output, and all pages will
|
||||||
|
# contain a <link> tag referring to it. The value of this option must be the
|
||||||
|
# base URL from which the finished HTML is served.
|
||||||
|
#html_use_opensearch = ''
|
||||||
|
|
||||||
|
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||||
|
#html_file_suffix = None
|
||||||
|
|
||||||
|
# Output file base name for HTML help builder.
|
||||||
|
htmlhelp_basename = 'Flask-Securitydoc'
|
||||||
|
|
||||||
|
|
||||||
|
# -- Options for LaTeX output --------------------------------------------------
|
||||||
|
|
||||||
|
latex_elements = {
|
||||||
|
# The paper size ('letterpaper' or 'a4paper').
|
||||||
|
#'papersize': 'letterpaper',
|
||||||
|
|
||||||
|
# The font size ('10pt', '11pt' or '12pt').
|
||||||
|
#'pointsize': '10pt',
|
||||||
|
|
||||||
|
# Additional stuff for the LaTeX preamble.
|
||||||
|
#'preamble': '',
|
||||||
|
}
|
||||||
|
|
||||||
|
# Grouping the document tree into LaTeX files. List of tuples
|
||||||
|
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||||
|
latex_documents = [
|
||||||
|
('index', 'Flask-Security.tex', u'Flask-Security Documentation',
|
||||||
|
u'Matt Wright', 'manual'),
|
||||||
|
]
|
||||||
|
|
||||||
|
# The name of an image file (relative to this directory) to place at the top of
|
||||||
|
# the title page.
|
||||||
|
#latex_logo = None
|
||||||
|
|
||||||
|
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||||
|
# not chapters.
|
||||||
|
#latex_use_parts = False
|
||||||
|
|
||||||
|
# If true, show page references after internal links.
|
||||||
|
#latex_show_pagerefs = False
|
||||||
|
|
||||||
|
# If true, show URL addresses after external links.
|
||||||
|
#latex_show_urls = False
|
||||||
|
|
||||||
|
# Documents to append as an appendix to all manuals.
|
||||||
|
#latex_appendices = []
|
||||||
|
|
||||||
|
# If false, no module index is generated.
|
||||||
|
#latex_domain_indices = True
|
||||||
|
|
||||||
|
|
||||||
|
# -- Options for manual page output --------------------------------------------
|
||||||
|
|
||||||
|
# One entry per manual page. List of tuples
|
||||||
|
# (source start file, name, description, authors, manual section).
|
||||||
|
man_pages = [
|
||||||
|
('index', 'flask-security', u'Flask-Security Documentation',
|
||||||
|
[u'Matt Wright'], 1)
|
||||||
|
]
|
||||||
|
|
||||||
|
# If true, show URL addresses after external links.
|
||||||
|
#man_show_urls = False
|
||||||
|
|
||||||
|
|
||||||
|
# -- Options for Texinfo output ------------------------------------------------
|
||||||
|
|
||||||
|
# Grouping the document tree into Texinfo files. List of tuples
|
||||||
|
# (source start file, target name, title, author,
|
||||||
|
# dir menu entry, description, category)
|
||||||
|
texinfo_documents = [
|
||||||
|
('index', 'Flask-Security', u'Flask-Security Documentation',
|
||||||
|
u'Matt Wright', 'Flask-Security', 'One line description of project.',
|
||||||
|
'Miscellaneous'),
|
||||||
|
]
|
||||||
|
|
||||||
|
# Documents to append as an appendix to all manuals.
|
||||||
|
#texinfo_appendices = []
|
||||||
|
|
||||||
|
# If false, no module index is generated.
|
||||||
|
#texinfo_domain_indices = True
|
||||||
|
|
||||||
|
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
||||||
|
#texinfo_show_urls = 'footnote'
|
||||||
|
|
||||||
|
|
||||||
|
# -- Options for Epub output ---------------------------------------------------
|
||||||
|
|
||||||
|
# Bibliographic Dublin Core info.
|
||||||
|
epub_title = u'Flask-Security'
|
||||||
|
epub_author = u'Matt Wright'
|
||||||
|
epub_publisher = u'Matt Wright'
|
||||||
|
epub_copyright = u'2012, Matt Wright'
|
||||||
|
|
||||||
|
# The language of the text. It defaults to the language option
|
||||||
|
# or en if the language is not set.
|
||||||
|
#epub_language = ''
|
||||||
|
|
||||||
|
# The scheme of the identifier. Typical schemes are ISBN or URL.
|
||||||
|
#epub_scheme = ''
|
||||||
|
|
||||||
|
# The unique identifier of the text. This can be a ISBN number
|
||||||
|
# or the project homepage.
|
||||||
|
#epub_identifier = ''
|
||||||
|
|
||||||
|
# A unique identification for the text.
|
||||||
|
#epub_uid = ''
|
||||||
|
|
||||||
|
# A tuple containing the cover image and cover page html template filenames.
|
||||||
|
#epub_cover = ()
|
||||||
|
|
||||||
|
# HTML files that should be inserted before the pages created by sphinx.
|
||||||
|
# The format is a list of tuples containing the path and title.
|
||||||
|
#epub_pre_files = []
|
||||||
|
|
||||||
|
# HTML files shat should be inserted after the pages created by sphinx.
|
||||||
|
# The format is a list of tuples containing the path and title.
|
||||||
|
#epub_post_files = []
|
||||||
|
|
||||||
|
# A list of files that should not be packed into the epub file.
|
||||||
|
#epub_exclude_files = []
|
||||||
|
|
||||||
|
# The depth of the table of contents in toc.ncx.
|
||||||
|
#epub_tocdepth = 3
|
||||||
|
|
||||||
|
# Allow duplicate toc entries.
|
||||||
|
#epub_tocdup = True
|
||||||
|
|
||||||
|
|
||||||
|
# Example configuration for intersphinx: refer to the Python standard library.
|
||||||
|
intersphinx_mapping = {'http://docs.python.org/': None}
|
||||||
|
|
||||||
|
pygments_style = 'flask_theme_support.FlaskyStyle'
|
||||||
|
|
||||||
|
# fall back if theme is not there
|
||||||
|
try:
|
||||||
|
__import__('flask_theme_support')
|
||||||
|
except ImportError, e:
|
||||||
|
print '-' * 74
|
||||||
|
print 'Warning: Flask themes unavailable. Building with default theme'
|
||||||
|
print 'If you want the Flask themes, run this command and build again:'
|
||||||
|
print
|
||||||
|
print ' git submodule update --init'
|
||||||
|
print '-' * 74
|
||||||
|
|
||||||
|
pygments_style = 'tango'
|
||||||
|
html_theme = 'default'
|
||||||
|
html_theme_options = {}
|
||||||
+347
@@ -0,0 +1,347 @@
|
|||||||
|
.. Flask-Security documentation master file, created by
|
||||||
|
sphinx-quickstart on Mon Mar 12 15:35:21 2012.
|
||||||
|
You can adapt this file completely to your liking, but it should at least
|
||||||
|
contain the root `toctree` directive.
|
||||||
|
|
||||||
|
Flask-Security
|
||||||
|
==============
|
||||||
|
|
||||||
|
.. module:: 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 on your own. Additionally, you may need to install an encryption
|
||||||
|
library such as `py-bcrypt <http://www.mindrot.org/projects/py-bcrypt/>`_ (if
|
||||||
|
you plan to use bcrypt) for your desired encryption method.
|
||||||
|
|
||||||
|
|
||||||
|
Contents
|
||||||
|
=========
|
||||||
|
* :ref:`overview`
|
||||||
|
* :ref:`installation`
|
||||||
|
* :ref:`getting-started`
|
||||||
|
* :ref:`additional-user-fields`
|
||||||
|
* :ref:`flask-script-commands`
|
||||||
|
* :ref:`api`
|
||||||
|
* :doc:`Changelog </changelog>`
|
||||||
|
|
||||||
|
|
||||||
|
.. _overview:
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
.. _installation:
|
||||||
|
|
||||||
|
Installation
|
||||||
|
============
|
||||||
|
|
||||||
|
First, install Flask-Security::
|
||||||
|
|
||||||
|
$ mkvirtualenv app-name
|
||||||
|
$ pip install Flask-Security
|
||||||
|
|
||||||
|
Then install your datastore requirement.
|
||||||
|
|
||||||
|
**SQLAlchemy**::
|
||||||
|
|
||||||
|
$ pip install Flask-SQLAlchemy
|
||||||
|
|
||||||
|
**MongoEngine**::
|
||||||
|
|
||||||
|
$ pip install https://github.com/sbook/flask-mongoengine/tarball/master
|
||||||
|
|
||||||
|
|
||||||
|
.. _getting-started:
|
||||||
|
|
||||||
|
Getting Started
|
||||||
|
===============
|
||||||
|
|
||||||
|
The following code samples will illustrate how to get started using SQLAlchemy.
|
||||||
|
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
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config['SECRET_KEY'] = 'secret'
|
||||||
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
|
||||||
|
|
||||||
|
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::
|
||||||
|
|
||||||
|
@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'])
|
||||||
|
|
||||||
|
Next you'll want to setup your login screen. Setup your view::
|
||||||
|
|
||||||
|
@app.route("/login")
|
||||||
|
def login():
|
||||||
|
return render_template('login.html', form=LoginForm())
|
||||||
|
|
||||||
|
And corresponding template::
|
||||||
|
|
||||||
|
<form action="{{ url_for('auth.authenticate') }}" method="POST">
|
||||||
|
{{ form.hidden_tag() }}
|
||||||
|
{{ form.username.label }} {{ form.username }}<br/>
|
||||||
|
{{ form.password.label }} {{ form.password }}<br/>
|
||||||
|
{{ form.remember.label }} {{ form.remember }}<br/>
|
||||||
|
{{ form.submit }}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
By default, Flask-Security will redirect a user to `/profile` after logging in.
|
||||||
|
You can set this page up yourself or set the `SECURITY_POST_LOGIN` config
|
||||||
|
value to change this behavior. Regardless, setup a protected view as such::
|
||||||
|
|
||||||
|
@app.route('/profile')
|
||||||
|
@login_required
|
||||||
|
def profile():
|
||||||
|
return render_template('profile.html')
|
||||||
|
|
||||||
|
Now you have an application with basic authentication. If you run the local
|
||||||
|
development server you can visit `http://localhost:5000/login <http://localhost:5000/login>`_
|
||||||
|
to login.
|
||||||
|
|
||||||
|
The last thing you'll want to do is add a logout link to your templates. This
|
||||||
|
can be achieved with::
|
||||||
|
|
||||||
|
<a href="{{ url_for('auth.logout') }}">Logout</a>
|
||||||
|
|
||||||
|
Now, for instance, say you want to protect an admin area to users that are
|
||||||
|
administrators. You can use the `roles_accepted` decorator to prevent access.
|
||||||
|
The corresponding view would look like such::
|
||||||
|
|
||||||
|
@app.route('/admin')
|
||||||
|
@roles_accepted('admin')
|
||||||
|
def admin():
|
||||||
|
return render_template('admin/index.html')
|
||||||
|
|
||||||
|
And lastly, maybe you only want to show something in a template if a user has a
|
||||||
|
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:
|
||||||
|
|
||||||
|
Configuration Values
|
||||||
|
====================
|
||||||
|
|
||||||
|
* :attr:`SECURITY_URL_PREFIX`: Specifies the URL prefix for the Security
|
||||||
|
blueprint
|
||||||
|
* :attr:`SECURITY_AUTH_PROVIDER`: Specifies the class to use as the
|
||||||
|
authentication provider. Such as `flask.ext.security.AuthenticationProvider`
|
||||||
|
* :attr:`SECURITY_PASSWORD_HASH`: Specifies the encryption method to use. e.g.:
|
||||||
|
plaintext, bcrypt, etc
|
||||||
|
* :attr:`SECURITY_USER_DATASTORE`: Specifies the property name to use for the
|
||||||
|
user datastore on the application instance
|
||||||
|
* :attr:`SECURITY_LOGIN_FORM`: Specifies the form class to use when processing
|
||||||
|
an authentication request
|
||||||
|
* :attr:`SECURITY_AUTH_URL`: Specifies the URL to to handle authentication
|
||||||
|
* :attr:`SECURITY_LOGOUT_URL`: Specifies the URL to process a logout request
|
||||||
|
* :attr:`SECURITY_LOGIN_VIEW`: Specifies the URL to redirect to when
|
||||||
|
authentication is required
|
||||||
|
* :attr:`SECURITY_POST_LOGIN`: Specifies the URL to redirect to after a user is
|
||||||
|
authenticated
|
||||||
|
* :attr:`SECURITY_POST_LOGOUT`: Specifies the URL to redirect to after a user
|
||||||
|
logs out
|
||||||
|
* :attr:`SECURITY_FLASH_MESSAGES`: Specifies wether or not to flash messages
|
||||||
|
during authentication request
|
||||||
|
|
||||||
|
|
||||||
|
.. _api:
|
||||||
|
|
||||||
|
API
|
||||||
|
===
|
||||||
|
|
||||||
|
.. autoclass:: flask_security.Security
|
||||||
|
:members:
|
||||||
|
|
||||||
|
.. data:: flask_security.current_user
|
||||||
|
|
||||||
|
A proxy for the current user.
|
||||||
|
|
||||||
|
|
||||||
|
Protecting Views
|
||||||
|
----------------
|
||||||
|
.. autofunction:: flask_security.login_required
|
||||||
|
|
||||||
|
.. autofunction:: flask_security.roles_required
|
||||||
|
|
||||||
|
.. autofunction:: flask_security.roles_accepted
|
||||||
|
|
||||||
|
|
||||||
|
User Object Helpers
|
||||||
|
-------------------
|
||||||
|
.. autoclass:: flask_security.UserMixin
|
||||||
|
:members:
|
||||||
|
|
||||||
|
.. autoclass:: flask_security.RoleMixin
|
||||||
|
:members:
|
||||||
|
|
||||||
|
.. autoclass:: flask_security.AnonymousUser
|
||||||
|
:members:
|
||||||
|
|
||||||
|
|
||||||
|
Datastores
|
||||||
|
----------
|
||||||
|
.. autoclass:: flask_security.datastore.UserDatastore
|
||||||
|
:members:
|
||||||
|
|
||||||
|
.. autoclass:: flask_security.datastore.sqlalchemy.SQLAlchemyUserDatastore
|
||||||
|
:members:
|
||||||
|
:inherited-members:
|
||||||
|
|
||||||
|
.. autoclass:: flask_security.datastore.mongoengine.MongoEngineUserDatastore
|
||||||
|
:members:
|
||||||
|
:inherited-members:
|
||||||
|
|
||||||
|
|
||||||
|
Models
|
||||||
|
------
|
||||||
|
.. autoclass:: flask_security.User
|
||||||
|
|
||||||
|
.. attribute:: id
|
||||||
|
|
||||||
|
User ID
|
||||||
|
|
||||||
|
.. attribute:: username
|
||||||
|
|
||||||
|
Username
|
||||||
|
|
||||||
|
.. attribute:: email
|
||||||
|
|
||||||
|
Email address
|
||||||
|
|
||||||
|
.. attribute:: password
|
||||||
|
|
||||||
|
Password
|
||||||
|
|
||||||
|
.. attribute:: active
|
||||||
|
|
||||||
|
Active state
|
||||||
|
|
||||||
|
.. attribute:: roles
|
||||||
|
|
||||||
|
User roles
|
||||||
|
|
||||||
|
.. attribute:: created_at
|
||||||
|
|
||||||
|
Created date
|
||||||
|
|
||||||
|
.. attribute:: modified_at
|
||||||
|
|
||||||
|
Modified date
|
||||||
|
|
||||||
|
|
||||||
|
.. autoclass:: flask_security.Role
|
||||||
|
|
||||||
|
.. attribute:: id
|
||||||
|
|
||||||
|
Role ID
|
||||||
|
|
||||||
|
.. attribute:: name
|
||||||
|
|
||||||
|
Role name
|
||||||
|
|
||||||
|
.. attribute:: description
|
||||||
|
|
||||||
|
Role description
|
||||||
|
|
||||||
|
|
||||||
|
Exceptions
|
||||||
|
----------
|
||||||
|
.. autoexception:: flask_security.BadCredentialsError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.AuthenticationError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.UserNotFoundError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.RoleNotFoundError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.UserIdNotFoundError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.UserDatastoreError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.UserCreationError
|
||||||
|
|
||||||
|
.. autoexception:: flask_security.RoleCreationError
|
||||||
|
|
||||||
|
|
||||||
|
Signals
|
||||||
|
-------
|
||||||
|
See the documentation for the signals provided by the Flask-Login and
|
||||||
|
Flask-Principal extensions. Flask-Security does not provide any additional
|
||||||
|
signals.
|
||||||
|
|
||||||
|
|
||||||
|
Changelog
|
||||||
|
=========
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 2
|
||||||
|
|
||||||
|
changelog
|
||||||
+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():
|
||||||
|
|||||||
+110
-33
@@ -1,15 +1,16 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
flask.ext.security
|
flask.ext.security
|
||||||
~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
Flask-Security is a Flask extension module that aims to add quick and
|
Flask-Security is a Flask extension that aims to add quick and simple
|
||||||
simple security via Flask-Login and Flask-Principal.
|
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.
|
||||||
"""
|
"""
|
||||||
from __future__ import absolute_import
|
|
||||||
|
__version__ = '1.2.1'
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
@@ -34,8 +35,11 @@ from passlib.context import CryptContext
|
|||||||
from werkzeug.utils import import_string
|
from werkzeug.utils import import_string
|
||||||
from werkzeug.local import LocalProxy
|
from werkzeug.local import LocalProxy
|
||||||
|
|
||||||
|
class User(object):
|
||||||
|
"""User model"""
|
||||||
|
|
||||||
User, Role = None, None
|
class Role(object):
|
||||||
|
"""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'
|
||||||
@@ -47,6 +51,7 @@ 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'
|
||||||
|
|
||||||
DEBUG_LOGIN = 'User %s logged in. Redirecting to: %s'
|
DEBUG_LOGIN = 'User %s logged in. Redirecting to: %s'
|
||||||
ERROR_LOGIN = 'Unsuccessful authentication attempt: %s. Redirecting to: %s'
|
ERROR_LOGIN = 'Unsuccessful authentication attempt: %s. Redirecting to: %s'
|
||||||
@@ -54,8 +59,10 @@ DEBUG_LOGOUT = 'User logged out, redirecting to: %s'
|
|||||||
FLASH_INACTIVE = 'Inactive user'
|
FLASH_INACTIVE = 'Inactive user'
|
||||||
FLASH_PERMISSIONS = 'You do not have permission to view this resource.'
|
FLASH_PERMISSIONS = 'You do not have permission to view this resource.'
|
||||||
|
|
||||||
|
#: Default Flask-Security configuration
|
||||||
default_config = {
|
default_config = {
|
||||||
URL_PREFIX_KEY: None,
|
URL_PREFIX_KEY: None,
|
||||||
|
FLASH_MESSAGES_KEY: True,
|
||||||
PASSWORD_HASH_KEY: 'plaintext',
|
PASSWORD_HASH_KEY: 'plaintext',
|
||||||
USER_DATASTORE_KEY: 'user_datastore',
|
USER_DATASTORE_KEY: 'user_datastore',
|
||||||
AUTH_PROVIDER_KEY: 'flask.ext.security.AuthenticationProvider',
|
AUTH_PROVIDER_KEY: 'flask.ext.security.AuthenticationProvider',
|
||||||
@@ -94,15 +101,15 @@ class UserIdNotFoundError(Exception):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
class UserDatastoreError(Exception):
|
class UserDatastoreError(Exception):
|
||||||
"""Raise when a user datastore experiences an unexpected error
|
"""Raised when a user datastore experiences an unexpected error
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class UserCreationError(Exception):
|
class UserCreationError(Exception):
|
||||||
"""Raise when an error occurs when creating a user
|
"""Raised when an error occurs when creating a user
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class RoleCreationError(Exception):
|
class RoleCreationError(Exception):
|
||||||
"""Raise when an error occurs when creating a role
|
"""Raised when an error occurs when creating a role
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -118,11 +125,24 @@ login_manager = LocalProxy(lambda: current_app.login_manager)
|
|||||||
#: Password encyption context
|
#: Password encyption context
|
||||||
pwd_context = LocalProxy(lambda: current_app.pwd_context)
|
pwd_context = LocalProxy(lambda: current_app.pwd_context)
|
||||||
|
|
||||||
# User service
|
#: 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
|
||||||
|
roles. Example::
|
||||||
|
|
||||||
|
@app.route('/dashboard')
|
||||||
|
@roles_required('admin', 'editor')
|
||||||
|
def dashboard():
|
||||||
|
return 'Dashboard'
|
||||||
|
|
||||||
|
The current user must have both the `admin` role and `editor` role in order
|
||||||
|
to view the page.
|
||||||
|
|
||||||
|
:param args: The required roles.
|
||||||
|
"""
|
||||||
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):
|
||||||
@@ -137,13 +157,26 @@ def roles_required(*args):
|
|||||||
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])
|
||||||
|
|
||||||
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
|
||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
def roles_accepted(*args):
|
def roles_accepted(*args):
|
||||||
|
"""View decorator which specifies that a user must have at least one of the
|
||||||
|
specified roles. Example::
|
||||||
|
|
||||||
|
@app.route('/create_post')
|
||||||
|
@roles_accepted('editor', 'author')
|
||||||
|
def create_post():
|
||||||
|
return 'Create Post'
|
||||||
|
|
||||||
|
The current user must have either the `editor` role or `author` role in
|
||||||
|
order to view the page.
|
||||||
|
|
||||||
|
: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):
|
||||||
@@ -159,13 +192,14 @@ def roles_accepted(*args):
|
|||||||
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])
|
||||||
|
|
||||||
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
|
||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
class RoleMixin(object):
|
class RoleMixin(object):
|
||||||
|
"""Mixin for `Role` model definitions"""
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return self.name == other.name
|
return self.name == other.name
|
||||||
|
|
||||||
@@ -177,10 +211,16 @@ class RoleMixin(object):
|
|||||||
|
|
||||||
|
|
||||||
class UserMixin(BaseUserMixin):
|
class UserMixin(BaseUserMixin):
|
||||||
|
"""Mixin for `User` model definitions"""
|
||||||
|
|
||||||
def is_active(self):
|
def is_active(self):
|
||||||
|
"""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.
|
||||||
|
|
||||||
|
:param role: A role name or `Role` instance"""
|
||||||
if not isinstance(role, Role):
|
if not isinstance(role, Role):
|
||||||
role = Role(name=role)
|
role = Role(name=role)
|
||||||
return role in self.roles
|
return role in self.roles
|
||||||
@@ -196,21 +236,29 @@ class AnonymousUser(AnonymousUserBase):
|
|||||||
self.roles = [] # TODO: Make this immutable?
|
self.roles = [] # TODO: Make this immutable?
|
||||||
|
|
||||||
def has_role(self, *args):
|
def has_role(self, *args):
|
||||||
|
"""Returns `False`"""
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
class Security(object):
|
class Security(object):
|
||||||
|
"""The :class:`Security` class initializes the Flask-Security extension.
|
||||||
|
|
||||||
|
:param app: The application.
|
||||||
|
:param datastore: An instance of a user datastore.
|
||||||
|
"""
|
||||||
def __init__(self, app=None, datastore=None):
|
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):
|
||||||
"""Initialize the application
|
"""Initializes the Flask-Security extension for the specified
|
||||||
|
application and datastore implentation.
|
||||||
:param app: An instance of an application
|
|
||||||
:param datastore: An instance of a datastore for your users
|
:param app: The application.
|
||||||
|
:param datastore: An instance of a user datastore.
|
||||||
"""
|
"""
|
||||||
if app is None or datastore is None: return
|
if app is None or datastore is None: return
|
||||||
|
|
||||||
|
# TODO: change blueprint name
|
||||||
blueprint = Blueprint('auth', __name__)
|
blueprint = Blueprint('auth', __name__)
|
||||||
|
|
||||||
configured = {}
|
configured = {}
|
||||||
@@ -220,9 +268,6 @@ class Security(object):
|
|||||||
|
|
||||||
app.config.update(configured)
|
app.config.update(configured)
|
||||||
config = app.config
|
config = app.config
|
||||||
#config = default_config.copy()
|
|
||||||
#config.update(app.config.get(AUTH_CONFIG_KEY, {}))
|
|
||||||
#app.config[AUTH_CONFIG_KEY] = config
|
|
||||||
|
|
||||||
# setup the login manager extension
|
# setup the login manager extension
|
||||||
login_manager = LoginManager()
|
login_manager = LoginManager()
|
||||||
@@ -279,7 +324,7 @@ class Security(object):
|
|||||||
|
|
||||||
except BadCredentialsError, e:
|
except BadCredentialsError, e:
|
||||||
message = '%s' % e
|
message = '%s' % e
|
||||||
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)
|
||||||
@@ -301,7 +346,7 @@ class Security(object):
|
|||||||
|
|
||||||
|
|
||||||
class LoginForm(Form):
|
class LoginForm(Form):
|
||||||
"""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")])
|
||||||
@@ -317,16 +362,27 @@ class LoginForm(Form):
|
|||||||
|
|
||||||
|
|
||||||
class AuthenticationProvider(object):
|
class AuthenticationProvider(object):
|
||||||
"""Default authentication provider"""
|
"""The default authentication provider implementation.
|
||||||
|
|
||||||
|
:param login_form_class: The login form class to use when authenticating a
|
||||||
|
user
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, login_form_class=None):
|
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.
|
||||||
|
|
||||||
|
: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):
|
||||||
# first some basic validation
|
"""Processes an authentication request and returns a user instance if
|
||||||
|
authentication is successful.
|
||||||
|
|
||||||
|
:param form: An instance of a populated login form
|
||||||
|
"""
|
||||||
if not form.validate():
|
if not form.validate():
|
||||||
if form.username.errors:
|
if form.username.errors:
|
||||||
raise BadCredentialsError(form.username.errors[0])
|
raise BadCredentialsError(form.username.errors[0])
|
||||||
@@ -336,6 +392,13 @@ class AuthenticationProvider(object):
|
|||||||
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
|
||||||
|
authentication fails an appropriate error is raised
|
||||||
|
|
||||||
|
:param user_identifier: The user's identifier, either an email address
|
||||||
|
or username
|
||||||
|
:param password: The user's unencrypted password
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
user = user_datastore.find_user(user_identifier)
|
user = user_datastore.find_user(user_identifier)
|
||||||
except AttributeError, e:
|
except AttributeError, e:
|
||||||
@@ -355,11 +418,19 @@ class AuthenticationProvider(object):
|
|||||||
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.
|
||||||
|
|
||||||
|
:param msg: An authentication error message"""
|
||||||
logger.error(msg)
|
logger.error(msg)
|
||||||
raise AuthenticationError(msg)
|
raise AuthenticationError(msg)
|
||||||
|
|
||||||
|
def do_flash(message, category):
|
||||||
|
if current_app.config[FLASH_MESSAGES_KEY]:
|
||||||
|
flash(message, category)
|
||||||
|
|
||||||
|
|
||||||
def get_class_by_name(clazz):
|
def get_class_by_name(clazz):
|
||||||
|
"""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 )
|
||||||
@@ -368,6 +439,7 @@ def get_class_by_name(clazz):
|
|||||||
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."""
|
||||||
try:
|
try:
|
||||||
return get_class_by_name(config[key])
|
return get_class_by_name(config[key])
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
@@ -375,22 +447,27 @@ 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(value):
|
def get_url(endpoint_or_url):
|
||||||
# try building the url or assume its a url already
|
"""Returns a URL if a valid endpoint is found. Otherwise, returns the
|
||||||
try: return url_for(value)
|
provided value."""
|
||||||
except: return value
|
try:
|
||||||
|
return url_for(endpoint_or_url)
|
||||||
|
except:
|
||||||
|
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"""
|
||||||
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):
|
||||||
# Look in the session first, and if not there go to the config, and
|
"""Returns the URL to redirect to after a user logs in successfully"""
|
||||||
# if its not there either just go to the root url
|
result = (get_url(session.pop(key.lower(), None)) or
|
||||||
result = (get_url(session.get(key.lower(), None)) or
|
get_url(current_app.config[key.upper()] or None) or '/')
|
||||||
get_url(current_app.config[key] or None) or '/')
|
|
||||||
# Try and delete the session value if it was used
|
try:
|
||||||
try: del session[key.lower()]
|
del session[key.lower()]
|
||||||
except: pass
|
except:
|
||||||
|
pass
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -1,10 +1,37 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
flask.ext.security.datastore
|
||||||
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
This module contains an abstracted user datastore.
|
||||||
|
|
||||||
|
:copyright: (c) 2012 by Matt Wright.
|
||||||
|
:license: MIT, see LICENSE for more details.
|
||||||
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
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 and implement
|
"""Abstracted user datastore. Always extend this class and implement the
|
||||||
missing methods"""
|
:attr:`get_models`, :attr:`_save_model`, :attr:`_do_with_id`,
|
||||||
|
:attr:`_do_find_user`, and :attr:`_do_find_role` methods.
|
||||||
|
|
||||||
|
:param db: An instance of a configured databse manager from a Flask
|
||||||
|
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
|
||||||
|
implementation"""
|
||||||
|
raise NotImplementedError(
|
||||||
|
"User datastore does not implement get_models method")
|
||||||
|
|
||||||
def _save_model(self, model, **kwargs):
|
def _save_model(self, model, **kwargs):
|
||||||
raise NotImplementedError(
|
raise NotImplementedError(
|
||||||
@@ -96,36 +123,79 @@ class UserDatastore(object):
|
|||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
def with_id(self, id):
|
def with_id(self, id):
|
||||||
|
"""Returns a user with the specified 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.
|
||||||
|
|
||||||
|
: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.
|
||||||
|
|
||||||
|
: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, commit=True, **kwargs):
|
def create_role(self, **kwargs):
|
||||||
|
"""Creates and returns a new role.
|
||||||
|
|
||||||
|
:param name: Role name
|
||||||
|
:param description: Role description
|
||||||
|
"""
|
||||||
role = security.Role(**self._prepare_create_role_args(kwargs))
|
role = security.Role(**self._prepare_create_role_args(kwargs))
|
||||||
return self._save_model(role)
|
return self._save_model(role)
|
||||||
|
|
||||||
def create_user(self, commit=True, **kwargs):
|
def create_user(self, **kwargs):
|
||||||
|
"""Creates and returns a new user.
|
||||||
|
|
||||||
|
:param username: Username
|
||||||
|
:param email: Email address
|
||||||
|
:param password: Unencrypted password
|
||||||
|
:param active: The optional active state
|
||||||
|
"""
|
||||||
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
|
||||||
|
the modified user.
|
||||||
|
|
||||||
|
:param user: A User instance or a user identifier
|
||||||
|
:param role: A Role instance or a role name
|
||||||
|
"""
|
||||||
return self._save_model(self._do_add_role(user, role))
|
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
|
||||||
|
modified user.
|
||||||
|
|
||||||
|
:param user: A User instance or a user identifier
|
||||||
|
:param role: A Role instance or a role name
|
||||||
|
"""
|
||||||
return self._save_model(self._do_remove_role(user, role))
|
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.
|
||||||
|
|
||||||
|
: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.
|
||||||
|
|
||||||
|
: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))
|
||||||
@@ -1,21 +1,49 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
flask.ext.security.datastore.mongoengine
|
||||||
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
This module contains a Flask-Security MongoEngine datastore implementation
|
||||||
|
|
||||||
|
:copyright: (c) 2012 by Matt Wright.
|
||||||
|
:license: MIT, see LICENSE for more details.
|
||||||
|
"""
|
||||||
|
|
||||||
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):
|
||||||
"""MongoEngine datastore"""
|
"""A MongoEngine datastore implementation for Flask-Security.
|
||||||
|
Example usage::
|
||||||
|
|
||||||
def __init__(self, db):
|
from flask import Flask
|
||||||
self.db = db
|
from flask.ext.mongoengine import MongoEngine
|
||||||
|
from flask.ext.security import Security
|
||||||
|
from flask.ext.security.datastore.mongoengine import MongoEngineUserDatastore
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config['SECRET_KEY'] = 'secret'
|
||||||
|
app.config['MONGODB_DB'] = 'flask_security_example'
|
||||||
|
app.config['MONGODB_HOST'] = 'localhost'
|
||||||
|
app.config['MONGODB_PORT'] = 27017
|
||||||
|
|
||||||
|
db = MongoEngine(app)
|
||||||
|
Security(app, MongoEngineUserDatastore(db))
|
||||||
|
"""
|
||||||
|
|
||||||
def get_models(self):
|
def get_models(self):
|
||||||
db = self.db
|
db = self.db
|
||||||
|
|
||||||
class Role(db.Document, RoleMixin):
|
class Role(db.Document, RoleMixin):
|
||||||
|
"""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"""
|
||||||
|
|
||||||
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)
|
||||||
|
|||||||
@@ -1,13 +1,35 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
flask.ext.security.datastore.sqlalchemy
|
||||||
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
This module contains a Flask-Security SQLAlchemy datastore implementation
|
||||||
|
|
||||||
|
:copyright: (c) 2012 by Matt Wright.
|
||||||
|
:license: MIT, see LICENSE for more details.
|
||||||
|
"""
|
||||||
|
|
||||||
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):
|
||||||
"""SQLAlchemy datastore"""
|
"""A SQLAlchemy datastore implementation for Flask-Security.
|
||||||
|
Example usage::
|
||||||
|
|
||||||
def __init__(self, db):
|
from flask import Flask
|
||||||
self.db = db
|
from flask.ext.security import Security
|
||||||
|
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
|
||||||
|
from flask.ext.sqlalchemy import SQLAlchemy
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config['SECRET_KEY'] = 'secret'
|
||||||
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/flask_security_example.sqlite'
|
||||||
|
|
||||||
|
db = SQLAlchemy(app)
|
||||||
|
Security(app, SQLAlchemyUserDatastore(db))
|
||||||
|
"""
|
||||||
|
|
||||||
def get_models(self):
|
def get_models(self):
|
||||||
db = self.db
|
db = self.db
|
||||||
|
|
||||||
@@ -16,6 +38,8 @@ class SQLAlchemyUserDatastore(UserDatastore):
|
|||||||
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"""
|
||||||
|
|
||||||
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))
|
||||||
@@ -24,7 +48,9 @@ class SQLAlchemyUserDatastore(UserDatastore):
|
|||||||
self.name = name
|
self.name = name
|
||||||
self.description = description
|
self.description = description
|
||||||
|
|
||||||
class User(db.Model, UserMixin):
|
class User(db.Model, UserMixin, self.user_account_mixin):
|
||||||
|
"""SQLAlchemy User model"""
|
||||||
|
|
||||||
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)
|
||||||
|
|||||||
@@ -1,3 +1,14 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
flask.ext.security.script
|
||||||
|
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
This module contains commands for use with the Flask-Script extension
|
||||||
|
|
||||||
|
:copyright: (c) 2012 by Matt Wright.
|
||||||
|
:license: MIT, see LICENSE for more details.
|
||||||
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
from flask.ext.script import Command, Option
|
from flask.ext.script import Command, Option
|
||||||
@@ -35,6 +46,19 @@ class CreateUserCommand(Command):
|
|||||||
pprint(kwargs)
|
pprint(kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class CreateRoleCommand(Command):
|
||||||
|
"""Create a role"""
|
||||||
|
|
||||||
|
option_list = (
|
||||||
|
Option('-n', '--name', dest='name', default=None),
|
||||||
|
Option('-d', '--desc', dest='description', default=None),
|
||||||
|
)
|
||||||
|
|
||||||
|
def run(self, **kwargs):
|
||||||
|
role = user_datastore.create_role(**kwargs)
|
||||||
|
print 'Role "%(name)s" created successfully.' % kwargs
|
||||||
|
|
||||||
|
|
||||||
class _RoleCommand(Command):
|
class _RoleCommand(Command):
|
||||||
option_list = (
|
option_list = (
|
||||||
Option('-u', '--user', dest='user_identifier'),
|
Option('-u', '--user', dest='user_identifier'),
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
Flask-Security
|
Flask-Security
|
||||||
--------------
|
--------------
|
||||||
|
|
||||||
Simple security for Flask apps
|
Flask-Security is a Flask extension that aims to add quick and simple security
|
||||||
|
via Flask-Login, Flask-Principal, Flask-WTF, and passlib.
|
||||||
|
|
||||||
Links
|
Links
|
||||||
`````
|
`````
|
||||||
@@ -11,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 flask_security import __version__
|
||||||
from setuptools import setup
|
from setuptools import setup
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name='Flask-Security',
|
name='Flask-Security',
|
||||||
version='1.1.0',
|
version=__version__,
|
||||||
url='https://github.com/mattupstate/flask-security',
|
url='https://github.com/mattupstate/flask-security',
|
||||||
license='MIT',
|
license='MIT',
|
||||||
author='Matthew Wright',
|
author='Matthew Wright',
|
||||||
|
|||||||
Reference in New Issue
Block a user