-
Notifications
You must be signed in to change notification settings - Fork 3
/
token.go
67 lines (57 loc) · 1.61 KB
/
token.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
package token
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
// Token struct
type Token struct {
secret string
}
var (
// We are going to expire all tokens at zero hour (Brasilia Standard Time) of the day of the election.
expirationDate = time.Date(2020, 11, 29, 0, 0, 0, 0, time.UTC).Add(-3 * time.Hour).Unix() // 3 is the difference between UTC and BST.
)
// New returns a new token service
func New(secret string) *Token {
return &Token{
secret: secret,
}
}
// GetToken returns a new token
func (t *Token) GetToken(email string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": email,
"exp": expirationDate,
})
return token.SignedString([]byte(t.secret))
}
// IsValid checks if token is valid
func (t *Token) IsValid(auhtorization string) bool {
token, err := jwt.Parse(auhtorization, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("error on validating auth token")
}
return []byte(t.secret), nil
})
if err != nil {
return false
}
return token.Valid
}
// GetClaims transforms the token string into a map with its claims
func GetClaims(auhtorization string) (map[string]string, error) {
token, _ := jwt.Parse(auhtorization, func(token *jwt.Token) (interface{}, error) {
return []byte(""), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok {
claimsMap := make(map[string]string)
for key, value := range claims {
if key != "exp" {
claimsMap[key] = value.(string)
}
}
return claimsMap, nil
}
return nil, fmt.Errorf("could not get claims")
}