Skip to content

Instantly share code, notes, and snippets.

@shrayasr
Last active June 30, 2019 15:46
Show Gist options
  • Select an option

  • Save shrayasr/10004888 to your computer and use it in GitHub Desktop.

Select an option

Save shrayasr/10004888 to your computer and use it in GitHub Desktop.
Getting started with Flask-Login

Getting started with Flask-Login

Pre-requisites

  • Flask pip install flask
  • Flask-Login pip install flask-login

Steps

  • Initialize the flask app with app=Flask(__name__)
  • Set a secret key, Flask-Login uses sessions and sessions in Flask need a secret Key
  • Create an instance of LoginManager class login_manager = LoginManager()
  • Initialize the LoginManager with the app that was created login_manager.init_app(app)
  • In your User model, implement the UserMixin from Flask-Login class User(UserMixin) and implement the required methods: is_authenticated, is_active, is_anonymous and get_id
  • Decorate a method with @login_manager.user_loader that returns the User object given the ID
  • In the login end point, once the app side validation is done, register the user into Flask-Login with the login_user method. login_user(userDAO.get(user_name)). This would register a session with that user
  • After that, any route that needs authentication can be decorated with @login_required and Flask-Login takes care of the rest
  • To logout, call the logout_user() method
  • To get the current user's ID the current_user.get_id() method can be used. If there is no one logged in, current_user.get_id() would return None

DONE.

Implementation

I've written one small repo that illustrates this over here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment