-
Notifications
You must be signed in to change notification settings - Fork 43
/
auth.go
77 lines (61 loc) · 1.92 KB
/
auth.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
package authjwt
import (
"context"
"fmt"
"time"
"github.com/cloud-barista/cb-tumblebug/src/api/grpc/logger"
"github.com/golang-jwt/jwt/v4"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func validateToken(ctx context.Context) (bool, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return false, status.Errorf(codes.InvalidArgument, "Retrieving metadata is failed")
}
authHeader, ok := md["authorization"]
if !ok {
return false, status.Errorf(codes.Unauthenticated, "Authorization jwt token is not supplied")
}
tokenStr := authHeader[0]
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtKey), nil
})
if err != nil {
return false, status.Errorf(codes.Unauthenticated, "Parsing jwt token is failed")
}
if token.Valid {
logger := logger.NewLogger()
var tokenInfo string = "{"
for key, val := range claims {
if key == "expire" {
if getTokenRemainingValidity(val) < 0 {
return false, status.Errorf(codes.Unauthenticated, "token is expired")
}
var timestamp interface{} = val
t := time.Unix(int64(timestamp.(float64)), 0)
tokenInfo = tokenInfo + fmt.Sprintf(" %s: %d-%02d-%02dT%02d:%02d:%02d, remainder seconds: %d,", key,
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second(),
getTokenRemainingValidity(val),
)
} else {
tokenInfo = tokenInfo + fmt.Sprintf(" %s: %v,", key, val)
}
}
tokenInfo = tokenInfo + " }"
logger.Debug("token parsing result : ", tokenInfo)
return true, nil
}
return false, status.Errorf(codes.Unauthenticated, "Authorization is failed")
}
func getTokenRemainingValidity(timestamp interface{}) int {
if validity, ok := timestamp.(float64); ok {
tm := time.Unix(int64(validity), 0)
remainder := tm.Sub(time.Now())
return int(remainder.Seconds())
}
return -1
}