forked from canonical/iot-agent
/
write_auth.go
47 lines (37 loc) · 1.09 KB
/
write_auth.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
package iotauth
import (
"fmt"
"golang.org/x/crypto/bcrypt"
"os"
"path"
"github.com/everactive/iot-agent/pkg/nats"
)
const (
natsAuthPath = "$SNAP_DATA/auth"
)
func GenerateSnapdAuthFiles(usersAndPasswords map[string]string) {
for user, password := range usersAndPasswords {
// Uses the same call to bcrypt that the `nats server passwd` util does
// https://github.com/nats-io/natscli/blob/main/nats/server_mkpasswd_command.go
hashBytes, err := bcrypt.GenerateFromPassword([]byte(password), DefaultCost)
if err != nil {
panic(err)
}
passwordValue := string(hashBytes)
err = StoreNatsParameters(user, passwordValue, path.Join(natsAuthPath, user+".json"))
if err != nil {
fmt.Println("Error storing Nats Parameters:", err)
os.Exit(1)
}
}
}
func StoreNatsParameters(username, hashedPassword, filename string) error {
perms := NewPerms(NewSubjectPermsProp(SS(natsutils.Publish)),
NewSubjectPermsProp(SS(natsutils.Subscribe)))
user := &User{
Hash: hashedPassword,
Name: username,
Permissions: perms,
}
return user.Store(os.ExpandEnv(filename))
}