summaryrefslogtreecommitdiff
path: root/store/secret.go
blob: 5941c2f75dfe2414aaecc141f371edc988cb4ed5 (plain)
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
package store

import (
	"crypto/rand"
	"fmt"
	"math/big"
	"os"
)

// SecretNew generates a new user secret.
func (s *Store) SecretNew() string {
	secret := make([]byte, 64)
	for i := 0; i < 64; i++ {
		if n, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters)))); err != nil {
			s.fatalClose(fmt.Sprintf("Error generating secret, %s", err))
		} else {
			secret[i] = letters[n.Int64()]
		}
	}
	return string(secret)
}

// SecretLookup looks up an user from a secret.
func (s *Store) SecretLookup(secret string) User {
	if !secretRegex.MatchString(secret) || !s.file(s.SecretPath(secret)) {
		return User{}
	}
	if !s.Compat {
		return s.user(s.SecretPath(secret) + "/" + infoJson)
	} else {
		if path, err := os.ReadFile(s.SecretPath(secret)); err != nil {
			s.fatalClose(fmt.Sprintf("Error reading association file of secret %s, %s", secret, err))
		} else {
			return s.user(string(path) + "/" + infoJson)
		}
	}
	return User{}
}

// SecretAssociate associates a secret with a user.
func (s *Store) SecretAssociate(secret, flake string) {
	if s.file(s.SecretPath(secret)) {
		return
	}
	s.link("../users/"+flake, s.SecretPath(secret))
}

// SecretDisassociate disassociates a secret.
func (s *Store) SecretDisassociate(secret string) {
	if !s.file(s.SecretPath(secret)) {
		return
	}
	if err := os.Remove(s.SecretPath(secret)); err != nil {
		s.fatalClose(fmt.Sprintf("Error disassociating secret %s, %s", secret, err))
	}
}