Flask · Lesson 6 of 15
Authentication with Flask-Login
Sessions, password hashes and protecting views with Flask-Login.
- Intermediate
- 16 min read
- 3 objectives
Before this lessonLesson 5: Config Objects and the App Factory
What you will learn
- Hash a password
- Log a user in
- Protect a route
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Flask-Login remembers the user id in the session. You still hash passwords yourself (or with Werkzeug) and load the user from the database.
The user mixin
from flask_login import UserMixin, LoginManager, login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
login_manager = LoginManager()
login_manager.login_view = "auth.login"
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(256), nullable=False)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
@login_manager.user_loader
def load_user(user_id):
return db.session.get(User, int(user_id))Login view
@bp.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
user = User.query.filter_by(email=request.form["email"]).first()
if user and user.check_password(request.form["password"]):
login_user(user, remember=True)
return redirect(request.args.get("next") or url_for("blog.index"))
flash("Invalid email or password.")
return render_template("login.html")
@bp.route("/logout")
def logout():
logout_user()
return redirect(url_for("blog.index"))
@bp.route("/private")
@login_required
def private():
return f"Hello {current_user.email}"