-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsalt.go
85 lines (61 loc) · 1.73 KB
/
salt.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
package salt
import (
"encoding/json"
"errors"
"github.com/ibmendoza/cryptohelper"
"time"
)
func GenerateKey() (string, error) {
return cryptohelper.RandomKey()
}
func ExpiresInSeconds(d time.Duration) int64 {
return time.Now().Add(time.Second * d).Unix()
}
func ExpiresInMinutes(d time.Duration) int64 {
return time.Now().Add(time.Minute * d).Unix()
}
func ExpiresInHours(d time.Duration) int64 {
return time.Now().Add(time.Hour * d).Unix()
}
func ExpiresInDays(d time.Duration) int64 {
return time.Now().Add(24 * time.Hour * d).Unix()
}
func ExpiresInMonths(d time.Duration) int64 {
return time.Now().Add(30 * 24 * time.Hour * d).Unix()
}
//returns the corresponding claims as map[string]interface{} if token is valid
func Verify(token, naclKey string) (map[string]interface{}, error) {
claims, err := cryptohelper.SecretboxDecrypt(token, naclKey)
if err != nil {
return nil, errors.New("Error decrypting claims")
}
mapClaims := make(map[string]interface{})
if naclKey != "" {
if err := json.Unmarshal([]byte(claims), &mapClaims); err != nil {
return nil, err
}
}
//if exp is not set, expiry is 0 (meaning no expiry)
expiry, ok := mapClaims["exp"].(float64)
if ok {
if float64(timeNow()) > expiry {
return nil, errors.New("Token is expired")
}
}
return mapClaims, nil
}
func Sign(claims map[string]interface{}, naclKey string) (string, error) {
byteClaims, err := json.Marshal(claims)
if err != nil {
return "", errors.New("Error in JSON marshal of claims")
}
var b64claims string
b64claims, err = cryptohelper.SecretboxEncrypt(string(byteClaims), naclKey)
if err != nil {
return "", errors.New("Error encrypting claims")
}
return b64claims, nil
}
func timeNow() int64 {
return time.Now().Unix()
}