-
Notifications
You must be signed in to change notification settings - Fork 0
/
paseto_maker.go
43 lines (34 loc) · 1.05 KB
/
paseto_maker.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 (
"fmt"
"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
}
// CreateToken creates a new token for a specific username and duration
func (maker *PasetoMaker) CreateToken(payload Payloads, opt ...interface{}) (string, error) {
return maker.paseto.Encrypt(maker.symmetricKey, payload, opt)
}
// VerifyToken checks if the token is valid or not
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
}