-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup_state.go
More file actions
50 lines (43 loc) · 1.25 KB
/
Copy pathsetup_state.go
File metadata and controls
50 lines (43 loc) · 1.25 KB
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
package main
import (
"encoding/json"
"os"
"path/filepath"
"golang.org/x/crypto/bcrypt"
)
// setupRecord stores reusable daemon choices. The password is bcrypt-hashed, so
// restarting Pulse never requires retaining the plaintext credential.
type setupRecord struct {
Tunnel bool `json:"tunnel"`
Acme bool `json:"acme"`
Domain string `json:"domain,omitempty"`
Notify bool `json:"notify"`
PasswordHash string `json:"passwordHash,omitempty"`
}
func hashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(hash), err
}
func setupPath() string { return filepath.Join(filepath.Dir(statePath()), "setup.json") }
func readSetup() (*setupRecord, error) {
b, err := os.ReadFile(setupPath())
if err != nil {
return nil, err
}
var setup setupRecord
if err := json.Unmarshal(b, &setup); err != nil {
return nil, err
}
if setup.PasswordHash == "" {
return nil, os.ErrInvalid
}
if _, err := bcrypt.Cost([]byte(setup.PasswordHash)); err != nil {
return nil, err
}
return &setup, nil
}
func writeSetup(setup setupRecord) {
b, _ := json.Marshal(setup)
os.MkdirAll(filepath.Dir(setupPath()), 0o700)
os.WriteFile(setupPath(), b, 0o600)
}