-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.go
51 lines (46 loc) · 1.09 KB
/
common.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
package fibercasbinrest
import (
"encoding/json"
"fmt"
"github.com/golang-jwt/jwt"
)
// Verify JWT
func Verify(token string, secret []byte) bool {
t, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return secret, nil
})
if err != nil {
return false
}
return t.Valid
}
// ParseToken for validate JWT
func ParseToken(token string, secret []byte) (*jwt.Token, error) {
return jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return secret, nil
})
}
// GetValue for get payload from JWT
func GetValue(reqToken string, key string, secretKey []byte) (interface{}, error) {
token, err := ParseToken(reqToken, secretKey)
if err != nil {
return "", err
}
claims, ok := token.Claims.(jwt.MapClaims)
if ok && token.Valid {
return claims[key], nil
}
return "", claims.Valid()
}
// ParseRoles interface to string array
func ParseRoles(roles interface{}) []string {
var rs []interface{}
if b, err := json.Marshal(roles); err == nil {
_ = json.Unmarshal(b, &rs)
}
s := make([]string, len(rs))
for i, v := range rs {
s[i] = fmt.Sprint(v)
}
return s
}