-
Notifications
You must be signed in to change notification settings - Fork 0
/
intercepter.go
94 lines (80 loc) · 2.47 KB
/
intercepter.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
package intercepter
import (
"context"
"fmt"
"github.com/KonstantinGasser/datalab/common"
"github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// TODO: must go in some ENV
type CtxKey string
const (
secretUser = "super_secure"
atuhCtxKey CtxKey = "user"
)
var (
ErrNoJwtFound = fmt.Errorf("could not find JWT in meta-context")
ErrNotAuthenticated = fmt.Errorf("user is not authenticated")
ErrJWTParse = fmt.Errorf("could not parse jwt token")
ErrCorruptJWT = fmt.Errorf("jwt could not be parsed (JWT might be corrupted)")
ErrExpiredJWT = fmt.Errorf("provided JWT has expired")
)
func WithUnary(middleware grpc.UnaryServerInterceptor) grpc.ServerOption {
return grpc.UnaryInterceptor(middleware)
}
func WithJwtAuth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// validating the app token must be excluded from user-JWT middelware since
// the call for validation is send by a unknown client who uses the app token
// to authenticate.
if info.FullMethod == "/issuer_proto.AppToken/Validate" {
return handler(ctx, req)
}
logrus.Info("[intercepter.WithJwtAuth] receiced request\n")
authedUser, err := validateJWT(ctx)
if err != nil {
return nil, err
}
authCtx := context.WithValue(ctx, "user", authedUser)
resp, err := handler(authCtx, req)
return resp, err
}
func validateJWT(ctx context.Context) (*common.AuthedUser, error) {
meta, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, fmt.Errorf("could not find correct context details")
}
accessToken, ok := meta["authorization"]
if !ok {
return nil, ErrNoJwtFound
}
token, err := verifyToken(accessToken[0], secretUser)
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok && !token.Valid {
return nil, ErrNotAuthenticated
}
if err := claims.Valid(); err != nil {
return nil, ErrExpiredJWT
}
return &common.AuthedUser{
Uuid: claims["sub"].(string),
Organization: claims["orgn"].(string),
Username: claims["uname"].(string),
}, nil
}
func verifyToken(tokenString, secret string) (*jwt.Token, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, ErrCorruptJWT
}
return []byte(secret), nil
})
if err != nil {
return nil, ErrJWTParse
}
return token, nil
}