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="TheCodeLearner@gmail.com", username="TheCodeLearner",password="!aehashf0qr324*&#W)*E!") login_user(user) return render_template("logged_in.html", current_user=user ) return login_manager.unauthorized()
Instructions
Write the code for the method we use to load the user in memory
Write the code so that the user is logged in when the password check succeeds.