-
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
-
290
-
291
-
292
-
293
-
294
-
295
-
296
-
297
// SPDX-FileCopyrightText: 2025 Shota FUJI <pockawoooh@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-only
package workspace
import (
"context"
"crypto/rand"
"slices"
"strings"
"connectrpc.com/connect"
"github.com/google/uuid"
"google.golang.org/protobuf/proto"
eventV1 "pocka.jp/x/yamori/proto/go/backend/events/v1"
"pocka.jp/x/yamori/proto/go/backend/workspace/v1/types"
errorV1 "pocka.jp/x/yamori/proto/go/error/v1"
workspaceV2 "pocka.jp/x/yamori/proto/go/workspace/v2"
"pocka.jp/x/yamori/backend/core/event"
"pocka.jp/x/yamori/backend/core/projection"
workspaceEvent "pocka.jp/x/yamori/backend/events/workspace"
)
func createUserSystemError(message string) *connect.Response[workspaceV2.CreateUserResponse] {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_SystemError{
SystemError: &errorV1.SystemError{
Message: proto.String(message),
},
},
})
}
func createUserAuthError() *connect.Response[workspaceV2.CreateUserResponse] {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_AuthenticationError{
AuthenticationError: &errorV1.AuthenticationError{},
},
})
}
func createUserPermError() *connect.Response[workspaceV2.CreateUserResponse] {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_PermissionError{
PermissionError: &errorV1.PermissionError{},
},
})
}
func (s *Service) CreateUser(
ctx context.Context,
req *connect.Request[workspaceV2.CreateUserRequest],
) (*connect.Response[workspaceV2.CreateUserResponse], error) {
logger := s.core.Logger.With(
"service", "yamori.workspace.v2.WorkspaceService",
"method", "CreateUser",
)
header := req.Header()
token, err := s.core.LoadTokenFromCookie(&header)
if err != nil || token == nil {
return createUserAuthError(), nil
}
tx, err := s.core.DB.Begin()
if err != nil {
logger.Error("Failed to begin transaction", "error", err)
return createUserSystemError("Database error"), nil
}
defer tx.Rollback()
users, err := projection.GetUsers(tx)
if err != nil {
logger.Error("Failed to read users projection", "error", err)
return createUserSystemError("Database error"), nil
}
secret, err := projection.GetLoginJwtSecret(tx)
if err != nil {
logger.Error("Failed to read login_jwt_secret projection", "error", err)
return createUserSystemError("Database error"), nil
}
if err := event.UpdateProjections(tx, users, secret); err != nil {
logger.Error("Failed to update projections", "error", err)
return createUserSystemError("Database error"), nil
}
user, err := token.FindUser(secret, users)
if err != nil {
logger.Warn("Malformed token found", "error", err)
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_AuthenticationError{
AuthenticationError: &errorV1.AuthenticationError{},
},
}), nil
}
name := req.Msg.GetName()
if name == "" {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_MissingFieldError{
MissingFieldError: &errorV1.MissingFieldError{
Path: proto.String("name"),
},
},
}), nil
}
if strings.Trim(name, " \r\n\t") != name {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_NameSurroundedBySpaces{
NameSurroundedBySpaces: "Name cannot contain space, CR, LF, Tab",
},
}), nil
}
displayName := strings.Trim(req.Msg.GetDisplayName(), " \r\n\t")
if displayName == "" {
displayName = name
}
password := req.Msg.GetPassword()
if password == "" {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_MissingFieldError{
MissingFieldError: &errorV1.MissingFieldError{
Path: proto.String("password"),
},
},
}), nil
}
if len(password) <= 8 {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_PasswordLessThanBytes{
PasswordLessThanBytes: 8,
},
}), nil
}
requiredPerm := types.Permission_PERMISSION_ADD_REGULAR_USER
if req.Msg.GetIsAdmin() {
requiredPerm = types.Permission_PERMISSION_ADD_ADMIN_USER
}
if !slices.Contains(user.Permissions, requiredPerm) {
return createUserPermError(), nil
}
for _, u := range users.Projection.Users {
if u.GetName() == name {
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_DuplicatedName{
DuplicatedName: name,
},
}), nil
}
}
id, err := uuid.NewRandom()
if err != nil {
logger.Error("Failed to generate UUID", "error", err)
return createUserSystemError("Unable to issue a new ID"), nil
}
keyID := make([]byte, 32)
rand.Read(keyID)
err = event.AppendEvents(tx, []*eventV1.Event{
workspaceEvent.CreateUser(id.String(), name, displayName, keyID),
workspaceEvent.ConfigurePasswordLogin(id.String(), password),
})
if err != nil {
logger.Error("Failed to append user creation events", "error", err)
return createUserSystemError("Database error"), nil
}
if req.Msg.GetIsAdmin() {
err := event.AppendEvents(tx, []*eventV1.Event{
workspaceEvent.GrantAdminAccess(id.String()),
})
if err != nil {
logger.Error("Failed to append adming grant events", "error", err)
return createUserSystemError("Database error"), nil
}
} else {
permissions := make([]types.Permission, 0, 32)
if req.Msg.Permissions != nil {
if req.Msg.Permissions.GetCanAddUser() {
// ユーザ追加権限はここに来ている時点で持っているためチェックは不要。
permissions = append(permissions, types.Permission_PERMISSION_ADD_REGULAR_USER)
}
if req.Msg.Permissions.GetCanDeleteRegularUser() {
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_DELETE_REGULAR_USER) {
return createUserPermError(), nil
}
permissions = append(permissions, types.Permission_PERMISSION_DELETE_REGULAR_USER)
}
if req.Msg.Permissions.GetCanReadOtherUserProfile() {
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_READ_REGULAR_USER_PROFILE) {
return createUserPermError(), nil
}
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_READ_ADMIN_USER_PROFILE) {
return createUserPermError(), nil
}
permissions = append(
permissions,
types.Permission_PERMISSION_READ_REGULAR_USER_PROFILE,
types.Permission_PERMISSION_READ_ADMIN_USER_PROFILE,
)
}
if req.Msg.Permissions.GetCanUpdateOtherRegularUserProfile() {
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_UPDATE_REGULAR_USER_PROFILE) {
return createUserPermError(), nil
}
permissions = append(permissions, types.Permission_PERMISSION_UPDATE_REGULAR_USER_PROFILE)
}
if req.Msg.Permissions.GetCanUpdateSelfProfile() {
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_UPDATE_SELF_PROFILE) {
return createUserPermError(), nil
}
permissions = append(permissions, types.Permission_PERMISSION_UPDATE_SELF_PROFILE)
}
if req.Msg.Permissions.GetCanUpdateOtherRegularUserLoginMethod() {
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_UPDATE_REGULAR_USER_LOGIN_METHOD) {
return createUserPermError(), nil
}
permissions = append(
permissions,
types.Permission_PERMISSION_UPDATE_REGULAR_USER_LOGIN_METHOD,
)
}
if req.Msg.Permissions.GetCanUpdateWorkspace() {
if !slices.Contains(user.Permissions, types.Permission_PERMISSION_EDIT_WORKSPACE_PROFILE) {
return createUserPermError(), nil
}
permissions = append(permissions, types.Permission_PERMISSION_EDIT_WORKSPACE_PROFILE)
}
}
err := event.AppendEvents(tx, []*eventV1.Event{
workspaceEvent.GrantPermission(id.String(), permissions),
})
if err != nil {
logger.Error("Failed to append a permissions grant event", "error", err)
return createUserSystemError("Database error"), nil
}
}
if err := event.UpdateProjections(tx, users); err != nil {
logger.Error("Failed to update users projection", "error", err)
return createUserSystemError("Database error"), nil
}
if err := tx.Commit(); err != nil {
logger.Error("Failed to commit transaction", "error", err)
return createUserSystemError("Database error"), nil
}
for _, u := range users.Projection.Users {
if u.GetId() == id.String() {
logger.Debug("Created a new user", "id", id.String())
return connect.NewResponse(&workspaceV2.CreateUserResponse{
Result: &workspaceV2.CreateUserResponse_Ok{
Ok: projectionUserToMessage(u),
},
}), nil
}
}
logger.Error(
"Creation of user succeeded, but the user does not exist in projection",
"id",
id.String(),
)
return createUserSystemError("Database error"), nil
}