2023-03-14 17:39:40 +07:00
|
|
|
package token
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/aead/chacha20poly1305"
|
|
|
|
"github.com/o1egl/paseto"
|
|
|
|
)
|
|
|
|
|
|
|
|
type PasetoMaker struct {
|
|
|
|
paseto *paseto.V2
|
|
|
|
symmetricKey []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPasetoMaker(symmetricKey string) (Maker, error) {
|
|
|
|
if len(symmetricKey) != chacha20poly1305.KeySize {
|
|
|
|
return nil, fmt.Errorf("invalid key size: must be exactly %d characters", chacha20poly1305.KeySize)
|
|
|
|
}
|
|
|
|
|
|
|
|
maker := &PasetoMaker{
|
|
|
|
paseto: paseto.NewV2(),
|
|
|
|
symmetricKey: []byte(symmetricKey),
|
|
|
|
}
|
|
|
|
|
|
|
|
return maker, nil
|
|
|
|
}
|
|
|
|
|
2023-03-16 12:21:41 +07:00
|
|
|
func (maker *PasetoMaker) CreateToken(email string, merchant_id string, duration time.Duration) (string, *Payload, error) {
|
2023-03-15 15:00:36 +07:00
|
|
|
payload, err := NewPayload(email, merchant_id, duration)
|
2023-03-14 17:39:40 +07:00
|
|
|
if err != nil {
|
2023-03-16 12:21:41 +07:00
|
|
|
return "", payload, err
|
2023-03-14 17:39:40 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
token, err := maker.paseto.Encrypt(maker.symmetricKey, payload, nil)
|
2023-03-16 12:21:41 +07:00
|
|
|
return token, payload, err
|
2023-03-14 17:39:40 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (maker *PasetoMaker) VerifyToken(token string) (*Payload, error) {
|
|
|
|
payload := &Payload{}
|
|
|
|
|
|
|
|
err := maker.paseto.Decrypt(token, maker.symmetricKey, payload, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, ErrInvalidToken
|
|
|
|
}
|
|
|
|
|
|
|
|
err = payload.Valid()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return payload, nil
|
|
|
|
}
|