-
Notifications
You must be signed in to change notification settings - Fork 250
/
util.go
79 lines (67 loc) · 1.46 KB
/
util.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
package util
import (
"encoding/json"
"regexp"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
)
// Min returns minimum of two ints
func Min(a, b int) int {
if a < b {
return a
}
return b
}
var (
jwtRe = regexp.MustCompile(`^Bearer ([\w-\.]+)$`)
)
// MakeWsURL converts http:// to ws://
func MakeWsURL(url string) string {
if strings.HasPrefix(url, "http") {
return "ws" + strings.TrimPrefix(url, "http")
}
return url
}
func ExtractJWT(authHeader string) string {
c := jwtRe.FindStringSubmatch(authHeader)
if len(c) != 2 {
return ""
}
return c[1]
}
func GetTokenExp(tokenString string) time.Time {
token, err := jwt.Parse(tokenString, nil)
if err.(*jwt.ValidationError).Errors == jwt.ValidationErrorMalformed {
return time.Time{}
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return time.Time{}
}
exp, ok := claims["exp"]
if !ok {
return time.Time{}
}
switch exp := exp.(type) {
case float64:
return time.Unix(int64(exp), 0)
case json.Number:
v, _ := exp.Int64()
return time.Unix(v, 0)
}
return time.Time{}
}
// verify token is valid, and also exp and nbf on token
func IsTokenUsable(tokenString string) bool {
token, err := jwt.Parse(tokenString, nil)
if err.(*jwt.ValidationError).Errors == jwt.ValidationErrorMalformed {
return false
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return false
}
now := time.Now().Unix()
return claims.VerifyExpiresAt(now, true) && claims.VerifyNotBefore(now, true)
}