Gqlgen: Problem authenticating with chi-router

Created on 20 Jan 2019  路  1Comment  路  Source: 99designs/gqlgen

I am trying the authentication example and for some reason, I am unable to get key-values in the context object. Here is a sample code

auth.go

package auth

import (
    "context"
    "net/http"
)

var userCtxKey = &contextKey{"user"}

type contextKey struct {
    name string
}

type User struct {
    Username string
}

func Middleware() func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

            user := User {
                Username: "jon_snow",
            }

            // put it in context
            ctx := context.WithValue(r.Context(), userCtxKey, user)


            // and call the next with our new context
            r = r.WithContext(ctx)
            next.ServeHTTP(w, r)

        })
    }
}

// ForContext finds the user from the context. REQUIRES Middleware to have run.
func ForContext(ctx context.Context) *User {
    raw, _ := ctx.Value(userCtxKey).(*User)
    return raw
}

server.go

package main

import (
    "github.com/99designs/gqlgen/handler"
    "github.com/go-chi/chi"
    "gitlab.com/johnsnow/as"
    "gitlab.com/johnsnow/as/middleware"
    "log"
    "net/http"
    "os"
)

const defaultPort = "8080"


func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = defaultPort
    }
    router := chi.NewRouter()

    // Inject middleware
    router.Use(auth.Middleware())

    router.Handle("/", handler.Playground("GraphQL playground", "/query"))
    router.Handle("/query",
        handler.GraphQL(as.NewExecutableSchema(as.Config{Resolvers: &as.Resolver{}})))

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    err := http.ListenAndServe(":"+port, router)
    if err != nil {
        panic(err)
    }
}

resolver.go

func (r *mutationResolver) CreateRecord(ctx context.Context, input NewRecord) (models.Record, error) {
    fmt.Printf(auth.ForContext(ctx))

    return models.Record, nil
}

Expected Behaviour

It should print jon_snow when CreateRecord mutation is executed

Actual Behavior

But it printed <nil>

Am I missing something ?

Most helpful comment

Is your problem that you are putting a User struct into context but then trying to get out a *User? If you check the type assertion return value in ForContext I suspect you will find an error and nil is just the empty value being returned.

>All comments

Is your problem that you are putting a User struct into context but then trying to get out a *User? If you check the type assertion return value in ForContext I suspect you will find an error and nil is just the empty value being returned.

Was this page helpful?
0 / 5 - 0 ratings