-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
71 lines (59 loc) · 1.77 KB
/
jwt.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
package model
import (
"context"
"fmt"
jjwt "github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
"github.com/emadghaffari/virgool/club/conf"
"github.com/emadghaffari/virgool/club/database/redis"
)
var (
// JWT variable instance of intef
JWT intef = &wt{}
)
type intef interface {
Get(ctx context.Context, token string, response interface{}) error
verify(tk string) (string, error)
}
type wt struct{}
// Get, for get values from jwt token
func (j *wt) Get(ctx context.Context, token string, response interface{}) error {
uuid, err := j.verify(token)
if err != nil {
return err
}
if err := redis.Database.Get(ctx, uuid, &response); err != nil {
return err
}
return nil
}
// verify the jwt
func (j *wt) verify(tk string) (string, error) {
token, err := jjwt.Parse(tk, func(token *jjwt.Token) (interface{}, error) {
//Make sure that the token method conform to "SigningMethodHMAC"
if _, ok := token.Method.(*jjwt.SigningMethodHMAC); !ok {
logrus.Warn(fmt.Sprintf("Error in unexpected signing method: %v", token))
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["uuid"])
}
return []byte(conf.GlobalConfigs.JWT.Secret), nil
})
if err != nil {
logrus.Warn(fmt.Sprintf("Error in jwt parse: %s", err))
return "", err
}
if _, ok := token.Claims.(jjwt.Claims); !ok && !token.Valid {
logrus.Warn(fmt.Sprintf("Error in jwt validation: %s", err))
return "", err
}
claims, ok := token.Claims.(jjwt.MapClaims)
if ok && token.Valid {
AccessUUID, ok := claims["uuid"].(string)
if !ok {
logrus.Warn(fmt.Sprintf("Error in claims uuid from client: %s", err))
return "", fmt.Errorf("Error in claims uuid from client")
}
return AccessUUID, nil
}
logrus.Warn(fmt.Sprintf("Error in jwt token verify: %s", err))
return "", err
}