-from flask import Blueprint, render_template, flash
+from flask import Blueprint, render_template, flash, redirect, url_for
+from flask.ext import login, scrypt
from imoo import db, login_manager
from . import forms, models
blueprint = Blueprint('main', __name__, template_folder='templates')
+@login_manager.user_loader
+def load_user(userid):
+ return models.User.query.get(userid)
+
@blueprint.route("/")
def index():
return render_template('index.html')
@blueprint.route("/login", methods=["GET", "POST"])
-def login():
+def login_page():
form = forms.LoginForm()
if form.validate_on_submit():
- flash(u"login form submitted", "success")
+ user = models.User.query.filter_by(username=form.username.data).first()
+ if not user:
+ # User does not exist.
+ flash(u'Username or password is incorrect', 'error')
+ elif not scrypt.check_password_hash(form.password.data, user.pw_hash, user.pw_salt):
+ # User exists, but wrong password. Give same behavior as no user
+ # existing, to try to prevent mining of usernames.
+ flash(u'Username or password is incorrect', 'error')
+ else:
+ # Successful login.
+ login_success = login.login_user(user, remember=False)
+ if login_success:
+ pass
+ else:
+ flash(u'Login failed for {} - is that user marked inactive?'.format(user.username), 'error')
+ return redirect(url_for('.test_protected'))
return render_template('login.html', form=form)
+
+# Ideally, logout would be POST-only but I'm leaving it as a link for easier manual testing
+@blueprint.route("/logout", methods=["GET", "POST"])
+def logout_page():
+ login.logout_user()
+ flash(u"You have logged out successfully", 'success')
+ return redirect(url_for('.index'))
+
+@blueprint.route('/test_protected', methods=["GET"])
+@login.login_required
+def test_protected():
+ flash(u"protected page", 'success')
+ return render_template("index.html")