gorilla/sessions

[question] How to use store.Get() from within resolvers?

jerlam06 opened this issue · 5 comments

How am I supposed to use the Get() function from within a graphql resolver?

session, _ := store.Get(r, "session-name")

I have been searching for two hours. I am surprised to be the only one wondering this.
r *http.Request is not accessible from within resolvers. I tried with the context, but it does not seem to work.

Thanks in advance

Thanks for your response. Here is the implementation:

func userLogin(ctx context.Context, r *mutationResolver, password string, email string) (bool, error) {
	db := r.ORM.New().Begin()
	user := &dbm.User{}
	db = db.Where(&gqlm.User{Email: email}).Find(&user)

	// Compares the password input with the password from the user with the specific email
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		fmt.Println(err)
		return false, errors.New("Email and/or Password invalid")
	}

	// HERE I need to have something like this: sess, err := session.Store.Get(h, "session")
}

As you can see in my code, it is impossible for me to use store.Get() or store.Save(), because they both need a *http.Request as first argument. But I only have access to http.Request in my middleware. And I have no idea how to manipulate the store from within my Login/Logout resolvers...

Why can’t you pass the request pointer to that function? You likely also want access to the http.ResponseWriter to save any updates to the session cookie.

Do you mean via the context? If so, I already tried it:

package middleware

var handlerCtxKey = &contextKey{"auth-token"}

type contextKey struct {
	name string
}

type HandlerContext struct {
	ResponseWriter   http.ResponseWriter
	Req                      http.Request
}

func SessionMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.WithValue(r.Context(), handlerCtxKey, HandlerContext{w, *r})

		r = r.WithContext(ctx)
		h.ServeHTTP(w, r)
	})
}

func HandlerFuncContext(ctx context.Context) HandlerContext {
	raw, _ := ctx.Value(handlerCtxKey).(HandlerContext)
	return raw
}

Then:

package resolvers

func userLogin(ctx context.Context, r *mutationResolver, password string, email string) (bool, error) {
        ...
        h := middleware.HandlerFuncContext(ctx)
        fmt.Println(h.Req) // <--- This prints the Request correctly

	sess, err := session.Store.Get(h.Req, "session")
	if err != nil {
		fmt.Println(err) // <--- But here I get an ERROR: runtime error: invalid memory address or 
                // nil pointer dereference
	}
	fmt.Println("sess", sess)
}

So in the end, I am not sure if that's even possible, or if I did some mistakes (which is very likely haha)...

Alright, my apologies, I forgot to actually start redis...upsi