Best practices for user authentication using Flask is to make it hard for someone to use a stolen credential.

To achieve this in Flask use the Flask’s Werkzeug library which has generate_password_hash method to generate a hash, and check_password_hash method to compare login input with the value returned from the check_password_hash method.

Our login code will check whether the value passed in is the same as the hardcoded user we are using to emulate a database.

We create a User class to represent a user. This object takes advantage of UserMixin (Mixins are prepackaged code of common code needs). In this case we use UserMixin because it allows us to take advantage of common user account functions without having to write it all ourselves from scratch.

The code below is the logic we use to log a user in if their password is correct.

@app.route('/', methods=['GET', 'POST']) def index(): if flask.request.method == 'GET': return ''' <p>Your credentials: username: TheCodeLearner password: !aehashf0qr324*&#W)*E! </p> <form action='/' method='POST'> <input type='text' name='email' id='email' placeholder='email'/> <input type='password' name='password' id='password' placeholder='password'/> <input type='submit' name='submit'/> </form> ''' email = "TheCodeLearner" if flask.request.form['password'] == "!aehashf0qr324*&#W)*E!": user = User(email="[email protected]", username="TheCodeLearner",password="!aehashf0qr324*&#W)*E!") login_user(user) return render_template("logged_in.html", current_user=user ) return login_manager.unauthorized()

Take a look at the second conditional:

if flask.request.form['password'] == "!aehashf0qr324*&#W)*E!":

Here, we’re checking that the form was submitted with a password that has the value "!aehashf0qr324*&#W)*E!". If the password matches "!aehashf0qr324*&#W)*E!" exactly, then we can create a new User instance with the properties specified above and save the object to user. We then use the login_user(user) to load the newly created User instance. Once logged in, we can load the proper page using render_template("logged_in.html", current_user=user). If the password isn’t correct, we return login_manager.unauthorized().



Write the code so that the user is logged in when the password check succeeds.

Inside the conditional that checks if the password matches "!aehashf0qr324*&#W)*E!" and under the user instance:

  1. Log in the user using the login_user() function.
  2. Return the result of calling render_template() with the page "logged_in.html", and setting current_user as user.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?