-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
57 lines (45 loc) · 1.12 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
package token
import (
"crypto/md5"
"encoding/hex"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/jameshwc/Million-Singer/conf"
)
type Claims struct {
Username string
Password string
jwt.StandardClaims
}
const expire = 3 * time.Hour
func Generate(username, password string) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(expire)
claims := Claims{
encodeMD5(username),
encodeMD5(password),
jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "million-singer",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(conf.ServerConfig.JwtSecret)
return token, err
}
func Parse(token string) (*Claims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return conf.ServerConfig.JwtSecret, nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}
func encodeMD5(s string) string {
m := md5.New()
m.Write([]byte(s))
return hex.EncodeToString(m.Sum(nil))
}