/
jwtconfig.go
111 lines (88 loc) · 2.25 KB
/
jwtconfig.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package state
import (
"crypto/rand"
"crypto/rsa"
"errors"
"github.com/function61/eventhorizon/pkg/ehevent"
"github.com/function61/gokit/fileexists"
"github.com/function61/gokit/httpauth"
"github.com/function61/gokit/jsonfile"
"github.com/function61/gokit/storedpassword"
"github.com/function61/passitron/pkg/domain"
"time"
)
const (
configFilename = "config.json"
)
type JwtConfig struct {
SigningKey string `json:"jwt_private_key"`
AuthenticatorKey string `json:"jwt_public_key"`
}
func readAndValidateJwtConfig() (*JwtConfig, error) {
cfg := &JwtConfig{}
if err := jsonfile.Read(configFilename, cfg, true); err != nil {
return nil, err
}
if cfg.AuthenticatorKey == "" {
return nil, errors.New("AuthenticatorKey not set")
}
if cfg.SigningKey == "" {
return nil, errors.New("SigningKey not set")
}
return cfg, nil
}
func writeJwtConfig(cfg *JwtConfig) error {
return jsonfile.Write(configFilename, cfg)
}
func InitConfig(adminUsername string, adminPassword string) error {
exists, err := fileexists.Exists(configFilename)
if err != nil {
return err
}
if exists {
return errors.New("config file already exists")
}
privKeyPem, pubKeyPem, err := httpauth.GenerateKey()
if err != nil {
return err
}
cfg := &JwtConfig{
SigningKey: string(privKeyPem),
AuthenticatorKey: string(pubKeyPem),
}
if err := writeJwtConfig(cfg); err != nil {
return err
}
state, err := New(nil)
if err != nil {
return err
}
return createAdminUser(adminUsername, adminPassword, state)
}
func createAdminUser(adminUsername string, adminPassword string, state *AppState) error {
storedPassword, err := storedpassword.Store(
adminPassword,
storedpassword.CurrentBestDerivationStrategy)
if err != nil {
return err
}
meta := ehevent.Meta(time.Now(), "2")
userCreated := domain.NewUserCreated(
meta.UserId,
adminUsername,
meta)
password := domain.NewUserPasswordUpdated(
meta.UserId,
string(storedPassword),
false,
meta)
privKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
}
decryptionKeyChanged, err := ExportPrivateKeyWithPassword(privKey, adminPassword, meta)
if err != nil {
return err
}
return state.EventLog.Append([]ehevent.Event{userCreated, password, decryptionKeyChanged})
}