/
validation.go
90 lines (75 loc) · 2.33 KB
/
validation.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
package contextconfig
/*
import (
"encoding/json"
"fmt"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
)
type claims struct {
Subject string `json:"sub" yaml:"sub"`
Name string `json:"name" yaml:"name"`
Email string `json:"email" yaml:"email"`
}
// GetTokenClaims returns the claims for the raw JWT token.
func GetTokenClaims(rawtoken string) (*claims, error) {
parts := strings.Split(rawtoken, ".")
// There are supposed to be three parts for the token
if len(parts) < 3 {
return nil, fmt.Errorf("Token is invalid: %v", rawtoken)
}
// Access claims in the token
claimBytes, err := jwt.DecodeSegment(parts[1])
if err != nil {
return nil, fmt.Errorf("Failed to decode claims: %v", err)
}
var claims *claims
// Unmarshal claims
err = json.Unmarshal(claimBytes, &claims)
if err != nil {
return nil, fmt.Errorf("Unable to get information from the claims in the token: %v", err)
}
return claims, nil
}
// AddClaimsInfo adds additional claims information to a contextconfig
func AddClaimsInfo(contextCfg *ContextConfig) *ContextConfig {
for i := range contextCfg.Configurations {
if contextCfg.Configurations[i].Token != "" {
claims, err := GetTokenClaims(contextCfg.Configurations[i].Token)
if err != nil {
continue
}
contextCfg.Configurations[i].Identity.Subject = claims.Subject
contextCfg.Configurations[i].Identity.Name = claims.Name
contextCfg.Configurations[i].Identity.Email = claims.Email
}
}
return contextCfg
}
// AddTokenValidity checks and marks if a token is invalid.
func AddTokenValidity(clientContext ClientContext) ClientContext {
var mapClaims jwt.MapClaims
_, _, err := new(jwt.Parser).
ParseUnverified(clientContext.Token, &mapClaims)
if err != nil {
clientContext.Error = err.Error()
clientContext.Name += " (token invalid)"
return clientContext
}
if mapClaims.VerifyExpiresAt(time.Now().Unix(), false) == false {
clientContext.Error = "Token is expired"
clientContext.Name += " (token expired)"
}
return clientContext
}
// MarkInvalidTokens will mark all invalid tokens for a given context config.
func MarkInvalidTokens(contextCfg *ContextConfig) *ContextConfig {
for i := range contextCfg.Configurations {
if contextCfg.Configurations[i].Token != "" {
contextCfg.Configurations[i] = AddTokenValidity(contextCfg.Configurations[i])
}
}
return contextCfg
}
*/