-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshadow_file.go
61 lines (49 loc) · 1.06 KB
/
shadow_file.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
package main
import (
"fmt"
"io"
"io/ioutil"
"strings"
)
type ShadowFile struct {
path string
lines []string
}
func ReadShadowFile(path string) (*ShadowFile, error) {
shadowEntries, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
lines := strings.Split(
strings.TrimRight(string(shadowEntries), "\n"),
"\n",
)
return &ShadowFile{
path: path,
lines: lines,
}, nil
}
func (file *ShadowFile) SetShadow(shadow *Shadow) error {
index, err := file.GetUserIndex(shadow.Username)
if err != nil {
return err
}
file.lines[index] = fmt.Sprintf("%s", shadow)
return nil
}
func (file *ShadowFile) GetUserIndex(userName string) (int, error) {
for index, line := range file.lines {
if strings.HasPrefix(line, userName+":") {
return index, nil
}
}
return 0, fmt.Errorf(
"user %s is not found in shadow file %s", userName, file.path,
)
}
func (file *ShadowFile) Write(writer io.Writer) (int, error) {
return io.WriteString(writer, strings.Join(file.lines, "\n")+"\n")
}
func (file *ShadowFile) GetPath() string {
return file.path
}