-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_service.go
70 lines (55 loc) · 1.52 KB
/
token_service.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
package main
import (
"time"
"github.com/dgrijalva/jwt-go"
pb "github.com/seidu626/abk-user-service/proto/auth"
)
var (
// Define a secure key string used
// as a salt when hashing our tokens.
// Please make your own way more secure than this,
// use a randomly generated md5 hash or something.
key = []byte("mySuperSecretKeyLol")
)
// CustomClaims is our custom metadata, which will be hashed
// and sent as the second segment in our JWT
type CustomClaims struct {
User *pb.User
jwt.StandardClaims
}
type Authable interface {
Decode(token string) (*CustomClaims, error)
Encode(user *pb.User) (string, error)
}
type TokenService struct {
repo Repository
}
// Decode a token string into a token object
func (srv *TokenService) Decode(tokenString string) (*CustomClaims, error) {
// Parse the token
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
// Validate the token and return the custom claims
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
} else {
return nil, err
}
}
// Encode a claim into a JWT
func (srv *TokenService) Encode(user *pb.User) (string, error) {
expireToken := time.Now().Add(time.Hour * 72).Unix()
// Create the Claims
claims := CustomClaims{
user,
jwt.StandardClaims{
ExpiresAt: expireToken,
Issuer: "shippy.user",
},
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign token and return
return token.SignedString(key)
}