-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
97 lines (77 loc) · 2.2 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package zube
import (
"crypto/rsa"
"encoding/json"
"log"
"os"
"path/filepath"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/platogo/zube/v2/models"
)
const PrivateKeyFileName = "zube_api_key.pem"
// Returns the correct path to the user's private key file
func PrivateKeyFilePath() string {
homedir, _ := os.UserHomeDir()
return filepath.Join(homedir, ".ssh", PrivateKeyFileName)
}
func GetPrivateKey() (*rsa.PrivateKey, error) {
return GetPrivateKeyWithPath(PrivateKeyFilePath())
}
// Returns the parsed RSA private key from the given path to a .pem file
func GetPrivateKeyWithPath(privateKeyPath string) (*rsa.PrivateKey, error) {
privateKeyFile, err := os.ReadFile(privateKeyPath)
if err != nil {
return nil, err
}
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyFile)
if err != nil {
return nil, err
}
return privateKey, nil
}
// Create a refresh JWT valid for one minute, used to fetch an access token JWT
func GenerateRefreshJWT(clientId string, key *rsa.PrivateKey) (string, error) {
now := time.Now()
claims := &jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate((now.Add(time.Minute))),
Issuer: clientId,
}
if err := claims.Valid(); err != nil {
log.Fatalf("invalid claims: %s", err)
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
return token.SignedString(key)
}
// Returns true if the token is present and not expired
func IsTokenValid(token models.ZubeAccessToken) bool {
if token.AccessToken != "" {
isExp, _ := isAccessTokenExpired(token.AccessToken)
return !isExp
}
return false
}
// Returns true if the JWT is expired
func isAccessTokenExpired(accessToken string) (bool, error) {
token, _, err := new(jwt.Parser).ParseUnverified(accessToken, jwt.MapClaims{})
if err != nil {
log.Fatal(err)
return true, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
log.Fatalf("Can't convert token's claims to standard claims")
}
var expTime time.Time
now := time.Now()
switch exp := claims["exp"].(type) {
case float64:
expTime = time.Unix(int64(exp), 0)
case json.Number:
v, _ := exp.Int64()
expTime = time.Unix(v, 0)
}
isExpired := expTime.Unix() < now.Unix()
return isExpired, nil
}