Search code examples
pythonauthenticationflaskflask-principal

decorator require doens't work correctly in flask-principal in my sample


I have problem with decorator require(http_exception=401) in flask-principal. I am trying to access to site which requires login, but I am able to access there. Do you have any idea why? My code following:

infrastructure.py

app = Flask(__name__)
db = SQLAlchemy(app)
principals = Principal(app)
principals._init_app(app)

# User Information providers
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    g.user = User.query.from_identity(identity)
# Permission
admin = Permission(RoleNeed('admin'))
member_perm = Permission(RoleNeed('member'))

User = get_user_class(db.Model)

views/login.py

# -*- coding: utf-8 -*-
from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash, current_app
from flask.ext.principal import identity_changed, Identity
from hlidejkatastr.infrastructure import app, User

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        user = User.query.filter(User.email==email).first()
        if user is not None:
            if user.password == request.form['password']:
                identity_changed.send(current_app._get_current_object(),   identity=Identity(user.id))
                return redirect(url_for('profil'))
            else:
                return render_template('login.html')
        else:
            return render_template('login.html')
    return render_template('login.html')

views/profil.py

@member_perm.require(http_exception=401)
@app.route('/profil/', methods=['GET', 'POST'])
def profil():
    # code ...

Thank you for you advice.


Solution

  • The @member_perm decorator should be below/within the @app.route decorator:

    So try:

    @app.route('/profil/', methods=['GET', 'POST'])
    @member_perm.require(http_exception=401)
    def profil():
        # code ...