Skip to content

Instantly share code, notes, and snippets.

@hansonkd
Created April 9, 2013 03:30
Show Gist options
  • Save hansonkd/5342748 to your computer and use it in GitHub Desktop.
Save hansonkd/5342748 to your computer and use it in GitHub Desktop.
from flask import Flask
from flask.ext.security import RoleMixin, UserMixin, MongoEngineUserDatastore, Security
from flask.ext.mongoengine import MongoEngine
from werkzeug.local import LocalProxy
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = dict(
db='flask_security_test',
host='localhost',
port=27017
)
db = MongoEngine(app)
class Role(db.Document, RoleMixin):
name = db.StringField(required=True, unique=True, max_length=80)
description = db.StringField(max_length=255)
class User(db.Document, UserMixin):
email = db.StringField(unique=True, max_length=255)
password = db.StringField(required=True, max_length=255)
last_login_at = db.DateTimeField()
current_login_at = db.DateTimeField()
last_login_ip = db.StringField(max_length=100)
current_login_ip = db.StringField(max_length=100)
login_count = db.IntField()
active = db.BooleanField(default=True)
confirmed_at = db.DateTimeField()
roles = db.ListField(db.ReferenceField(Role), default=[])
app.security = Security(app, datastore=MongoEngineUserDatastore(db, User, Role))
ds = LocalProxy(lambda: app.extensions['security'].datastore)
def create_roles():
for role in ('admin', 'editor', 'author'):
ds.create_role(name=role)
def create_users(count=None):
users = [('[email protected]', 'password', ['admin'], True),
('[email protected]', 'password', ['editor'], True),
('[email protected]', 'password', ['admin', 'editor'], True),
('[email protected]', 'password', ['author'], True),
('[email protected]', 'password', [], False)]
count = count or len(users)
for u in users[:count]:
pw = u[1]
ds.create_user(email=u[0], password=pw,
roles=u[2], active=u[3])
def populate_data(user_count=None):
create_roles()
create_users()
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment