DEV Community

Chevy Vall
Chevy Vall

Posted on

1

Flask me how to Login!

Many applications and websites need a way to keep track of and coordinate session and user information on the back end. While there are a plethora of ways to implement these features, Flask-Login easily provides us with the most important. The examples routes I'll be showing use flask-RESTful to organize the api, and I'll be showing as simple an implementation as I can manage. Let's take a look.

First, we install:

$ pip install flask-login
Enter fullscreen mode Exit fullscreen mode

Next, we'll import and create our LoginManager class, then initialize it with our app, assuming that we're using a config file:

# config.py
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
Enter fullscreen mode Exit fullscreen mode

Our app.py imports:

# app.py
from flask_login import login_user, logout_user, current_user

from config import app, db, api, login_manager
from models import User
Enter fullscreen mode Exit fullscreen mode

That's a lot of imports! Let's break them down: login_user is a function that takes a user and stores them as the current_user and adds their id to the session. logout_user clears the current_user and cleans up relevant cookies from the session.

We'll also need provide a user_loader callback to pull the user from our database based on the id stored in session. We don't have to interact with this function directly after it's implemented.

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)
Enter fullscreen mode Exit fullscreen mode

We also have to provide the corresponding class method in our model:

# models.py
from flask_login import UserMixin

class User(db.Model, UserMixin):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)

    @classmethod
    def get(self, id):
        return User.query.get(id)
Enter fullscreen mode Exit fullscreen mode

You may have noticed we're inheriting from UserMixin as well. Flask-login requires your model to have the following properties and methods:

    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return str(self.id)
Enter fullscreen mode Exit fullscreen mode

While you can overwrite these, UserMixin allows you to shortcut including these by providing default implementations if you don't need the extra functionality.

Back in our app.py we can take a look at handling request to log in:

class Login(Resource):
    def post(self):
        data = request.json
        user = User.query.filter_by(username=data.get("username")).first()
        if user is None or not user.authenticate(data.get("password")):
            response = make_response({'error':'Invalid username or ID'})
            response.status_code = 401
            return response

        login_user(user)
        return make_response(user.to_dict(), 201)
Enter fullscreen mode Exit fullscreen mode

The call to login_user is the magic here, this will store the id of the user that was passed to us in session so that we can easily authenticate and reload the user on a page refresh, as well as set the current_user to the user passed. We'll return a copy of the user so our front-end can log in too.

Our logout is even simpler:

class Logout(Resource):
    def get(self):
        logout_user()
        return make_response('logout successful', 200)
Enter fullscreen mode Exit fullscreen mode

logout_user will clear our the current user's id from session and the current_user object. We'll return a simple message for our front end.

And that's it! Flask-login includes many more features than these but this should get you off the ground if you just need a basic login management system.

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay