updated and added some packages

This commit is contained in:
wt committed 2025-05-29 01:11:04 +07:00
1 parent cf3b619b20
commit 6375fc028e
16 files changed
+443 -334

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
package jwt
import (
"maps"
"time"
"github.com/golang-jwt/jwt"
)
func CreateJWT(
secretKey string,
data map[string]any,
ttl time.Duration,
) (string, error) {
claims := jwt.MapClaims{
"exp": time.Now().Add(ttl).Unix(),
"iat": time.Now().Unix(),
"nbf": time.Now().Unix(),
}
maps.Copy(claims, data)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString([]byte(secretKey))
if err != nil {
return "", nil
}
return signedToken, nil
}
+3
View File
@@ -0,0 +1,3 @@
package jwt
const Defaultsecretkey = "secret"
+39
View File
@@ -0,0 +1,39 @@
package jwt
import (
"fmt"
"github.com/golang-jwt/jwt"
)
func VerifyJWT(
tokenString string,
secretKey string,
) (map[string]any, error) {
token, e := jwt.Parse(
tokenString,
func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf(
"unexpexted signing method: %v",
token.Header["alg"],
)
}
return []byte(secretKey), nil
},
)
if e != nil {
return nil, fmt.Errorf("token validation failed: %w", e)
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
result := make(map[string]any)
for key, value := range claims {
if key == "exp" || key == "iat" || key == "nbf" {
continue
}
result[key] = value
}
return result, nil
}
return nil, fmt.Errorf("invalid token")
}