-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathnew_user.go
289 lines (261 loc) · 6.79 KB
/
new_user.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package pkg
import (
"errors"
"fmt"
"strconv"
"github.com/badoux/checkmail"
"github.com/go-ldap/ldap/v3"
ldaperror "github.com/romnn/ldap-manager/pkg/err"
pb "github.com/romnn/ldap-manager/pkg/grpc/gen"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// UserAlreadyExistsError is returned when a username already exists
type UserAlreadyExistsError struct {
ldaperror.ApplicationError
Username string
}
func (e *UserAlreadyExistsError) Error() string {
return fmt.Sprintf(
"user with username %q already exists",
e.Username,
)
}
// StatusError returns the GRPC status error for this error
func (e *UserAlreadyExistsError) StatusError() error {
return status.Errorf(codes.AlreadyExists, e.Error())
}
// InvalidUserError is returned when the user contains invalid values
type InvalidUserError struct {
ldaperror.ApplicationError
Invalid map[string]error
}
func (e *InvalidUserError) Error() string {
return fmt.Sprintf(
"invalid new user: missing or invalid: %v",
e.Invalid,
)
}
// StatusError returns the GRPC status error for this error
func (e *InvalidUserError) StatusError() error {
message := "Invalid new user request:"
for field, reason := range e.Invalid {
message += fmt.Sprintf("\n-> %s: %s", field, reason)
}
return status.Errorf(codes.InvalidArgument, message)
}
// ValidateEmail validates an email
func ValidateEmail(email string) error {
if len(email) < 3 {
return errors.New("must contain at least 3 characters")
}
if len(email) > 254 {
return errors.New("can contain at most 254 characters")
}
if err := checkmail.ValidateFormat(email); err != nil {
return fmt.Errorf("%q is not a valid email: %v", email, err)
}
return nil
}
// ValidatePassword validates a password
func ValidatePassword(password string) error {
if password == "" {
return errors.New("must not be empty")
}
if len(password) < 5 {
return errors.New("must contain at least 5 characters")
}
return nil
}
// ValidateUsername validates a username
func ValidateUsername(username string) error {
if username == "" {
return errors.New("must not be empty")
}
if len(username) < 5 {
return errors.New("must contain at least 5 characters")
}
return nil
}
// ValidateFirstName validates a first name
func ValidateFirstName(name string) error {
if name == "" {
return errors.New("must not be empty")
}
return nil
}
// ValidateLastName validates a last name
func ValidateLastName(name string) error {
if name == "" {
return errors.New("must not be empty")
}
return nil
}
// ValidateNewUser validates a new user request
func ValidateNewUser(req *pb.NewUserRequest) *InvalidUserError {
invalid := make(map[string]error)
if err := ValidateUsername(req.GetUsername()); err != nil {
invalid["username"] = err
}
if err := ValidatePassword(req.GetPassword()); err != nil {
invalid["password"] = err
}
if err := ValidateEmail(req.GetEmail()); err != nil {
invalid["email"] = err
}
if err := ValidateFirstName(req.GetFirstName()); err != nil {
invalid["first name"] = err
}
if err := ValidateLastName(req.GetLastName()); err != nil {
invalid["last name"] = err
}
if len(invalid) > 0 {
return &InvalidUserError{Invalid: invalid}
}
return nil
}
func (m *LDAPManager) checkUserExists(username string) error {
_, err := m.GetUser(username)
if err != nil {
notFoundErr, notFound := err.(*ZeroOrMultipleUsersError)
if notFound {
if notFoundErr.Count > 1 {
return &UserAlreadyExistsError{
Username: username,
}
}
} else {
return fmt.Errorf(
"failed to check for existing user %q: %v",
username, err,
)
}
} else {
return &UserAlreadyExistsError{
Username: username,
}
}
return nil
}
// NewUser adds a new user
func (m *LDAPManager) NewUser(req *pb.NewUserRequest) error {
if err := ValidateNewUser(req); err != nil {
return err
}
username := req.GetUsername()
if err := m.checkUserExists(username); err != nil {
return err
}
// set default values
loginShell := req.GetLoginShell()
if loginShell == "" {
loginShell = m.DefaultUserShell
}
homeDirectory := req.GetHomeDirectory()
if homeDirectory == "" {
homeDirectory = fmt.Sprintf("/home/%s", username)
}
UID, err := m.GetHighestUID()
if err != nil {
return fmt.Errorf(
"failed to get highest UID (%s): %v",
m.AccountAttribute, err,
)
}
fullName := fmt.Sprintf(
"%s %s",
req.GetFirstName(),
req.GetLastName(),
)
userAttributes := []ldap.Attribute{
{Type: "objectClass", Vals: []string{
"person",
"inetOrgPerson",
"posixAccount",
}},
{Type: m.AccountAttribute, Vals: []string{username}},
{Type: "givenName", Vals: []string{req.GetFirstName()}},
{Type: "sn", Vals: []string{req.GetLastName()}},
{Type: "cn", Vals: []string{fullName}},
{Type: "displayName", Vals: []string{fullName}},
{Type: "uidNumber", Vals: []string{strconv.Itoa(UID)}},
{Type: "gidNumber", Vals: []string{
strconv.Itoa(MinGID),
// strconv.Itoa(int(userGroup.GetGID())),
}},
{Type: "loginShell", Vals: []string{loginShell}},
{Type: "homeDirectory", Vals: []string{homeDirectory}},
{Type: "mail", Vals: []string{req.GetEmail()}},
}
// add user
addUserRequest := &ldap.AddRequest{
DN: m.UserDN(username),
Attributes: userAttributes,
Controls: []ldap.Control{},
}
log.Debug(PrettyPrint(addUserRequest))
conn, err := m.Pool.Get()
if err != nil {
return err
}
defer conn.Close()
if err := conn.Add(addUserRequest); err != nil {
exists := ldap.IsErrorWithCode(err, ldap.LDAPResultEntryAlreadyExists)
if exists {
return &UserAlreadyExistsError{
Username: username,
}
}
return fmt.Errorf(
"failed to add user %q: %v",
username, err,
)
}
// change password of user
passwordModifyRequest := &ldap.PasswordModifyRequest{
UserIdentity: m.UserDN(username),
NewPassword: req.GetPassword(),
}
log.Debug(PrettyPrint(passwordModifyRequest))
_, err = conn.PasswordModify(passwordModifyRequest)
if err != nil {
return fmt.Errorf(
"failed to set password of new user %q: %v",
username, err,
)
}
groupName := m.DefaultUserGroup
strict := false
if err := m.NewGroup(&pb.NewGroupRequest{
Name: groupName,
Members: []string{username},
}, strict); err != nil {
if _, exists := err.(*GroupAlreadyExistsError); !exists {
return fmt.Errorf(
"failed to create %q group: %v",
groupName, err,
)
}
}
allowNonExistent := false
if err := m.AddGroupMember(&pb.GroupMember{
Group: groupName,
Username: username,
}, allowNonExistent); err != nil {
if _, exists := err.(*MemberAlreadyExistsError); !exists {
return fmt.Errorf(
"failed to add user %q to group %q: %v",
username, groupName, err,
)
}
}
if err := m.updateLastID("lastUID", UID+1); err != nil {
return err
}
log.Infof(
"added new user %q (member of group %q)",
username, groupName,
)
return nil
}