This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwtutil.go
62 lines (51 loc) · 1.7 KB
/
jwtutil.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
package jwtutil
import (
"log"
// "github.com/gorilla/securecookie"
"gopkg.in/gorilla/securecookie.v1"
)
// -----------------------------------------------------------------------------
// Flags is a package flags sample
// in form ready for use with github.com/jessevdk/go-flags
type Flags struct {
AppKey string `long:"psw_session_key" description:"Key to encode user session (default: random key reset on restart)"`
BlockKey string `long:"psw_block_key" default:"T<8rYvXmgLBdND(YW}3QRcLwh4$4P5eq" description:"Key to encode session blocks (16,32 or 62 byte)"`
}
type Cryptor interface {
Decode(name, value string, dst interface{}) error
Encode(name string, value interface{}) (string, error)
}
// App is a package general type
type App struct {
Log *log.Logger
Config *Flags
Cryptor Cryptor
}
// -----------------------------------------------------------------------------
// New creates mailer object
// Configuration should be set via functional options
func New(logger *log.Logger, cfg *Flags, options ...func(a *App) error) (*App, error) {
a := App{Config: cfg, Log: logger}
for _, option := range options {
err := option(&a)
if err != nil {
return nil, err
}
}
if a.Cryptor == nil {
a.setDefaultCryptor()
}
return &a, nil
}
func (a *App) setDefaultCryptor() error {
var hashKeyBytes = []byte(a.Config.AppKey)
if a.Config.AppKey == "" {
hashKeyBytes = securecookie.GenerateRandomKey(32)
a.Log.Print("info: Random key generated. Sessions will be expired on restart")
}
var blockKeyBytes = []byte(a.Config.BlockKey) // "txVzHcURYJrK]UQ:d/YDmx97*Adwb;/%")
var s = securecookie.New(hashKeyBytes, blockKeyBytes)
s.SetSerializer(securecookie.JSONEncoder{})
a.Cryptor = s
return nil
}