-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_gl.go
78 lines (58 loc) · 1.45 KB
/
jwt_gl.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
package jwt_gl
import (
"errors"
"os"
"time"
error_message "github.com/Almazatun/golephant/pkg/common/error-message"
"github.com/dgrijalva/jwt-go"
)
var secretKey = os.Getenv("JWT_SECRET_KEY")
var SET_COOKIE_PATH = os.Getenv("SET_COOKIE_PATH")
var JWT_KEY_BYTE = []byte(secretKey)
const (
HTTP_COOKIE = "Token"
)
type Claims struct {
Email string `json:"email"`
jwt.StandardClaims
}
type JWT struct {
Token string
ExperationTime time.Time
}
func IsValidJWTStr(tokenStr string) (res bool, err error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenStr, claims,
func(t *jwt.Token) (interface{}, error) {
return JWT_KEY_BYTE, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
newErr := errors.New(error_message.UNAUTHORIZED)
return false, newErr
}
errMes := "Bad request"
newErr := errors.New(errMes)
return false, newErr
}
if !token.Valid {
newErr := errors.New(error_message.UNAUTHORIZED)
return false, newErr
}
return true, nil
}
func GenerateJWTStr(email string) (res *JWT, err error) {
experationTimeJWT := time.Now().Add(time.Minute * 60)
claims := Claims{
Email: email,
StandardClaims: jwt.StandardClaims{
ExpiresAt: experationTimeJWT.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(JWT_KEY_BYTE)
if err != nil {
return nil, err
}
return &JWT{Token: tokenString, ExperationTime: experationTimeJWT}, nil
}