forked from gofiber/contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
80 lines (63 loc) · 2.07 KB
/
helpers.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package pasetoware
import (
"crypto/ed25519"
"errors"
"time"
"github.com/gofiber/fiber/v2"
"github.com/o1egl/paseto"
)
const (
LookupHeader = "header"
LookupCookie = "cookie"
LookupQuery = "query"
LookupParam = "param"
// DefaultContextKey is the Default key used by this middleware to store decrypted token
DefaultContextKey = "auth-token"
)
type TokenPurpose int
const (
PurposeLocal TokenPurpose = iota
PurposePublic
)
var (
ErrExpiredToken = errors.New("token has expired")
ErrMissingToken = errors.New("missing PASETO token")
ErrIncorrectTokenPrefix = errors.New("missing prefix for PASETO token")
ErrDataUnmarshal = errors.New("can't unmarshal token data to Payload type")
pasetoObject = paseto.NewV2()
)
type acquireToken func(c *fiber.Ctx, key string) string
// PayloadValidator Function that receives the decrypted payload and returns an interface and an error
// that's a result of validation logic
type PayloadValidator func(decrypted []byte) (interface{}, error)
// PayloadCreator Signature of a function that generates a payload token
type PayloadCreator func(key []byte, dataInfo string, duration time.Duration, purpose TokenPurpose) (string, error)
// Acquire Token methods
func acquireFromHeader(c *fiber.Ctx, key string) string {
return c.Get(key)
}
func acquireFromQuery(c *fiber.Ctx, key string) string {
return c.Query(key)
}
func acquireFromParams(c *fiber.Ctx, key string) string {
return c.Params(key)
}
func acquireFromCookie(c *fiber.Ctx, key string) string {
return c.Cookies(key)
}
// Public helper functions
// CreateToken Create a new Token Payload that will be stored in PASETO
func CreateToken(key []byte, dataInfo string, duration time.Duration, purpose TokenPurpose) (string, error) {
payload, err := NewPayload(dataInfo, duration)
if err != nil {
return "", err
}
switch purpose {
case PurposeLocal:
return pasetoObject.Encrypt(key, payload, nil)
case PurposePublic:
return pasetoObject.Sign(ed25519.PrivateKey(key), payload, nil)
default:
return pasetoObject.Encrypt(key, payload, nil)
}
}