Skip to content
site logo mobile

Forum in maintenance, we will back soon 🙂

Python Flask, Flask...
 
Notifications
Clear all

Python Flask, Flask-Login, decorator login_required, and a new script for a logout_required decorator

3 Posts
2 Users
3 Likes
14 Views
SSAdvisor
(@ssadvisor)
Posts: 960
Noble Member
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
Topic starter
 

One of the coding items you'll need to code is authentication and controlling access to your route endpoints. For instance if you have a route to the endpoint /profile you don't want unauthenticated users accessing that endpoint. So to control that you import the login_required decorator function from the flask_login package to use like so.

from flask import Flask, render_template
from flask_login import login_required

app = Flask(__name__)

@app.route('/profile')
@login_required
def profile():
    return render_template('profile.html')

So now if your /profile endpoint is accessed anonymously the user is redirected to the login page.

Unfortunately flask_login doesn't provide the opposite decorator to control the /login and /register endpoints. I've created the following with the help of ChatGPT.

import flask as fl
import flask_login as flLogin
import functools as ft

def logout_required(f):
    @ft.wraps(f)
    def decorated_function(*args, **kwargs):
        if flLogin.current_user.is_authenticated:
            # Redirect to the home page or another appropriate page
            return fl.redirect(fl.url_for('index'))
        return f(*args, **kwargs)
    return decorated_function

and to use it

@app.route('/login')
@logout_required
def login():
    return render_template('index.html')

@app.route('/register')
@logout_required
def register():
    return render_template('register.html')

NOTE: The examples are incomplete and are given only as a sample for use of the decorators.

POLL: Is this something you think you could use?

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 05/05/2024 1:34 am
Hasan Aboul Hasan
(@admin)
Posts: 992
Member Admin
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

Thanks for sharing, I was just creating some custom decorators today for my API project, but am using FastAPI and not Flask.

 
Posted : 05/05/2024 12:47 pm
SSAdvisor
(@ssadvisor)
Posts: 960
Noble Member
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
Topic starter
 

@admin looking forward to seeing your API project.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 05/05/2024 2:02 pm
Share: