-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
65 lines (53 loc) · 1.64 KB
/
middleware.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
package main
import (
"context"
"fmt"
"github.com/bugsnag/bugsnag-go"
"github.com/dgrijalva/jwt-go"
"github.com/spf13/viper"
"github.com/Gratheon/swarm-api/logger"
"net/http"
)
func logToBugsnag(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = bugsnag.StartSession(ctx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
type Input struct {
OperationName string `json:"operationName"` //IntrospectionQuery
}
func authMiddleware(next http.Handler) http.Handler {
jwtSecret := viper.GetString("jwt_key")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uid := r.Header.Get("internal-userId")
if uid == "" {
tokenString := r.Header.Get("token")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
})
unauthorizedBodyResponse := "{\"success\":false, \"errors\":[\"Unauthorized\"]}"
if token == nil || !token.Valid {
logger.LogError(err)
http.Error(w, unauthorizedBodyResponse, http.StatusForbidden)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
logger.LogError(err)
http.Error(w, unauthorizedBodyResponse, http.StatusForbidden)
return
}
if claims["user_id"] == nil {
http.Error(w, unauthorizedBodyResponse, http.StatusForbidden)
}
// Get context from an HTTP request
ctx := context.WithValue(r.Context(), "userID", fmt.Sprintf("%v", claims["user_id"]))
next.ServeHTTP(w, r.WithContext(ctx))
} else {
ctx := context.WithValue(r.Context(), "userID", uid)
next.ServeHTTP(w, r.WithContext(ctx))
}
})
}