/
component.go
445 lines (360 loc) · 16.1 KB
/
component.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package account
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/cloudtrust/common-service/configuration"
cs "github.com/cloudtrust/common-service"
"github.com/cloudtrust/common-service/database"
errorhandler "github.com/cloudtrust/common-service/errors"
api "github.com/cloudtrust/keycloak-bridge/api/account"
"github.com/cloudtrust/keycloak-bridge/internal/constants"
"github.com/cloudtrust/keycloak-bridge/internal/dto"
"github.com/cloudtrust/keycloak-bridge/internal/keycloakb"
internal "github.com/cloudtrust/keycloak-bridge/internal/keycloakb"
kc "github.com/cloudtrust/keycloak-client"
)
// Constants
const (
ActionVerifyEmail = "VERIFY_EMAIL"
ActionVerifyPhoneNumber = "mobilephone-validation"
)
// KeycloakAccountClient interface exposes methods we need to call to send requests to Keycloak API of Account
type KeycloakAccountClient interface {
UpdatePassword(accessToken, realm, currentPassword, newPassword, confirmPassword string) (string, error)
GetCredentials(accessToken string, realmName string) ([]kc.CredentialRepresentation, error)
GetCredentialRegistrators(accessToken string, realmName string) ([]string, error)
UpdateLabelCredential(accessToken string, realmName string, credentialID string, label string) error
DeleteCredential(accessToken string, realmName string, credentialID string) error
MoveToFirst(accessToken string, realmName string, credentialID string) error
MoveAfter(accessToken string, realmName string, credentialID string, previousCredentialID string) error
UpdateAccount(accessToken, realm string, user kc.UserRepresentation) error
GetAccount(accessToken, realm string) (kc.UserRepresentation, error)
DeleteAccount(accessToken, realm string) error
ExecuteActionsEmail(accessToken string, realmName string, actions []string) error
}
// Component interface exposes methods used by the bridge API
type Component interface {
UpdatePassword(ctx context.Context, currentPassword, newPassword, confirmPassword string) error
GetCredentials(ctx context.Context) ([]api.CredentialRepresentation, error)
GetCredentialRegistrators(ctx context.Context) ([]string, error)
UpdateLabelCredential(ctx context.Context, credentialID string, label string) error
DeleteCredential(ctx context.Context, credentialID string) error
MoveCredential(ctx context.Context, credentialID string, previousCredentialID string) error
GetAccount(ctx context.Context) (api.AccountRepresentation, error)
UpdateAccount(context.Context, api.AccountRepresentation) error
DeleteAccount(context.Context) error
GetConfiguration(context.Context, string) (api.Configuration, error)
SendVerifyEmail(ctx context.Context) error
SendVerifyPhoneNumber(ctx context.Context) error
}
// UsersDBModule is the minimum required interface to access the users database
type UsersDBModule interface {
StoreOrUpdateUser(ctx context.Context, realm string, user dto.DBUser) error
GetUser(ctx context.Context, realm string, userID string) (*dto.DBUser, error)
}
// Component is the management component.
type component struct {
keycloakAccountClient KeycloakAccountClient
eventDBModule database.EventsDBModule
configDBModule keycloakb.ConfigurationDBModule
usersDBModule UsersDBModule
logger internal.Logger
}
// NewComponent returns the self-service component.
func NewComponent(keycloakAccountClient KeycloakAccountClient, eventDBModule database.EventsDBModule, configDBModule keycloakb.ConfigurationDBModule, usersDBModule UsersDBModule, logger internal.Logger) Component {
return &component{
keycloakAccountClient: keycloakAccountClient,
eventDBModule: eventDBModule,
configDBModule: configDBModule,
usersDBModule: usersDBModule,
logger: logger,
}
}
func (c *component) reportEvent(ctx context.Context, apiCall string, values ...string) {
errEvent := c.eventDBModule.ReportEvent(ctx, apiCall, "self-service", values...)
if errEvent != nil {
//store in the logs also the event that failed to be stored in the DB
internal.LogUnrecordedEvent(ctx, c.logger, apiCall, errEvent.Error(), values...)
}
}
func (c *component) UpdatePassword(ctx context.Context, currentPassword, newPassword, confirmPassword string) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var realm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var username = ctx.Value(cs.CtContextUsername).(string)
if currentPassword == newPassword || newPassword != confirmPassword {
return errorhandler.Error{
Status: http.StatusBadRequest,
Message: internal.ComponentName + "." + "invalidValues",
}
}
_, err := c.keycloakAccountClient.UpdatePassword(accessToken, realm, currentPassword, newPassword, confirmPassword)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
//store the API call into the DB
c.reportEvent(ctx, "PASSWORD_RESET", database.CtEventRealmName, realm, database.CtEventUserID, userID, database.CtEventUsername, username)
return nil
}
func (c *component) GetAccount(ctx context.Context) (api.AccountRepresentation, error) {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var realm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var userRep api.AccountRepresentation
userKc, err := c.keycloakAccountClient.GetAccount(accessToken, realm)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return userRep, err
}
var dbUser *dto.DBUser
dbUser, err = c.usersDBModule.GetUser(ctx, realm, userID)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return userRep, err
}
userRep = api.ConvertToAPIAccount(userKc)
if dbUser != nil {
userRep.BirthLocation = dbUser.BirthLocation
userRep.IDDocumentType = dbUser.IDDocumentType
userRep.IDDocumentNumber = dbUser.IDDocumentNumber
userRep.IDDocumentExpiration = dbUser.IDDocumentExpiration
}
return userRep, nil
}
func (c *component) UpdateAccount(ctx context.Context, user api.AccountRepresentation) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var realm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var username = ctx.Value(cs.CtContextUsername).(string)
var userRep kc.UserRepresentation
// get the "old" user representation
oldUserKc, err := c.keycloakAccountClient.GetAccount(accessToken, realm)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
var emailVerified, phoneNumberVerified *bool
var actions []string
// when the email changes, set the EmailVerified to false
if user.Email != nil && oldUserKc.Email != nil && *oldUserKc.Email != *user.Email {
var verified = false
emailVerified = &verified
actions = append(actions, ActionVerifyEmail)
}
// when the phone number changes, set the PhoneNumberVerified to false
if user.PhoneNumber != nil {
if oldUserKc.Attributes != nil {
var m = *oldUserKc.Attributes
if _, ok := m["phoneNumber"]; !ok || m["phoneNumber"][0] != *user.PhoneNumber {
var verified = false
phoneNumberVerified = &verified
actions = append(actions, ActionVerifyPhoneNumber)
}
} else { // the user has no attributes until now, i.e. he has not set yet his phone number
var verified = false
phoneNumberVerified = &verified
}
}
userRep = api.ConvertToKCUser(user)
if emailVerified != nil {
userRep.EmailVerified = emailVerified
}
// Merge the attributes coming from the old user representation and the updated user representation in order not to lose anything
var mergedAttributes = make(kc.Attributes)
//Populate with the old attributes
if oldUserKc.Attributes != nil {
for key, attribute := range *oldUserKc.Attributes {
mergedAttributes[key] = attribute
}
}
mergedAttributes.SetStringWhenNotNil(constants.AttrbPhoneNumber, user.PhoneNumber)
mergedAttributes.SetBoolWhenNotNil(constants.AttrbPhoneNumberVerified, phoneNumberVerified)
mergedAttributes.SetStringWhenNotNil(constants.AttrbGender, user.Gender)
mergedAttributes.SetDateWhenNotNil(constants.AttrbBirthDate, user.BirthDate, constants.SupportedDateLayouts)
mergedAttributes.SetStringWhenNotNil(constants.AttrbLocale, user.Locale)
userRep.Attributes = &mergedAttributes
err = c.keycloakAccountClient.UpdateAccount(accessToken, realm, userRep)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
//store the API call into the DB - As user is partially update, report event even if database update fails
c.reportEvent(ctx, "UPDATE_ACCOUNT", database.CtEventRealmName, realm, database.CtEventUserID, userID, database.CtEventUsername, username)
if len(actions) > 0 {
err = c.executeActions(ctx, actions)
}
var oldUser *dto.DBUser
oldUser, err = c.usersDBModule.GetUser(ctx, realm, userID)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
var dbUser = dto.DBUser{
UserID: &userID,
BirthLocation: user.BirthLocation,
IDDocumentType: user.IDDocumentType,
IDDocumentNumber: user.IDDocumentNumber,
IDDocumentExpiration: user.IDDocumentExpiration,
}
if oldUser != nil {
// Keep old values when none was provided
if dbUser.BirthLocation == nil {
dbUser.BirthLocation = oldUser.BirthLocation
}
if dbUser.IDDocumentType == nil {
dbUser.IDDocumentType = oldUser.IDDocumentType
}
if dbUser.IDDocumentNumber == nil {
dbUser.IDDocumentNumber = oldUser.IDDocumentNumber
}
if dbUser.IDDocumentExpiration == nil {
dbUser.IDDocumentExpiration = oldUser.IDDocumentExpiration
}
}
err = c.usersDBModule.StoreOrUpdateUser(ctx, realm, dbUser)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
}
return err
}
func (c *component) DeleteAccount(ctx context.Context) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var realm = ctx.Value(cs.CtContextRealm).(string)
err := c.keycloakAccountClient.DeleteAccount(accessToken, realm)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
//store the API call into the DB
c.reportEvent(ctx, "SELF_DELETE_ACCOUNT", database.CtEventRealmName, realm)
return nil
}
func (c *component) GetCredentials(ctx context.Context) ([]api.CredentialRepresentation, error) {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
credentialsKc, err := c.keycloakAccountClient.GetCredentials(accessToken, currentRealm)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return nil, err
}
var credentialsRep = []api.CredentialRepresentation{}
for _, credentialKc := range credentialsKc {
var credentialRep = api.ConvertCredential(&credentialKc)
credentialsRep = append(credentialsRep, credentialRep)
}
return credentialsRep, err
}
func (c *component) GetCredentialRegistrators(ctx context.Context) ([]string, error) {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
credentialTypes, err := c.keycloakAccountClient.GetCredentialRegistrators(accessToken, currentRealm)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return nil, err
}
return credentialTypes, nil
}
func (c *component) UpdateLabelCredential(ctx context.Context, credentialID string, label string) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var username = ctx.Value(cs.CtContextUsername).(string)
err := c.keycloakAccountClient.UpdateLabelCredential(accessToken, currentRealm, credentialID, label)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
//store the API call into the DB
// the error should be treated
additionalInfos, _ := json.Marshal(map[string]string{"credentialID": credentialID, "label": label})
c.reportEvent(ctx, "SELF_UPDATE_CREDENTIAL", database.CtEventRealmName, currentRealm, database.CtEventUserID, userID, database.CtEventUsername, username, database.CtEventAdditionalInfo, string(additionalInfos))
return nil
}
func (c *component) DeleteCredential(ctx context.Context, credentialID string) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var username = ctx.Value(cs.CtContextUsername).(string)
err := c.keycloakAccountClient.DeleteCredential(accessToken, currentRealm, credentialID)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
additionalInfos, _ := json.Marshal(map[string]string{"credentialID": credentialID})
//store the API call into the DB
c.reportEvent(ctx, "SELF_DELETE_CREDENTIAL", database.CtEventRealmName, currentRealm, database.CtEventUserID, userID, database.CtEventUsername, username, database.CtEventAdditionalInfo, string(additionalInfos))
return nil
}
func (c *component) MoveCredential(ctx context.Context, credentialID string, previousCredentialID string) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var username = ctx.Value(cs.CtContextUsername).(string)
var err error
if previousCredentialID == "null" {
err = c.keycloakAccountClient.MoveToFirst(accessToken, currentRealm, credentialID)
} else {
err = c.keycloakAccountClient.MoveAfter(accessToken, currentRealm, credentialID, previousCredentialID)
}
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
additionalInfos, err := json.Marshal(map[string]string{"credentialID": credentialID, "previousCredentialID": previousCredentialID})
//store the API call into the DB
c.reportEvent(ctx, "SELF_MOVE_CREDENTIAL", database.CtEventRealmName, currentRealm, database.CtEventUserID, userID, database.CtEventUsername, username, database.CtEventAdditionalInfo, string(additionalInfos))
return nil
}
func (c *component) GetConfiguration(ctx context.Context, realmIDOverride string) (api.Configuration, error) {
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
config, err := c.configDBModule.GetConfiguration(ctx, currentRealm)
if err != nil {
return api.Configuration{}, err
}
var adminConfig configuration.RealmAdminConfiguration
adminConfig, err = c.configDBModule.GetAdminConfiguration(ctx, currentRealm)
if err != nil {
return api.Configuration{}, err
}
var apiConfig = api.Configuration{
EditingEnabled: config.APISelfAccountEditingEnabled,
ShowAuthenticatorsTab: config.ShowAuthenticatorsTab,
ShowAccountDeletionButton: config.ShowAccountDeletionButton,
ShowPasswordTab: config.ShowPasswordTab,
ShowProfileTab: config.ShowProfileTab,
RedirectSuccessfulRegistrationURL: config.RedirectSuccessfulRegistrationURL,
AvailableChecks: adminConfig.AvailableChecks,
}
if realmIDOverride != "" {
overrideConfig, err := c.configDBModule.GetConfiguration(ctx, realmIDOverride)
if err != nil {
return api.Configuration{}, err
}
apiConfig.RedirectSuccessfulRegistrationURL = overrideConfig.RedirectSuccessfulRegistrationURL
}
return apiConfig, nil
}
func (c *component) SendVerifyEmail(ctx context.Context) error {
return c.executeActions(ctx, []string{ActionVerifyEmail})
}
func (c *component) SendVerifyPhoneNumber(ctx context.Context) error {
return c.executeActions(ctx, []string{ActionVerifyPhoneNumber})
}
func (c *component) executeActions(ctx context.Context, actions []string) error {
var accessToken = ctx.Value(cs.CtContextAccessToken).(string)
var currentRealm = ctx.Value(cs.CtContextRealm).(string)
var userID = ctx.Value(cs.CtContextUserID).(string)
var err = c.keycloakAccountClient.ExecuteActionsEmail(accessToken, currentRealm, actions)
if err != nil {
c.logger.Warn(ctx, "err", err.Error())
return err
}
var additionalInfos = map[string]string{"actions": strings.Join(actions, ",")}
var additionalBytes, _ = json.Marshal(additionalInfos)
var additionalString = string(additionalBytes)
c.reportEvent(ctx, "ACTION_EMAIL", database.CtEventRealmName, currentRealm, database.CtEventUserID, userID, database.CtEventAdditionalInfo, additionalString)
return err
}