37 lines
791 B
Go
37 lines
791 B
Go
package security
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"time"
|
|
)
|
|
|
|
type JwtClaims struct {
|
|
}
|
|
|
|
func CreateToken(username string) (string, error) {
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
|
jwt.MapClaims{
|
|
"username": username,
|
|
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
|
})
|
|
return t.SignedString([]byte("secret"))
|
|
}
|
|
|
|
func VerifyToken(jwtString string) (*jwt.Token, error) {
|
|
parse, err := jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte("secret"), nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if !parse.Valid {
|
|
return nil, errors.New("invalid token")
|
|
}
|
|
if time.Unix(int64(parse.Claims.(jwt.MapClaims)["exp"].(float64)), 0).Before(time.Now()) {
|
|
return nil, errors.New("token is expired")
|
|
}
|
|
|
|
return parse, nil
|
|
}
|