osacognitive
osacognitive

Reputation: 103

Flask Blueprints and decorators

I'm new to flask.

Can I use decorators with a flask blueprint if the decorator depends on a variable that would be initialized based on a flask app?

The example I can give is that I'm trying to use the flask_oidc library to integrate MFA login with keycloak. However, every time I attempt to initialize an OpenIDConnect object, I encounter some sort of issue. I don't think that I can do this outside of an app context. Currently, I am doing the following:

from flask import Blueprint, ...
from flask_oidc import OpenIDConnect

.
.
.

main = Blueprint('main', __name__)

.
.
.

@main.route('/login', methods=['POST'])
@current_app.oidc.require_login
def login():
    app = current_app._get_current_object()
    with app.app_context():
        username = app.oidc.user_getfield('email')

I've defined oidc within the create_app function in another file.

def create_app(config_name):

    .
    .
    .

    app.config.update({
    'DEBUG': True,
    'TESTING': True,
    'SECRET_KEY': 'testest',
    'OIDC_CLIENT_SECRETS': 'app/config/client_secrets.json',
    'OIDC_USER_INFO_ENABLED': True,
    'OIDC_OPENID_REALM': 'master',
    'OIDC_SCOPES': ['openid', 'profile'],
    'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post',
    })

    oidc = OpenIDConnect(app)

When I do this, I receive AttributeError: 'Flask' object has no attribute 'oidc' Is there a way for me to set the oidc variable within the blueprint? Is there a better way for me to access oidc from within the app context?

Here is the entire traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "./app/main.py", line 48, in login
    username = app.oidc.user_getfield('email')
AttributeError: 'Flask' object has no attribute 'oidc'
b'{\n  "error": "\'Flask\' object has no attribute \'oidc\'"\n}\n'

Upvotes: 0

Views: 1083

Answers (1)

DevLounge
DevLounge

Reputation: 8447

In your create_app you just create the oidc variable but you don't make it an attribute of app

It should be app.oidc = OpenIDConnect(app)

Upvotes: 0

Related Questions