Updated April 19, 2023
Definition of Flask Users
Flask users are defined as a module or utility that enables developers to provide customizable user authentication and user management in a Flask application as an immediate out of the box solution bringing in the capability of sessions, login pages, registration pages, emailing post-registration, emailing the confirmation links, password changing links, and similar such kinds. In other words, the module provides developers to register users, send confirmations, changing usernames or passwords, and all sorts of the login of user-related capability. This module comes in a well-documented format and can be referred to anytime it is needed. In this article, we will go through the usage of flask users in real-world projects.
Syntax:
In cases of a web applications, we generally start with a simple login page and there we would like to authenticate our users. In those cases, we would need to not only handle registrations, email confirmations, providing flexibility to change usernames or passwords but also offer added security, increased reliability, role-based authorization, and finally possibility of including international languages. Here we will look at all the syntax that is a part of the flask user in its mission to provide multiple capabilities.
Installing the Flask user module:
pip install Flask-User
Importing all the libraries from Flask user module:
from flask_user import *
Importing login_required library from Flask user module:
from flask_user import login_required
Importing UserManager library from Flask user module:
from flask_user import UserManager
Importing UserMixin library from Flask user module:
from flask_user import UserMixin
Importing SQLAlchemyAdapter library from Flask user module:
from flask_user import SQLAlchemyAdapter
How does user function work in Flask?
In the user module, there are many sub utilities which have their respective way of working and in this section, we will learn more about those sub utilities which majorly captures the utility of flask user module. Just a point of disclaimer is that the list of modules that will be discussed here is not exhaustive, but ones that are widely used.
The first utility we will talk about is the working of login_required. This is the decorator which is used by developers to ensure that a user is logged in before accessing a page. This page can either be a rendered page or any other endpoint that needs to be accessed. Here in this utility, the class or decorator login_required extends the Flask Login’s utility of making sure that the user is logged in before accessing the page. Now, when a decorator is used, it makes the function mapped to that decorator only accessible to logged-in users. The decorator has an is_authenticated( ) implementation that provides the capability of knowing if the user is authenticated. Once the decorator is mapped to the function, any usage functionality in the function of the landing URLs will be controlled thus limiting the modification or deletion of HTTP operations to only the users for whom the utility is enabled.
The next utility that we will talk about is UserManager. This utility can be called a library from the flask_user module. This contains a UserManager class that implements most of the functionality of flask_user. Also, the features in UserManager is fully customizable which can be done by extending or overriding the methods within the class. This class would require parameters like: Flask application instance, Object-Database mapper instance, and a userClass. This utility allows developers to configure the user settings and these settings are then relayed back when any of the utilities are required. For example, if USER_ENABLE_FORGOT_PASSWORD parameter is True, then the Forgot password link will be enabled for its respective usage.
So, by now we have known about how the user is authenticated in login_required, and also supporting facilities to modify one’s settings using UserManager. Now the third is about UserMixin utility. This function allows secured storage of User ID in the browser cache and invalidates a token when there is a change in password. The details in user ID and password are encrypted, timestamped, and signed as well. The utility is extended from flask_login utility and is not a standalone utility. It stores the user ID, takes help from login_required to know if the user is authenticated and acts “like chocolate chips in a cookie” and helps build the utility of the application to what is wanted.
The final module is SQLAlchemyAdapter, and this helps in shielding itself from Database operations. Operations like finding all objects, getting objects, adding objects,s, etc. This module needs Flask-SQLAlchemy as a dependent. Calling this function, we will be able to register the user model.
Concluding, with the above classes in place it collectively works together for the utility of the entire flask_user module!
Examples
Example #1
Installing the Flask user module
Syntax:
pip install Flask-User
Output:
Example #2
Using abort function to portray unauthorized login
Syntax
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter
appFlask = Flask(__name__)
appFlask.config['SECRET_KEY'] = 'eduCBA'
appFlask.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://// Users/edu/database.db'
appFlask.config['CSRF_ENABLED'] = True
appFlask.config['USER_ENABLE_EMAIL'] = False
db = SQLAlchemy(appFlask)
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, server_default='')
active = db.Column(db.Boolean(), nullable=False, server_default='0')
adapterDB = SQLAlchemyAdapter(db, User)
manageUser = UserManager(adapterDB, appFlask)
@appFlask.route('/')
def index():
return '<h1>This is the initial landing page!</h1>'
@appFlask.route('/profile')
@login_required
def profile():
return '<h1>This page is accessible to logged in users!</h1>'
if __name__ == '__main__':
appFlask.run(debug=True)
Output
For admin login:
For another user Login:
Conclusion
To conclude, in this article we have looked at the simple way of working for redirect function and also how to abort function goes hand in hand with the redirect function. Usage of this functionality is left to readers to try out these concepts in Flask applications. Also, the list of error codes here will come in handy for our readers to use for correct functionality!
Recommended Articles
This is a guide to Flask Users. Here we discuss the definition, How does user function work in Flask? and examples with code implementation. You may also have a look at the following articles to learn more –