-
Notifications
You must be signed in to change notification settings - Fork 28
/
service.go
371 lines (318 loc) · 9.32 KB
/
service.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package elasticsearch
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/sirupsen/logrus"
"github.com/authgear/authgear-server/pkg/api/model"
identityloginid "github.com/authgear/authgear-server/pkg/lib/authn/identity/loginid"
identityoauth "github.com/authgear/authgear-server/pkg/lib/authn/identity/oauth"
"github.com/authgear/authgear-server/pkg/lib/authn/user"
libuser "github.com/authgear/authgear-server/pkg/lib/authn/user"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/lib/infra/db/appdb"
"github.com/authgear/authgear-server/pkg/lib/infra/redisqueue"
"github.com/authgear/authgear-server/pkg/lib/infra/task"
"github.com/authgear/authgear-server/pkg/lib/rolesgroups"
"github.com/authgear/authgear-server/pkg/util/accesscontrol"
"github.com/authgear/authgear-server/pkg/util/clock"
"github.com/authgear/authgear-server/pkg/util/graphqlutil"
"github.com/authgear/authgear-server/pkg/util/log"
"github.com/authgear/authgear-server/pkg/util/slice"
)
type UserQueries interface {
Get(userID string, role accesscontrol.Role) (*model.User, error)
}
type ElasticsearchServiceLogger struct{ *log.Logger }
func NewElasticsearchServiceLogger(lf *log.Factory) *ElasticsearchServiceLogger {
return &ElasticsearchServiceLogger{lf.New("elasticsearch-service")}
}
type UserReindexCreateProducer interface {
NewTask(appID string, input json.RawMessage) *redisqueue.Task
EnqueueTask(ctx context.Context, task *redisqueue.Task) error
}
type Service struct {
Clock clock.Clock
Context context.Context
Database *appdb.Handle
Logger *ElasticsearchServiceLogger
AppID config.AppID
Client *elasticsearch.Client
Users UserQueries
UserStore *user.Store
OAuth *identityoauth.Store
LoginID *identityloginid.Store
RolesGroups *rolesgroups.Store
TaskQueue task.Queue
Producer UserReindexCreateProducer
}
type queryUserResponse struct {
Hits struct {
Total struct {
Value int `json:"value"`
} `json:"total"`
Hits []struct {
Source model.ElasticsearchUserSource `json:"_source"`
Sort interface{} `json:"sort"`
} `json:"hits"`
} `json:"hits"`
}
type action string
const (
actionReindex action = "reindex"
actionDelete action = "delete"
actionSkip action = "skip"
)
func (s *Service) EnqueueReindexUserTask(userID string) error {
request := ReindexRequest{UserID: userID}
rawMessage, err := json.Marshal(request)
if err != nil {
return err
}
task := s.Producer.NewTask(string(s.AppID), rawMessage)
err = s.Producer.EnqueueTask(s.Context, task)
if err != nil {
return err
}
return nil
}
func (s *Service) getSource(userID string) (*model.ElasticsearchUserSource, action, error) {
rawUser, err := s.UserStore.Get(userID)
if errors.Is(err, libuser.ErrUserNotFound) {
return nil, actionDelete, nil
}
if rawUser.LastIndexedAt != nil && rawUser.RequireReindexAfter != nil && rawUser.LastIndexedAt.After(*rawUser.RequireReindexAfter) {
// Already latest state, skip the update
return nil, actionSkip, nil
}
u, err := s.Users.Get(userID, accesscontrol.RoleGreatest)
if errors.Is(err, libuser.ErrUserNotFound) {
return nil, actionDelete, nil
}
if err != nil {
return nil, "", err
}
oauthIdentities, err := s.OAuth.List(u.ID)
if err != nil {
return nil, "", err
}
loginIDIdentities, err := s.LoginID.List(u.ID)
if err != nil {
return nil, "", err
}
effectiveRoles, err := s.RolesGroups.ListEffectiveRolesByUserID(u.ID)
if err != nil {
return nil, "", err
}
groups, err := s.RolesGroups.ListGroupsByUserID(u.ID)
if err != nil {
return nil, "", err
}
raw := &model.ElasticsearchUserRaw{
ID: u.ID,
AppID: string(s.AppID),
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
LastLoginAt: u.LastLoginAt,
IsDisabled: u.IsDisabled,
StandardAttributes: u.StandardAttributes,
EffectiveRoles: slice.Map(effectiveRoles, func(r *rolesgroups.Role) *model.Role { return r.ToModel() }),
Groups: slice.Map(groups, func(g *rolesgroups.Group) *model.Group { return g.ToModel() }),
}
var arrClaims []map[model.ClaimName]string
for _, oauthI := range oauthIdentities {
arrClaims = append(arrClaims, oauthI.ToInfo().IdentityAwareStandardClaims())
raw.OAuthSubjectID = append(raw.OAuthSubjectID, oauthI.ProviderSubjectID)
}
for _, loginIDI := range loginIDIdentities {
arrClaims = append(arrClaims, loginIDI.ToInfo().IdentityAwareStandardClaims())
}
for _, claims := range arrClaims {
if email, ok := claims[model.ClaimEmail]; ok {
raw.Email = append(raw.Email, email)
}
if phoneNumber, ok := claims[model.ClaimPhoneNumber]; ok {
raw.PhoneNumber = append(raw.PhoneNumber, phoneNumber)
}
if preferredUsername, ok := claims[model.ClaimPreferredUsername]; ok {
raw.PreferredUsername = append(raw.PreferredUsername, preferredUsername)
}
}
return RawToSource(raw), actionReindex, nil
}
func (s *Service) ExecReindexUser(request ReindexRequest) (result ReindexResult) {
failure := func(err error) ReindexResult {
s.Logger.WithFields(map[string]interface{}{"user_id": request.UserID}).
WithError(err).
Error("unknown error on reindexing user")
return ReindexResult{
UserID: request.UserID,
IsSuccess: false,
ErrorMessage: fmt.Sprintf("%v", err),
}
}
startedAt := s.Clock.NowUTC()
var source *model.ElasticsearchUserSource = nil
var actionToExec action
err := s.Database.ReadOnly(func() error {
s, a, err := s.getSource(request.UserID)
if err != nil {
return err
}
source = s
actionToExec = a
return nil
})
if err != nil {
return failure(err)
}
switch actionToExec {
case actionDelete:
err = s.deleteUser(request.UserID)
if err != nil {
return failure(err)
}
case actionReindex:
err = s.reindexUser(source)
if err != nil {
return failure(err)
}
err = s.Database.WithTx(func() error {
return s.UserStore.UpdateLastIndexedAt([]string{request.UserID}, startedAt)
})
if err != nil {
return failure(err)
}
case actionSkip:
s.Logger.WithFields(logrus.Fields{
"app_id": s.AppID,
"user_id": request.UserID,
}).Info("skipping reindexing user because it is already up to date")
default:
panic(fmt.Errorf("elasticsearch: unknown action %s", actionToExec))
}
return ReindexResult{
UserID: request.UserID,
IsSuccess: true,
}
}
func (s *Service) QueryUser(
searchKeyword string,
filterOptions libuser.FilterOptions,
sortOption libuser.SortOption,
pageArgs graphqlutil.PageArgs,
) ([]model.PageItemRef, *Stats, error) {
if s.Client == nil {
return nil, &Stats{TotalCount: 0}, nil
}
// Prepare body
bodyJSONValue := MakeSearchBody(s.AppID, searchKeyword, filterOptions, sortOption)
// Prepare search_after
searchAfter, err := CursorToSearchAfter(model.PageCursor(pageArgs.After))
if err != nil {
return nil, nil, err
}
if searchAfter != nil {
bodyJSONValue["search_after"] = searchAfter
}
bodyJSONBytes, err := json.Marshal(bodyJSONValue)
if err != nil {
return nil, nil, err
}
body := bytes.NewReader(bodyJSONBytes)
// Prepare size
size := int(*pageArgs.First)
if size == 0 {
size = 20
}
res, err := s.Client.Search(func(o *esapi.SearchRequest) {
o.Index = []string{IndexNameUser}
o.Body = body
o.Size = &size
})
if err != nil {
return nil, nil, fmt.Errorf("failed to connect to elasticsearch: %w", err)
}
defer res.Body.Close()
if res.IsError() {
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, nil, err
}
return nil, nil, fmt.Errorf("failed to query user: %v", string(bytes))
}
var r queryUserResponse
err = json.NewDecoder(res.Body).Decode(&r)
if err != nil {
return nil, nil, err
}
items := make([]model.PageItemRef, len(r.Hits.Hits))
for i, u := range r.Hits.Hits {
user := u.Source
cursor, err := SortToCursor(u.Sort)
if err != nil {
return nil, nil, err
}
items[i] = model.PageItemRef{ID: user.ID, Cursor: cursor}
}
return items, &Stats{
TotalCount: r.Hits.Total.Value,
}, nil
}
func (s *Service) reindexUser(user *model.ElasticsearchUserSource) error {
documentID := fmt.Sprintf("%s:%s", user.AppID, user.ID)
s.Logger.WithFields(logrus.Fields{
"app_id": user.AppID,
"user_id": user.ID,
}).Info("reindexing user")
var res *esapi.Response
var sourceBytes []byte
sourceBytes, err := json.Marshal(user)
if err != nil {
return err
}
body := &bytes.Buffer{}
_, err = body.Write(sourceBytes)
if err != nil {
return err
}
res, err = s.Client.Index(IndexNameUser, body, func(o *esapi.IndexRequest) {
o.DocumentID = documentID
})
if err != nil {
return err
}
defer res.Body.Close()
if res.IsError() {
err = fmt.Errorf("%v", res)
return err
}
return nil
}
func (s *Service) deleteUser(userID string) error {
appID := s.AppID
s.Logger.WithFields(logrus.Fields{
"app_id": appID,
"user_id": userID,
}).Info("removing user from index")
documentID := fmt.Sprintf("%s:%s", appID, userID)
var res *esapi.Response
res, err := s.Client.Delete(IndexNameUser, documentID)
if err != nil {
return err
}
defer res.Body.Close()
if res.IsError() {
err = fmt.Errorf("%v", res)
return err
}
return nil
}
func (s *Service) MarkUsersAsReindexRequired(userIDs []string) error {
return s.UserStore.MarkAsReindexRequired(userIDs)
}