62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package security
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"time"
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
)
|
|
|
|
var jwtSecret []byte
|
|
|
|
type Claims struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
jwt.StandardClaims
|
|
}
|
|
|
|
// EncodeMD5 md5 encryption
|
|
func EncodeMD5(value string) string {
|
|
m := md5.New()
|
|
m.Write([]byte(value))
|
|
|
|
return hex.EncodeToString(m.Sum(nil))
|
|
}
|
|
|
|
// GenerateToken generate tokens used for auth
|
|
func GenerateToken(username, password string) (string, error) {
|
|
nowTime := time.Now()
|
|
expireTime := nowTime.Add(3 * time.Hour)
|
|
|
|
claims := Claims{
|
|
EncodeMD5(username),
|
|
EncodeMD5(password),
|
|
jwt.StandardClaims{
|
|
ExpiresAt: expireTime.Unix(),
|
|
Issuer: "gin-server",
|
|
},
|
|
}
|
|
|
|
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
token, err := tokenClaims.SignedString(jwtSecret)
|
|
|
|
return token, err
|
|
}
|
|
|
|
// ParseToken parsing token
|
|
func ParseToken(token string) (*Claims, error) {
|
|
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return jwtSecret, nil
|
|
})
|
|
|
|
if tokenClaims != nil {
|
|
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
|
|
return claims, nil
|
|
}
|
|
}
|
|
|
|
return nil, err
|
|
}
|
|
|