-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication.service.go
54 lines (46 loc) · 1.11 KB
/
authentication.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
package services
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v4"
)
type AuthenticationClaims struct {
email string
isUser bool
jwt.StandardClaims
}
type AuthenticationService struct {
secret string
}
func NewAuthenticationService() IAuthenticationService {
return &AuthenticationService{secret: "hgdhgdgfwdegwyhdfew"}
}
func (a *AuthenticationService) SignToken(email string, isUser bool) string {
claims := &AuthenticationClaims{
email,
isUser,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 48).Unix(),
IssuedAt: time.Now().Unix(),
Issuer: "X_X",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, err := token.SignedString([]byte(a.secret))
fmt.Println(t, err)
if err == nil {
return t
}
return ""
}
func (a *AuthenticationService) ValidateToken(token string) (*jwt.Token, error) {
return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, nil
}
if claims, ok := t.Claims.(jwt.MapClaims); ok && t.Valid {
fmt.Println(claims)
}
return []byte(a.secret), nil
})
}