-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-handler.go
executable file
·106 lines (92 loc) · 2.43 KB
/
http-handler.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package gen
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"github.com/99designs/gqlgen/handler"
jwtgo "github.com/dgrijalva/jwt-go"
"gopkg.in/gormigrate.v1"
)
func GetHTTPServeMux(r ResolverRoot, db *DB, migrations []*gormigrate.Migration) *http.ServeMux {
mux := http.NewServeMux()
executableSchema := NewExecutableSchema(Config{Resolvers: r})
gqlHandler := handler.GraphQL(executableSchema)
loaders := GetLoaders(db)
playgroundHandler := handler.Playground("GraphQL playground", "/graphql")
if os.Getenv("EXPOSE_MIGRATION_ENDPOINT") == "true" {
mux.HandleFunc("/migrate", func(res http.ResponseWriter, req *http.Request) {
err := db.Migrate(migrations)
if err != nil {
http.Error(res, err.Error(), 400)
}
fmt.Fprintf(res, "OK")
})
mux.HandleFunc("/automigrate", func(res http.ResponseWriter, req *http.Request) {
err := db.AutoMigrate()
if err != nil {
http.Error(res, err.Error(), 400)
}
fmt.Fprintf(res, "OK")
})
}
mux.HandleFunc("/graphql", func(res http.ResponseWriter, req *http.Request) {
claims, _ := getJWTClaims(req)
var principalID *string
if claims != nil {
principalID = &(*claims).Subject
}
ctx := context.WithValue(req.Context(), KeyJWTClaims, claims)
if principalID != nil {
ctx = context.WithValue(ctx, KeyPrincipalID, principalID)
}
ctx = context.WithValue(ctx, KeyLoaders, loaders)
ctx = context.WithValue(ctx, KeyExecutableSchema, executableSchema)
req = req.WithContext(ctx)
if req.Method == "GET" {
playgroundHandler(res, req)
} else {
gqlHandler(res, req)
}
})
handler := mux
return handler
}
func GetPrincipalIDFromContext(ctx context.Context) *string {
v, _ := ctx.Value(KeyPrincipalID).(*string)
return v
}
func GetJWTClaimsFromContext(ctx context.Context) *JWTClaims {
val, _ := ctx.Value(KeyJWTClaims).(*JWTClaims)
return val
}
type JWTClaims struct {
jwtgo.StandardClaims
Scope *string
}
func getJWTClaims(req *http.Request) (*JWTClaims, error) {
var p *JWTClaims
tokenStr := strings.Replace(req.Header.Get("authorization"), "Bearer ", "", 1)
if tokenStr == "" {
return p, nil
}
p = &JWTClaims{}
jwtgo.ParseWithClaims(tokenStr, p, nil)
return p, nil
}
func (c *JWTClaims) Scopes() []string {
s := c.Scope
if s != nil && len(*s) > 0 {
return strings.Split(*s, " ")
}
return []string{}
}
func (c *JWTClaims) HasScope(scope string) bool {
for _, s := range c.Scopes() {
if s == scope {
return true
}
}
return false
}