2

I have a flask app that uses flask security for authentication. I want to use graphql with graphene to fetch data but I'm having trouble accessing the current_user proxy which is I've always used to resolve requests. graphene only provides a customized pluggable view which is understandable but it can't access the current_user within the context of the app and therefore current_user reverts back to AnonymousUser.

here is some sample code

from flask import Flask, render_template, redirect, request
from flask_security import Security, SQLAlchemySessionUserDatastore, login_required, current_user, login_user

from flask_graphql import GraphQLView
import graphene
from graphene_sqlalchemy import SQLAlchemyConnectionField

from .models import UserModel, RoleModel, Todo, TodoModel
from .pipeline import session

app = Flask(__name__, template_folder="../templates", static_folder="../static")
app.config.from_object('core.pipeline.configs.DevConfig')
user_datastore = SQLAlchemySessionUserDatastore(session, UserModel, RoleModel)
security = Security(app, user_datastore)

@app.route('/')
@login_required
def index(path):
    user = current_user

    return render_template('index.html')

1 Answers1

1

Main issue in your code is

app.add_url_rule('/graphql', view_func=graphql_view())

Where graphql_view() run during code load without any flask request context.

Please, try this code

class GraphQLViewCurrentUser(GraphQLView):

    def get_context(self, request):
        context = super().get_context(request)
        context.update({'current_user': current_user})
        return context


app.add_url_rule(
    '/graphql', view_func=GraphQLViewCurrentUser.as_view(
        'graphql', schema=schema, context={}, graphiql=True))