This video is available to students only

Setting Logins

The first function we'll use from flask_login is called login_user which handles the part of setting the cookie for the user.

Add this import to your file (from flask_login import login_user) and then add login_user(user) to your register route.

from flask_login import login_user

@user_bp.route('/register', methods=["GET", "POST"])
def register():
    form = SignupForm()
    if form.validate_on_submit():
        user = User.create(,
        return redirect(url_for("products.index")))

    return render_template("users/register.html", form=form)

Once this step is done, anyone who submits this form will be issued a cookie that represents a request from their specific user ID. The cookie is encrypted with a secret value (SECRET_KEY) in the Flask configuration. We should not arbitrarily set plain text data in cookies for things like authentication data because it's possible for browser or end user to modify this cookie. We wouldn't want to issue a cookie saying this cookie is from User 1, and then have a the end user modify it to look like it comes from User 2. By encrypting the data with our SECRET_KEY, we can ensure that only our server can encode valid data.


Create a login form in

from import  check_password_hash

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[, validators.required()])
    password = PasswordField('Password', validators=[validators.required()])

    def validate(self):
        check_validate = super(LoginForm, self).validate()
        if not check_validate:
            return False

        user = User.query.filter_by(

        if not user or not check_password_hash(user.password,
  'Invalid email or password')
            return False
        return True

In our user blueprint (, add code to handle the login and call login_user

from flask import ..., flash

@user_bp.route('/login', methods=["GET", "POST"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(
        flash("Logged in successfully.", "success")
        return redirect(url_for("products.index"))

    return render_template("users/login.html", form=form)

Start a new discussion. All notification go to the author.