Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle login in flask with multiple blueprints?

I have multiple blueprints that needs to be integrated into a single app. I'm using flask-login to handle logins. However I'm confused on how to handle the LoginManager() and the .user_loader for my blueprints.

This is my current file structure.

system/
     run.py
     config.py
     app/
        __init__.py
        models.py
        views/
             blueprint1.py
             blueprint2.py
        static/
        templates/
              <templates>

What's the correct way to implement them? Do I just call them at the __init__.py and import the login manager variable at the blueprints? or Do I need to call them individually in the blueprints?

Hopefully I'm able to portray the question clearly. Thank you for reading and answering

like image 793
Andriano winatra Avatar asked Nov 22 '13 02:11

Andriano winatra


People also ask

How do I register my blueprints in Flask?

To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() . When a Flask Blueprint is registered, the application is extended with its contents. While the application is running, go to http://localhost:5000 using your web browser.

How do I redirect to another page after Login in Flask?

Python for web development using FlaskFlask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.

What is Login manager in Flask?

Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users' sessions over extended periods of time. Flask-Login is not bound to any particular database system or permissions model.


1 Answers

The documentation is really unclear and I will put down what I come up with after spending some time researching.

You only need to define login_manager once in the flask app.py and init_app. Then at each blueprint, from flask_login import login_required and use the @login_required as usual. Turns out it can be used without stating the login_manager

Code example (app with single blueprint)

app.py

import flask
from flask import redirect, url_for
import flask_login

from blueprint.secret import secret_bp
from model.user import User

login_manager = flask_login.LoginManager()

app = flask.Flask(__name__)
app.register_blueprint(secret_bp, url_prefix="/secret")

login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == "GET":
        return "<form action='/login' method='POST'><input type='text' name='user'><button type='submit'>Submit</button></form>"

    user = flask.request.form.get('user')
    if user == "user":
        # Login and validate the user.
        # user should be an instance of your `User` class
        flask_login.login_user(user)

        flask.flash('Logged in successfully.')

        return flask.redirect(next or flask.url_for('index'))
    return flask.redirect(flask.url_for('login'))

@app.route('/admin')
def admin():
    return "Admin page"

@login_manager.unauthorized_handler
def unauthorized():
    # do stuff
    return redirect(url_for('login'))

secret.py

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
from flask_login import login_required

secret_bp = Blueprint('secret', __name__,
                        template_folder='templates')

@secret_bp.route('/noneed')
def no_need():
    return "You can see this without login."

@secret_bp.route('/needlogin')
@login_required
def show():
    return "can't see this if not login"

As expected, /secret/noneed can be access without login and /secret/needlogin will redirect you with the function stated with @unauthorized_handler.

like image 61
Jim LK Yu Avatar answered Oct 18 '22 10:10

Jim LK Yu