muthan
muthan

Reputation: 2472

Proper way to handle two different types of user session in one app in flask

The flask app that I am building is split in 2 blueprint sections. Each section should have it's own authentication system that is totally independet from the other (own login page, each authentication has their own restricted access area, ... )

But as I feared and stated in this Post the Flask-Login module can only register to the app and not the blueprint, so that you have only one type of session for the whole app.

So what is the proper way to initalize a second type of login session that totally differ from the other one.

Upvotes: 1

Views: 3225

Answers (1)

Dan Safee
Dan Safee

Reputation: 1618

I don't think you need to do it the way you described.

You can create two different User models, and then you can change which model gets authenticated in different routes:

@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():

        user = User.query.filter_by(username=form.username.data).first()

        if user is not None and user.verify_password(form.password.data):
            login_user(user, True)
            next = request.args.get('next')
            #if not next_is_valid('next'):
            #    return abort(400)

            return redirect(next or url_for('simple.index'))
        flash('Invalid username or password')

    return render_template('/auth/login.html', form=form)

When you call login_user() you can pass in whichever user model you need. This will attach that database object to Flask-Login's current_user , which can be used in templates and in view functions. Using this method, you could keep separate user tables, and only login user that are in that particular table used in the route.

In reality, you probably want to use just one User model, but assign different roles to different users and only allow users with certain roles to access certain parts of the site.

Check out this REALLY simple decorator that you can use to restrict certain views to certain roles:

http://flask.pocoo.org/snippets/98/

Upvotes: 4

Related Questions