forked from foxcpp/maddy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.go
136 lines (107 loc) · 2.39 KB
/
users.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package maddy
import (
"fmt"
"net/http"
"strings"
"github.com/foxcpp/maddy/internal/rest/model"
echo "github.com/labstack/echo/v4"
"github.com/foxcpp/maddy/internal/auth/pass_table"
)
func createUser(c echo.Context) error {
r := model.CreateUserDto{}
if err := c.Bind(&r); err != nil {
return err
}
if err := userCreate(r.Username, r.Password, r.CreateMailboxes); err != nil {
return err
}
return c.NoContent(http.StatusCreated)
}
func listUsers(c echo.Context) error {
list, err := userList()
if err != nil {
return err
}
results := []string{}
domain := c.QueryParam("domain")
if domain != "" {
for _, user := range list {
if strings.HasSuffix(user, fmt.Sprintf("@%s", domain)) {
results = append(results, user)
}
}
return c.JSON(http.StatusOK, results)
}
return c.JSON(http.StatusOK, list)
}
func getUser(c echo.Context) error {
list, err := userList()
if err != nil {
return err
}
for _, user := range list {
if user == c.Param("id") {
return c.JSON(http.StatusOK, model.User{Username: user})
}
}
return c.NoContent(http.StatusNotFound)
}
func deleteUser(c echo.Context) error {
deleteMailbox := c.QueryParam("delete_mailbox") == "true"
if err := userDelete(c.Param("id"), deleteMailbox); err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func updateUserPassword(c echo.Context) error {
r := model.Password{}
if err := c.Bind(&r); err != nil {
return err
}
if err := userDb.SetUserPassword(c.Param("id"), r.Password); err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func userCreate(username, password string, createMailboxes bool) (err error) {
beHash, ok := userDb.(*pass_table.Auth)
if !ok {
return fmt.Errorf("Hash cannot be used with non-pass_table credentials DB")
}
err = beHash.CreateUserHash(username, password, pass_table.HashBcrypt, pass_table.HashOpts{
BcryptCost: 10,
})
if err != nil {
return err
}
if createMailboxes {
err = imapAcctCreate(username)
if err != nil {
return
}
}
return
}
func userList() (list []string, err error) {
list, err = userDb.ListUsers()
if err != nil {
return
}
if len(list) == 0 {
return []string{}, nil
}
return
}
func userDelete(username string, deleteMailbox bool) (err error) {
err = userDb.DeleteUser(username)
if err != nil {
return
}
if deleteMailbox {
err = imapAcctRemove(username)
if err != nil {
return
}
}
return
}