-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpayload.go
43 lines (35 loc) · 790 Bytes
/
payload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package token
import (
"errors"
"time"
"github.com/google/uuid"
)
var (
ErrExpiredToken = errors.New("token has already expired")
ErrInvalidToken = errors.New("token is invalid")
)
type Payload struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
IssuedAt time.Time `json:"issued_at"`
Expiry time.Time `json:"expired_at"`
}
func NewPayload(username string, duration time.Duration) (*Payload, error) {
tokenID, err := uuid.NewRandom()
if err != nil {
return nil, err
}
payload := &Payload{
ID: tokenID,
Username: username,
IssuedAt: time.Now(),
Expiry: time.Now().Add(duration),
}
return payload, nil
}
func (payload *Payload) Valid() error {
if time.Now().After(payload.Expiry) {
return ErrExpiredToken
}
return nil
}