Created
July 1, 2014 15:35
-
-
Save chris-allan/ce7e594b483ee060deb8 to your computer and use it in GitHub Desktop.
Basic Flask-Security server with principals enabled
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask.ext.mongoengine import MongoEngine | |
from flask.ext.security import Security, MongoEngineUserDatastore, \ | |
UserMixin, RoleMixin, login_required | |
from flask.ext.principal import Principal | |
# Create app | |
app = Flask(__name__) | |
app.config['DEBUG'] = True | |
app.config['SECRET_KEY'] = 'super-secret' | |
# Load the Flask-Principal extension | |
principals = Principal(app) | |
# MongoDB Config | |
app.config["MONGODB_HOST"] = "mongodb://localhost:27017/flask_security" | |
app.config["MONGODB_DB"] = True | |
# Create database connection object | |
db = MongoEngine(app) | |
class Role(db.Document, RoleMixin): | |
name = db.StringField(max_length=80, unique=True) | |
description = db.StringField(max_length=255) | |
class User(db.Document, UserMixin): | |
email = db.StringField(max_length=255) | |
password = db.StringField(max_length=255) | |
active = db.BooleanField(default=True) | |
confirmed_at = db.DateTimeField() | |
roles = db.ListField(db.ReferenceField(Role), default=[]) | |
# Setup Flask-Security | |
user_datastore = MongoEngineUserDatastore(db, User, Role) | |
security = Security(app, user_datastore) | |
# Create a user to test with | |
@app.before_first_request | |
def create_user(): | |
test_role = user_datastore.find_or_create_role('test') | |
user_datastore.create_user( | |
email='[email protected]', password='abc123', roles=[test_role] | |
) | |
# Views | |
@app.route('/') | |
@login_required | |
def home(): | |
return 'private' | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment