basic common app packages
This commit is contained in:
48
jwt/jwt.go
Normal file
48
jwt/jwt.go
Normal file
@@ -0,0 +1,48 @@
|
||||
// Copyright 2024 Patial Tech (Ankit Patial).
|
||||
// All rights reserved.
|
||||
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
"log"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Sign(key ed25519.PrivateKey, claims map[string]any, issuer string, d time.Duration) (string, error) {
|
||||
cl := jwt.MapClaims{
|
||||
"iss": issuer,
|
||||
"iat": jwt.NewNumericDate(time.Now().UTC()),
|
||||
"exp": jwt.NewNumericDate(time.Now().Add(d)),
|
||||
}
|
||||
maps.Copy(cl, claims)
|
||||
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, cl)
|
||||
return t.SignedString(key)
|
||||
}
|
||||
|
||||
func Parse(key ed25519.PrivateKey, tokenString string, issuer string) (jwt.MapClaims, error) {
|
||||
token, err := jwt.Parse(
|
||||
tokenString,
|
||||
func(token *jwt.Token) (any, error) {
|
||||
return key.Public(), nil
|
||||
},
|
||||
jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}),
|
||||
jwt.WithIssuer(issuer),
|
||||
jwt.WithIssuedAt(),
|
||||
jwt.WithExpirationRequired(),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
||||
return claims, nil
|
||||
} else {
|
||||
return nil, errors.New("no claims found")
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user