naise_pos/token/payload.go

45 lines
897 B
Go
Raw Permalink Normal View History

2023-03-14 17:39:40 +07:00
package token
import (
"errors"
"time"
"github.com/google/uuid"
)
var (
ErrExpiredToken = errors.New("token has expired")
ErrInvalidToken = errors.New("token is invalid")
)
type Payload struct {
2023-03-15 15:00:36 +07:00
ID uuid.UUID `json:"id"`
Email string `json:"email"`
MerchantID uuid.UUID `json:"merchant_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiredAt time.Time `json:"expired_at"`
2023-03-14 17:39:40 +07:00
}
2023-03-15 15:00:36 +07:00
func NewPayload(email string, merchant_id string, duration time.Duration) (*Payload, error) {
2023-03-14 17:39:40 +07:00
tokenID, err := uuid.NewRandom()
if err != nil {
return nil, err
}
payload := &Payload{
2023-03-15 15:00:36 +07:00
ID: tokenID,
Email: email,
MerchantID: uuid.MustParse(merchant_id),
IssuedAt: time.Now(),
ExpiredAt: time.Now().Add(duration),
2023-03-14 17:39:40 +07:00
}
return payload, nil
}
func (payload *Payload) Valid() error {
if time.Now().After(payload.ExpiredAt) {
return ErrExpiredToken
}
return nil
}