Search code examples
gographqlgraphql-go

Get the query name from the request in "github.com/graphql-go/graphql"


I'm creating a graphql api in golang using "github.com/gin-gonic/gin" "github.com/graphql-go/graphql" To secure my api i will use a jwt token and i want to keep my api to be fully graphql (the only route allowed is localhost:9000/graphql) Is there a way to get the query name from the request so i would only do the jwtparsing for every other query except login

my handle file

package graphql

import (
    "fmt"
    "log"

    "*****/graphql/mutations"
    "*****/graphql/queries"
    "github.com/gin-gonic/gin"
    "github.com/graphql-go/graphql"
    "github.com/graphql-go/handler"
)

func Handler() gin.HandlerFunc {

    schema, err := graphql.NewSchema(graphql.SchemaConfig{
        Query: graphql.NewObject(
            graphql.ObjectConfig{Name: "QueryType", Fields: graphql.Fields{
                "book":  queries.BookQuery,
                "books": queries.GetAllBooks,
                "login": queries.Login,
            }},
        ),
        Mutation: graphql.NewObject(
            graphql.ObjectConfig{Name: "MutationType", Fields: graphql.Fields{
                "insertOneBook": mutations.InsertOneBook,
                "updateOneBook": mutations.UpdateOneBook,
                "deleteOneBook": mutations.DeleteOneBook,
            }},
        ),
    })

    if err != nil {

        log.Fatal("error Parsing")
    }

    h := handler.New(&handler.Config{
        Schema:     &schema,
        Pretty:     true,
        GraphiQL:   true,
        Playground: true,
    }) 
    return func(c *gin.Context) {
        // Get the header authorisation
        // fmt.Println(c.Request.Header)
        // authHeader := c.GetHeader("Authorization")

        // Get the token by removing the "Bearer" string
        // tokenString := strings.SplitN(authHeader, " ", -1)
        // fmt.Println("this is token string", tokenString)
        // if len(tokenString) < 2 {
        //  c.AbortWithStatus(http.StatusUnauthorized)
        // } else {
        //  authState := utils.JwtValidate(tokenString[1])
        //  if authState != http.StatusAccepted {
        //      c.AbortWithStatus(authState)
        //  } else {
        //      h.ServeHTTP(c.Writer, c.Request)
        //  }
        // }
        h.ServeHTTP(c.Writer, c.Request)
        // Check is tokens validity

    }
}

Solution

  • it's json - you can check if [string] contains login ...

    ... but it's about security ... you're bypassing ...

    • check if request contains only login query, without other injections (no side/parallel queries) ... (strip new lines/white chars ... regex) ... exact phrase - must be perfectly equal to predefined template, length, too!!!
    • and has required variables provided