Implementing the timeout

I was looking for an easy way to override the default behaviour in Flask which is to use the UserID field to login to a web app using Flask Login. I put together multiple different examples to get the following code:

class User(UserMixin):
    def __init__(self, email, password):
        self.email = email
        self.password = password

    def get_id(self):
        return self.email

This code overrides the default ‘User’ class in Flask Login, by extending the Usermixin object to define it’s own get_id method to return the email address, rather than a UserID. This means that that you can use users email addresses as the default login method for your users, rather than having to rely on them creating UserIDs when registering, which according to most guidance makes more sense as users will generally remember an email address more than their username, especially if it’s a web app that they don’t often use.

Complete Example

Please see below for a complete example:

from flask import Flask, render_template, redirect, url_for
from flask_login import LoginManager, login_user, current_user, login_required, logout_user
from User import User

app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret-key-goes-here'

login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(email):
    # Load user from database or create new user object
    return User(email=email, password='password-goes-here')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        user = User(email=email, password=password)

        if user:
            login_user(user)
            return redirect(url_for('index'))

    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run()


The main limitations of this code is that it is a prototype, and relies on a backend database to be implemented to store users credentials securely. Finally, any users using the code will have to adjust their code to be able to accept email addresses in their frontend rather than a username.

For more tutorials please check out the tag links below: