Giter Club home page Giter Club logo

Comments (17)

maciejzukowski avatar maciejzukowski commented on June 2, 2024 10

You can check if root variable is null

class LoggingMiddleware(object):
    def resolve(self, next, root, info, **kwargs):
          if root is None:
              #This will only be called once for a request
              print(info.operation.name.value)

from flask-graphql.

maciejzukowski avatar maciejzukowski commented on June 2, 2024 7

For those that are using this solution for authentication of requests - I think a better approach is to not have security in the middleware but instead use decorators on the resolvers themselves.

from flask-graphql.

squarewave24 avatar squarewave24 commented on June 2, 2024 3

checking for root is None appears to work so far, but would love to know if this is the correct way to use it.

i am trying to use middleware for authorization of each graphql request.

from flask-graphql.

johnfrancisgit avatar johnfrancisgit commented on June 2, 2024 2

Running into the same issue with graphene-django. Only want to execute middleware resolve funcitons once on request, not for every response field.

from flask-graphql.

mrfoxes avatar mrfoxes commented on June 2, 2024 2

Hi, Do you have some news about this topic?

Thanks

Hi @diegopaladini, for now to run that logic just one time in a middleware I'm doing the same as @maciejzukowski beacause the default graphql behaviour is to run that middelware logic for each resolver that is being called but in my case i don't need it

class LoggingMiddleware(object):
    def resolve(self, next, root, info, **kwargs):
          if root is None:
              #This will only be called once for a request
              print(info.operation.name.value)

from flask-graphql.

gijswobben avatar gijswobben commented on June 2, 2024 1

I have the same issue, but no solution. I did notice however, that the middleware gets called with different inputs. If you try something like this, you'll see what I mean (careful, this creates a LOT of output):

def testMiddleware(next, root, info, *args, **kwargs):
    p = next(root, info, *args, **kwargs)
    def r(x):
        print(type(x), x)
        return x
    return p.then(lambda x: r(x))

Any suggestions are welcome!

from flask-graphql.

gijswobben avatar gijswobben commented on June 2, 2024 1

It appears to be expected behavior. The Django debug middleware is using it to gather all the promises and summarize them: https://github.com/graphql-python/graphene-django/blob/dc561c68c49d1a91637503f765857d819c36769a/graphene_django/debug/middleware.py

However, I think it's still nice to have some kind of work-around.

from flask-graphql.

yamila-moreno avatar yamila-moreno commented on June 2, 2024

Thanks! We'll check it.

from flask-graphql.

aindong avatar aindong commented on June 2, 2024

Did anyone find a workaround on this? Because I want to log only the root query, not the whole fields many times.

from flask-graphql.

yamila-moreno avatar yamila-moreno commented on June 2, 2024

I made a workaround for logout only, not for the query-per-field; the solution was:

class Logout(relay.ClientIDMutation):
    class Input:
        pass

    data = Boolean()

    @classmethod
    def mutate_and_get_payload(cls, root, info, **input):
        try:
            # Workaround for https://github.com/graphql-python/flask-graphql/issues/53
            token = info.context['request'].headers.get('Authorization')
            user = auth_service.get_authorized_user_via_token(token)
            if not user:
                raise GenericError('API_ERRORS.BAD_CREDENTIALS')
            auth_service.logout(token)
        except GenericError as e:
            return Promise.reject(GraphQLError(e.message))

        return Logout(data=True)

from flask-graphql.

mrfoxes avatar mrfoxes commented on June 2, 2024

I'm having the same problem, check for root is None seems fine but as you look the middleware continue to run many many times, you just stop executing the logic every time but it continue to run

It seems that every resolver function call the middleware execution

In my case i'm using Django and I'm considering to move the authentication logic inside the default MIDDLEWARE section so that grapqhl stop executing the middleware for each resolver function

Screenshot 2020-01-29 at 13 31 57

from flask-graphql.

diegopaladini avatar diegopaladini commented on June 2, 2024

Hi, Do you have some news about this topic?

Thanks

from flask-graphql.

alimirjahani7 avatar alimirjahani7 commented on June 2, 2024

I have the same problem and the middleware is running four time for any request and in two of them root is not None

from flask-graphql.

acorrea-B avatar acorrea-B commented on June 2, 2024

i have the same problem but i use a external service to auth and and a get a spam because launch 10 request 1 per second

from flask-graphql.

acorrea-B avatar acorrea-B commented on June 2, 2024

You can check if root variable is null

class LoggingMiddleware(object):
    def resolve(self, next, root, info, **kwargs):
          if root is None:
              #This will only be called once for a request
              print(info.operation.name.value)

is a good solution and works for me, but @graphql-python have to solution

from flask-graphql.

milieere avatar milieere commented on June 2, 2024

Hi! graphene fastAPI user here. Currently facing the same challenge. It is very cumbersome to implement authorization since I have a complex schema and GraphQL middleware executes so many times. In the middleware, I need to execute JWT verification, which sends requests to Azure AD endpoints to get certificates, which is overwhelming the server and it becomes unresponsive :(

I had to implement the authorization in the middleware of FastAPI, but this is not ideal either - since now when my user is not authorized and hits graphql endpoint, he only gets back 'Internal Server Error'..

Anyone though about a different workaround? Using a decorator with resolvers is not neat either since I want to authorize every single request, i.e. introspection queries.

from flask-graphql.

akash-mahmud avatar akash-mahmud commented on June 2, 2024

Same problem, I am using graphne and django for my graphql server. I have my external server where I just need to pass the jwt. So I am using the middleware system. it seems that the middleware always gets called multiple times. The root None solution works. But still this function is executing multiple times which I don't need,

My middleware code

from django.conf import settings
from graphql_jwt.middleware import JSONWebTokenMiddleware
from .helpers.user import get_user
class CustomJWTMiddleware(JSONWebTokenMiddleware):
    def resolve(self, next, root, info, **kwargs):
        if root is None:
            print(root)
            # Get the JWT token from the request headers
            jwt_token = info.context.META.get('HTTP_AUTHORIZATION')
            # If there is no JWT token, call the next middleware
            if not jwt_token:
                return next(root, info, **kwargs)

            # Send the JWT token to your Node.js server for verification

            try:
                

                user = get_user(jwt_token)
                info.context.user =user
            except Exception as e:
                print(e)
                raise Exception(e)
        print("middleware calling")
        return next(root, info, **kwargs) 

from flask-graphql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.