- Flask
pip install flask
- Flask-Login
pip install flask-login
- Create your user model class:
User
. This would be a class that stores information about your User. Essentially theuser_name
,user_id
,email
, etc. - Create your user access class:
UserDAO (User Data Access Object)
. This is the wrapper around your user model that uses theUser
class and performs functions around it (signup, signin, validate, etc) - 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
classlogin_manager = LoginManager()
- Initialize the
LoginManager
with the app that was createdlogin_manager.init_app(app)
- In
User
, inherit theUserMixin
from Flask-Login.class User(UserMixin)
. Implement the required methods:is_authenticated
,is_active
,is_anonymous
andget_id
- Decorate a method with
@login_manager.user_loader
that returns theUser
object given the ID (theUserDAO
would be where this method would be written) - In the login end point, once the app side validation is done, register the user into Flask-Login with the
login_user
method. Thelogin_user
method takes aUser
object.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 returnNone
DONE.
- Check this repo.