-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
109 lines (82 loc) · 2.14 KB
/
config.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
package config
import (
"bytes"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"log"
"os"
"github.com/Tympanix/artoodetoo/data"
"github.com/Tympanix/artoodetoo/types"
"github.com/foomo/htpasswd"
)
// Port is the port which the application listens on
var Port int
// Secret is the crypto secret for the application
var Secret []byte
// Passwords is used to log into the application
var Passwords htpasswd.HashedPasswords
// Config is the configuration object for the application
type Config struct {
Port int `json:"port"`
Secret string `json:"secret"`
}
// Parse parses the application configuration file
func Parse(args types.AppArgs) {
Port = args.Port()
data.TmpDir = args.TmpDirPath()
file, err := os.Open(args.SecretPath())
if err != nil {
log.Fatal(err)
}
buf := new(bytes.Buffer)
if _, err = buf.ReadFrom(file); err != nil {
log.Fatal(err)
}
Secret = buf.Bytes()
pass, err := htpasswd.ParseHtpasswdFile(args.HtpasswdPath())
if err != nil {
log.Fatal(err)
}
Passwords = pass
}
// AddUser adds a new user to the system
func AddUser(path string, username string, password string) error {
return htpasswd.SetPassword(path, username, password, htpasswd.HashBCrypt)
}
// DeleteUser removes a user from the application
func DeleteUser(path string, username string) error {
return htpasswd.RemoveUser(path, username)
}
// GetUsers returns the users of the application
func GetUsers(path string) (htpasswd.HashedPasswords, error) {
return htpasswd.ParseHtpasswdFile(path)
}
// GenerateSecret generates a new application secret
func GenerateSecret(path string, length int, force bool) (err error) {
min := 64
max := 1 << 14
if length < min || length > max {
return fmt.Errorf("Length must be between %v and %v bytes", min, max)
}
if _, err = os.Stat(path); err == nil {
if !force {
return errors.New("File already exists. Use force argument to overwrite")
}
}
file, err := os.Create(path)
if err != nil {
return
}
defer file.Close()
b := make([]byte, length)
_, err = rand.Read(b)
if err != nil {
return
}
if err = binary.Write(file, binary.LittleEndian, b); err != nil {
return
}
return nil
}