Initial backend import
This commit is contained in:
49
internal/auth/jwt_user.go
Normal file
49
internal/auth/jwt_user.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
const IssuerAdmin = "ark-admin"
|
||||
const IssuerUserWallet = "ark-user"
|
||||
|
||||
type UserWalletClaims struct {
|
||||
Wallet string `json:"wallet"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func SignUserWallet(secret, wallet string, ttl time.Duration) (string, error) {
|
||||
claims := UserWalletClaims{
|
||||
Wallet: wallet,
|
||||
Role: "user",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Issuer: IssuerUserWallet,
|
||||
Subject: wallet,
|
||||
},
|
||||
}
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
|
||||
return t.SignedString([]byte(secret))
|
||||
}
|
||||
|
||||
func ParseUserWallet(secret, token string) (*UserWalletClaims, error) {
|
||||
claims := &UserWalletClaims{}
|
||||
parsed, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !parsed.Valid || claims.Issuer != IssuerUserWallet {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
Reference in New Issue
Block a user