Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logged in User tutorial does not work #1449

Open
dove-young opened this issue Sep 2, 2022 · 2 comments
Open

Logged in User tutorial does not work #1449

dove-young opened this issue Sep 2, 2022 · 2 comments

Comments

@dove-young
Copy link

Here https://www.howtographql.com/graphql-go/8-logged-in-user-object/

mutation {
  createUser(input: {username: "user1", password: "123"})
}
  • Paste the token to the Authorization JSON
{
  "Authorization": "" // use your own generated token
}
  • Send mutation
mutation {
  createLink(input: {title: "real link!", address: "www.graphql.org"}){
    user{
      name
    }
  }
}
  • it always fails
{
  "errors": [
    {
      "message": "access denied",
      "path": [
        "createLink"
      ]
    }
  ],
  "data": null
}
@dove-young
Copy link
Author

CreateLink function starts at

user := auth.ForContext(ctx)
	if user == nil {
		return &model.Link{}, fmt.Errorf("access denied")
	}

And the ForContext function is like this. I don't find anywhere fetching user information

func ForContext(ctx context.Context) *users.User {
	raw, _ := ctx.Value(userCtxKey).(*users.User)
	return raw
}

@dove-young
Copy link
Author

dove-young commented Sep 2, 2022

I got it fixed

git diff server.go
diff --git a/server.go b/server.go
index 1db5d8f..b29dd01 100644
--- a/server.go
+++ b/server.go
@@ -9,6 +9,7 @@ import (
        "github.com/99designs/gqlgen/graphql/playground"
        graph "github.com/dove-young/hackernews/graph"
        "github.com/dove-young/hackernews/graph/generated"
+       "github.com/dove-young/hackernews/internal/auth"
        database "github.com/dove-young/hackernews/internal/pkg/db/mysql"
        "github.com/go-chi/chi"
 )
@@ -21,11 +22,12 @@ func main() {
                port = defaultPort
        }
 
-       router := chi.NewRouter()
-
        database.InitDB()
        defer database.CloseDB()
        database.Migrate()
+       router := chi.NewRouter()
+       router.Use(auth.Middleware())
+
        server := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))
        router.Handle("/", playground.Handler("GraphQL playground", "/query"))
        router.Handle("/query", server)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant