Last active
August 29, 2015 14:00
-
-
Save kaiserama/11398525 to your computer and use it in GitHub Desktop.
Flask-Login + Principal Basic
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
class LoginForm(Form): | |
email = TextField('Email', validators=[Required()]) | |
password = PasswordField('Password', validators=[Required()]) | |
remember = BooleanField('Remember Me', default=True) | |
class UserRole(db.Model): | |
__tablename__ = 'user_role' | |
id = db.Column('user_role_id', db.Integer, primary_key=True) | |
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id')) | |
role = db.Column(db.String) | |
class User(db.Model, UserMixin): | |
__tablename__ = 'user' | |
id = db.Column('user_id', db.Integer, primary_key=True) | |
email = db.Column(db.String(155)) | |
password_hash = db.Column(db.String(40)) | |
user_roles = db.relationship('UserRole', foreign_keys=[UserRole.user_id]) | |
# decorator function for principal once an identity has been loaded we'll pull out the given user's roles | |
@identity_loaded.connect_via(app) | |
def on_identity_loaded(sender, identity): | |
identity.user = current_user | |
if hasattr(current_user, 'id'): | |
identity.provides.add(UserNeed(current_user.id)) | |
if hasattr(current_user, 'user_roles'): # my user model contains a user_roles relationship | |
for this_role in current_user.user_roles: | |
identity.provides.add(RoleNeed(this_role.role.)) | |
@app.route('/login', methods=['GET', 'POST']) | |
def login() | |
form = LoginForm() | |
if form.validate_on_submit(): | |
# authenticate user | |
user = User.query.filter_by(email=request.form['email']).first() | |
if user and user.check_password(request.form['password']) and user.id != 0: | |
remember = request.form.get("remember", "no") == "yes" | |
login_user(user, remember=remember) | |
identity_changed.send(app, identity=Identity(user.id)) # call to principal | |
return redirect(request.args.get("next") or url_for("router")) | |
else: | |
flash("Sorry, invalid username/password.", "danger") # I use flask-bootstrap so the category danger will create color coded messages | |
return render_template('login.html', form=form, title="Account Log In", |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment