init: 1.0.0

This commit is contained in:
Chang lue Tsen
2025-04-25 12:08:29 +09:00
commit 8addcc584b
1031 changed files with 76472 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
package jwt
import (
"github.com/golang-jwt/jwt/v5"
)
// Option jwt additional data
type Option struct {
Key string
Val any
}
// WithOption returns Option with key-value pairs
func WithOption(key string, val any) Option {
return Option{
Key: key,
Val: val,
}
}
// NewJwtToken Generate and return jwt token with given data.
func NewJwtToken(secretKey string, iat, seconds int64, opt ...Option) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
for _, v := range opt {
claims[v.Key] = v.Val
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
}
// ParseJwtToken Parse jwt token and return claims.
func ParseJwtToken(tokenString, secretKey string) (jwt.MapClaims, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, jwt.ErrTokenInvalidId
}
return claims, nil
}
+22
View File
@@ -0,0 +1,22 @@
package jwt
import (
"testing"
"github.com/golang-jwt/jwt/v5"
"github.com/pkg/errors"
)
// TestNewJwtToken test NewJwtToken function
func TestParseJwtToken(t *testing.T) {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJEZXZpY2VJZCI6IjM4IiwiZXhwIjoxNzE4MTU2OTQ4LCJpYXQiOjE3MTc1NTIxNDgsInVzZXJJZCI6MX0.4W0nga82kNrfwWjkwcgYAWj4fI4iRc-ZftwVbu-a_kI"
secret := "ae0536f9-6450-4606-8e13-5a19ed505da0"
claims, err := ParseJwtToken(token, secret)
if err != nil && !errors.Is(err, jwt.ErrTokenExpired) {
t.Errorf("err: %v", err.Error())
return
}
// parse jwt token success
t.Logf("claims: %v", claims)
}
+18
View File
@@ -0,0 +1,18 @@
package jwt
import "github.com/golang-jwt/jwt/v5"
var (
InvalidToken = jwt.ErrTokenInvalidId
ExpiredToken = jwt.ErrTokenExpired
)
func VerifyToken(tokenString, secret string) error {
_, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return err
}
return nil
}