about summary refs log tree commit diff stats
path: root/users.go
blob: 1f8cfb39177d3f20afd9324886369b7eebf24095 (plain) (blame)
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
package main

import (
	"fmt"
	"os/exec"
	"strings"
)

// Users handles the /<format>/users endpoint.
// Responds with information on the system's users.
func usersQuery(format string) ([]byte, error) {
	ls, err := exec.Command("/bin/ls", "/home").Output()
	if err != nil {
		return nil, fmt.Errorf("Users Query: %w", err)
	}

	users := strings.Fields(string(ls))

	if format == "plain" {
		var out []string
		for _, e := range users {
			if strings.HasPrefix(e, ".") || strings.HasPrefix(e, "_") {
				continue
			}
			out = append(out, e)
		}
		outstring := strings.Join(out, "\n")
		outstring += "\n"
		return []byte(outstring), nil
	}

	out := `{
	"users": [
`
	for i, e := range users {
		if strings.HasPrefix(e, ".") || strings.HasPrefix(e, "_") {
			continue
		}

		out = fmt.Sprintf("%s\t\t\"%s\"", out, e)

		if i < len(users)-1 {
			out = fmt.Sprintf("%s,\n", out)
		} else {
			out = fmt.Sprintf("%s\n", out)
		}
	}

	out = fmt.Sprintf("%s\t]\n}\n", out)

	return []byte(out), nil
}