40 lines
999 B
Go
40 lines
999 B
Go
package jwt
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"sonarqube-badge/config"
|
|
"sonarqube-badge/store"
|
|
"time"
|
|
)
|
|
|
|
func CreateToken(user store.User, ctx context.Context) (string, error) {
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
|
jwt.MapClaims{
|
|
"username": user.Username,
|
|
"email": user.Email,
|
|
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
|
})
|
|
secret := ctx.Value("config").(config.Config).Secret
|
|
return t.SignedString([]byte(secret))
|
|
}
|
|
|
|
func VerifyToken(jwtString string, ctx context.Context) (*jwt.Token, error) {
|
|
secret := ctx.Value("config").(config.Config).Secret
|
|
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
|
|
}
|