hiling_go/util/token/payload.go

37 lines
708 B
Go
Raw Permalink Normal View History

2023-09-08 22:25:22 +07:00
package token
import (
"errors"
"time"
)
var (
ErrExpiredToken = errors.New("token has expired")
ErrInvalidToken = errors.New("token is invalid")
)
type Payload struct {
2023-09-21 21:38:41 +07:00
Username string `json:"email"`
2023-09-08 22:25:22 +07:00
UserID int `json:"user_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiredAt time.Time `json:"expired_at"`
}
2023-09-21 21:38:41 +07:00
func NewPayload(username string, user_id int, duration time.Duration) (*Payload, error) {
2023-09-08 22:25:22 +07:00
payload := &Payload{
2023-09-21 21:38:41 +07:00
Username: username,
2023-09-08 22:25:22 +07:00
UserID: user_id,
IssuedAt: time.Now(),
ExpiredAt: time.Now().Add(duration),
}
return payload, nil
}
func (payload *Payload) Valid() error {
if time.Now().After(payload.ExpiredAt) {
return ErrExpiredToken
}
return nil
}