-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_service.go
94 lines (78 loc) · 2.04 KB
/
jwt_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package service
import (
"context"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/reinanhs/golang-web-api-structure/internal/core/config"
"strconv"
"time"
)
type JWTService interface {
GenerateToken(id uint) (string, error)
ValidateToken(token string) bool
GetIDFromToken(t string) (int64, error)
}
type jwtService struct {
ctx context.Context
secretKey string
issuer string
expiresIn int
}
type Claim struct {
Sum uint `json:"sum"`
jwt.StandardClaims
}
//NewJWTService is creates a new instance of JWTService
func NewJWTService(ctx context.Context) JWTService {
return &jwtService{
ctx: ctx,
secretKey: ctx.Value("config").(*config.AppConfig).JwtSecret,
expiresIn: ctx.Value("config").(*config.AppConfig).JwtExpiresIn,
issuer: "auth-login",
}
}
func (s *jwtService) GenerateToken(id uint) (string, error) {
claim := &Claim{
id,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * time.Duration(s.expiresIn)).Unix(),
Issuer: s.issuer,
IssuedAt: time.Now().Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
t, err := token.SignedString([]byte(s.secretKey))
if err != nil {
return "", err
}
return t, nil
}
func (s *jwtService) ValidateToken(token string) bool {
_, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if _, isValid := t.Method.(*jwt.SigningMethodHMAC); !isValid {
return nil, fmt.Errorf("invalid token: %v", token)
}
return []byte(s.secretKey), nil
})
return err == nil
}
func (s *jwtService) GetIDFromToken(t string) (int64, error) {
token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
if _, isvalid := token.Method.(*jwt.SigningMethodHMAC); !isvalid {
return nil, fmt.Errorf("invalid Token: %v", t)
}
return []byte(s.secretKey), nil
})
if err != nil {
return 0, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
id := fmt.Sprintf("%v", claims["sum"])
val, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return 0, err
}
return val, nil
}
return 0, err
}