-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
52 lines (43 loc) · 1.33 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"context"
"errors"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/handler"
jwt "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
// AuthContextKeyType type of authContextKey
type AuthContextKeyType string
const authContextKey AuthContextKeyType = "auth"
func main() {
e := echo.New()
e.Use(middleware.Recover())
e.Use(middleware.Logger())
e.POST("/login", login)
e.GET("/playground", echo.WrapHandler(handler.Playground("GraphQL playground", "/api/graphql")))
api := e.Group("/api")
api.Use(middleware.JWTWithConfig(middleware.JWTConfig{
Claims: &jwt.StandardClaims{},
ContextKey: string(authContextKey),
SigningKey: []byte("secret"),
}))
api.POST("/graphql", func(c echo.Context) error {
h := handler.GraphQL(NewExecutableSchema(Config{Resolvers: &Resolver{}}),
handler.ResolverMiddleware(func(ctx context.Context, next graphql.Resolver) (interface{}, error) {
token, ok := c.Get(string(authContextKey)).(*jwt.Token)
if ok == false {
return nil, errors.New("auth_context_not_found")
}
ctx = context.WithValue(ctx, authContextKey, token)
return next(ctx)
}),
)
h.ServeHTTP(c.Response(), c.Request())
return nil
})
e.Logger.SetLevel(elog.INFO)
e.HideBanner = true
e.Logger.Fatal(e.Start(":3000"))
}