-
Notifications
You must be signed in to change notification settings - Fork 471
/
user_group_unix.go
73 lines (60 loc) · 1.21 KB
/
user_group_unix.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
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package system
import (
"bufio"
"io"
"os"
"sort"
"strconv"
"strings"
)
func groupsForUser(user string, pgid int, grp io.Reader) ([]string, error) {
s := bufio.NewScanner(grp)
out := []string{}
for s.Scan() {
if err := s.Err(); err != nil {
return nil, err
}
text := s.Text()
if text == "" {
continue
}
// see: man 5 group
// group_name:password:GID:user_list
// Name:Pass:Gid:List
// root:x:0:root
// adm:x:4:root,adm,daemon
parts := strings.Split(text, ":")
if len(parts) != 4 {
continue
}
gid, err := strconv.Atoi(parts[2])
if err == nil {
if gid == pgid {
out = append(out, parts[0])
continue
}
}
for _, g := range strings.Split(parts[3], ",") {
if g == user {
out = append(out, parts[0])
continue
}
}
}
sort.Strings(out)
return out, nil
}
func (u *DefUser) Groups() ([]string, error) {
grp, err := os.Open("/etc/group")
if err != nil {
return nil, err
}
defer grp.Close()
pgid, err := u.GID()
if err != nil {
return nil, err
}
return groupsForUser(u.username, pgid, grp)
}