Flask-login doesn’t actually have a user backend, it just handles the session machinery to help you login and logout users. You have to tell it (by decorating methods), what represents a user and it is also up to you to figure out how to know if a user is “active” or not (since being “active” can mean different things in different applications).
You should read the documentation and be sure what it does and does not do. Here I am only going to concentrate on wiring it up with the db backend.
To start off with, define a user object; which represents properties for your users. This object can then query databases, or LDAP, or whatever and it is the hook that connects the login mechanism with your database backend.
I will be using the login example script for this purpose.
class User(UserMixin):
def __init__(self, name, id, active=True):
self.name = name
self.id = id
self.active = active
def is_active(self):
# Here you should write whatever the code is
# that checks the database if your user is active
return self.active
def is_anonymous(self):
return False
def is_authenticated(self):
return True
Once you have the user object created, you need to write a method that loads the user (basically, creates an instance of the User
class from above). This method is called with the user id.
@login_manager.user_loader
def load_user(id):
# 1. Fetch against the database a user by `id`
# 2. Create a new object of `User` class and return it.
u = DBUsers.query.get(id)
return User(u.name,u.id,u.active)
Once you have these steps, your login method does this:
-
Checks to see if the username and password match (against your database) – you need to write this code yourself.
-
If authentication was successful you should pass an instance of the user to
login_user()