-
Notifications
You must be signed in to change notification settings - Fork 0
/
martian_jwt.go
72 lines (57 loc) · 1.45 KB
/
martian_jwt.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
package martian_jwt
import (
"encoding/json"
"log"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/google/martian"
"github.com/google/martian/parse"
"github.com/gorilla/context"
)
func init() {
parse.Register("jwt.TrampolimModifier", trampolimModifierFromJSON)
}
type TrampolimModifier struct {
privateKey string
}
type TrampolimModifierJSON struct {
PrivateKey string `json:"privateKey"`
Scope []parse.ModifierType `json:"scope"`
}
func (m *TrampolimModifier) ModifyRequest(req *http.Request) error {
tokenJWT := req.Header.Get("Authorization")
//if tokenJWT == "" {
// http.Error()
//}
token, err := jwt.Parse(tokenJWT, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, nil
}
return nil, nil
})
if err != nil {
//http.Error()
return nil
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
userId := claims["user_id"].(string)
context.Set(req, "user_id", userId)
log.Printf("Authenticated User: %s\n", userId)
} else {
//http.Error()
return nil
}
return nil
}
func TrampolimNewModifier(privateKey string) martian.RequestModifier {
return &TrampolimModifier{
privateKey: privateKey,
}
}
func trampolimModifierFromJSON(b []byte) (*parse.Result, error) {
msg := &TrampolimModifierJSON{}
if err := json.Unmarshal(b, msg); err != nil {
return nil, err
}
return parse.NewResult(TrampolimNewModifier(msg.PrivateKey), msg.Scope)
}