sonarqube-badges/security/jwt/jwt.go

41 lines
999 B
Go
Raw Permalink Normal View History

2025-03-15 01:49:52 +01:00
package jwt
2025-03-13 08:25:39 +01:00
import (
2025-03-15 01:49:52 +01:00
"context"
2025-03-13 08:25:39 +01:00
"errors"
"github.com/golang-jwt/jwt/v5"
2025-03-15 01:49:52 +01:00
"sonarqube-badge/config"
"sonarqube-badge/store"
2025-03-13 08:25:39 +01:00
"time"
)
2025-03-15 01:49:52 +01:00
func CreateToken(user store.User, ctx context.Context) (string, error) {
2025-03-13 08:25:39 +01:00
t := jwt.NewWithClaims(jwt.SigningMethodHS256,
jwt.MapClaims{
2025-03-15 01:49:52 +01:00
"username": user.Username,
"email": user.Email,
2025-03-13 08:25:39 +01:00
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
2025-03-15 01:49:52 +01:00
secret := ctx.Value("config").(config.Config).Secret
return t.SignedString([]byte(secret))
2025-03-13 08:25:39 +01:00
}
2025-03-15 01:49:52 +01:00
func VerifyToken(jwtString string, ctx context.Context) (*jwt.Token, error) {
secret := ctx.Value("config").(config.Config).Secret
2025-03-13 08:25:39 +01:00
parse, err := jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
2025-03-15 01:49:52 +01:00
return []byte(secret), nil
2025-03-13 08:25:39 +01:00
})
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
}