summaryrefslogtreecommitdiff
path: root/store/secret.go
blob: c17443a00db840997cafbda95cd16bf61c8f460e (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
57
58
59
package store

import (
	"crypto/rand"
	log "github.com/sirupsen/logrus"
	"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 {
			log.Fatalf("Error while generating secret, %s", err)
			log.Exit(1)
		} 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 {
			log.Fatalf("Error reading association file of secret %s, %s", secret, err)
			os.Exit(1)
		} 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 {
		log.Fatalf("Error disassociating secret %s, %s", secret, err)
		os.Exit(1)
	}
}