KeycloakServices.groovy
17.9 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import groovy.json.JsonOutput
import groovy.transform.Field
import java.sql.Timestamp
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import groovy.json.JsonSlurper
import org.moqui.context.ExecutionContext
import org.moqui.entity.EntityCondition
import org.moqui.entity.EntityFind
import org.moqui.entity.EntityList
import org.moqui.entity.EntityValue
import org.moqui.keycloak.KeycloakToolFactory
import org.keycloak.OAuth2Constants
import org.keycloak.admin.client.Keycloak
import org.keycloak.admin.client.KeycloakBuilder
import org.keycloak.admin.client.resource.ClientResource
import org.keycloak.admin.client.resource.GroupsResource
import org.keycloak.admin.client.resource.RealmResource
import org.keycloak.admin.client.resource.RoleMappingResource
import org.keycloak.admin.client.resource.RoleScopeResource
import org.keycloak.admin.client.resource.RoleResource
import org.keycloak.admin.client.resource.RolesResource
import org.keycloak.admin.client.resource.ServerInfoResource
import org.keycloak.admin.client.resource.UserResource
import org.keycloak.admin.client.resource.UsersResource
import org.keycloak.representations.idm.ClientMappingsRepresentation
import org.keycloak.representations.idm.CredentialRepresentation
import org.keycloak.representations.idm.GroupRepresentation
import org.keycloak.representations.idm.MappingsRepresentation
import org.keycloak.representations.idm.RoleRepresentation
import org.keycloak.representations.idm.UserRepresentation
import org.keycloak.util.JsonSerialization
@Field Logger logger = LoggerFactory.getLogger('KeycloakServices')
Long timestampToKeycloak(Timestamp timestamp) {
return timestamp.getTime()
}
String keycloakToJson(Object o) {
return JsonSerialization.writeValueAsString(o)
}
void cleanupKeycloak() {
Map<String, Object> sharedMap = ec.getContextRoot()
Keycloak keycloak = sharedMap['keycloak']
if (keycloak != null) {
keycloak.close()
}
Iterator<String> keyIt = sharedMap.keySet().iterator()
while (keyIt.hasNext()) {
String key = keyIt.next()
if (key == 'keycloak' || key.startsWith('keycloak:')) {
keyIt.remove()
}
}
}
Keycloak getKeycloak() {
Map<String, Object> sharedMap = ec.getContextRoot()
KeycloakToolFactory keycloakToolFactory = ec.getFactory().getToolFactory('Keycloak')
Keycloak keycloak = sharedMap['keycloak']
if (keycloak == null) {
keycloak = keycloakToolFactory.getInstance()
sharedMap['keycloak'] = keycloak
}
return keycloak
}
RealmResource getKeycloakRealm() {
Map<String, Object> sharedMap = ec.getContextRoot()
RealmResource keycloakRealm = sharedMap['keycloak:realm']
if (!realm) {
Keycloak keycloak = getKeycloak()
KeycloakToolFactory keycloakToolFactory = ec.getFactory().getToolFactory('Keycloak')
keycloakRealm = keycloak.realm(keycloakToolFactory.getRealmName())
sharedMap['keycloak:realm'] = keycloakRealm
}
return keycloakRealm
}
String getKeycloakClientId() {
Map<String, Object> sharedMap = ec.getContextRoot()
String keycloakClientId = sharedMap['keycloak:clientId']
if (!keycloakClientId) {
RealmResource keycloakRealm = getKeycloakRealm()
KeycloakToolFactory keycloakToolFactory = ec.getFactory().getToolFactory('Keycloak')
keycloakClientId = keycloakRealm.clients().findByClientId(keycloakToolFactory.getClientId()).get(0).getId()
sharedMap['keycloak:clientId'] = keycloakClientId
}
return keycloakClientId
}
ClientResource getKeycloakClient() {
Map<String, Object> sharedMap = ec.getContextRoot()
ClientResource keycloakClient = sharedMap['keycloak:client']
if (!keycloakClient) {
String keycloakClientId = getKeycloakClientId()
RealmResource realm = getKeycloakRealm()
keycloakClient = realm.clients().get(keycloakClientId)
sharedMap['keycloak:client'] = keycloakClient
}
return keycloakClient
}
Map<String, Object> syncUserAccount() {
String userId = context.userId
String newPassword = context.newPassword
try {
EntityValue userAccount = ec.getEntity().find('UserAccount').condition('userId', userId).one()
if (!userAccount.username) {
ec.message.addMessage("Skipping userAccount with empty username: ${userId})")
return
}
RealmResource realmResource = getKeycloakRealm()
UsersResource usersResource = realmResource.users()
if (userAccount.externalUserId == null) {
logger.info("Searching for existing user: ${userAccount.username}")
List<UserRepresentation> existingByUsername = usersResource.search(userAccount.username, true)
logger.info("Found: ${existingByUsername}")
if (!existingByUsername.isEmpty()) {
// FIXME: disable eeca
boolean reenableEeca = ec.artifactExecutionFacade.disableEntityEca()
try {
userAccount.externalUserId = existingByUsername[0].getId()
userAccount.store()
} finally {
if (reenableEeca) ec.artifactExecutionFacade.enableEntityEca()
}
}
}
if (userAccount.externalUserId == null) {
UserRepresentation newKeycloakUser = new UserRepresentation()
newKeycloakUser.setUsername(userAccount.username)
newKeycloakUser.setEnabled(false)
newKeycloakUser.setEmail(userAccount.emailAddress)
Object response = usersResource.create(newKeycloakUser)
logger.info("create response: ${keycloakToJson(response)}")
logger.info("status=${response.status}")
if (response.status == 201) {
List<UserRepresentation> newlyCreatedUserList = usersResource.search(userAccount.username)
if (newlyCreatedUserList.size() == 1) {
// FIXME: disable eeca
boolean reenableEeca = ec.artifactExecutionFacade.disableEntityEca()
try {
userAccount.externalUserId = newlyCreatedUserList[0].getId()
userAccount.store()
} finally {
if (reenableEeca) ec.artifactExecutionFacade.enableEntityEca()
}
}
}
if (userAccount.externalUserId == null) {
ec.message.addError("Couldn't create keycloak user for: ${userAccount.username})")
return
}
}
String keycloakUserId = userAccount.externalUserId
logger.info("Would update: keycloak(${keycloakUserId})")
updateUser(keycloakUserId, userId)
if (newPassword != null) {
UserResource userResource = usersResource.get(keycloakUserId)
List<CredentialRepresentation> credentials = userResource.credentials()
for (CredentialRepresentation credential: credentials) {
logger.info("keycloak(${keycloakUserId}) credential=${keycloakToJson(credential)}")
}
CredentialRepresentation newPasswordRepr = new CredentialRepresentation()
newPasswordRepr.setType(CredentialRepresentation.PASSWORD)
newPasswordRepr.setValue(newPassword)
newPasswordRepr.setTemporary(false)
userResource.resetPassword(newPasswordRepr)
}
} finally {
cleanupKeycloak()
}
}
Map<String, Object> updatePasswordInternal() {
String userId = context.userId
String newPassword = context.newPassword
logger.info("updatePasswordInternal: userId:${userId} newPassword:${newPassword}")
try {
EntityValue userAccount = ec.getEntity().find('UserAccount').condition('userId', userId).one()
String keycloakUserId = userAccount.externalUserId
RealmResource realmResource = getKeycloakRealm()
UsersResource usersResource = realmResource.users()
UserResource userResource = usersResource.get(keycloakUserId)
List<CredentialRepresentation> credentials = userResource.credentials()
for (CredentialRepresentation credential: credentials) {
logger.info("keycloak(${keycloakUserId}) credential=${keycloakToJson(credential)}")
}
CredentialRepresentation newPasswordRepr = new CredentialRepresentation()
newPasswordRepr.setType(CredentialRepresentation.PASSWORD)
newPasswordRepr.setValue(newPassword)
newPasswordRepr.setTemporary(false)
userResource.resetPassword(newPasswordRepr)
} finally {
cleanupKeycloak()
}
}
// This does not add in the composite child roles
RoleResource syncUserGroup(String userGroupId) {
EntityValue userGroup = ec.getEntity().find('UserGroup').condition('userGroupId', userGroupId).one()
return configureClientRoleResource('UserGroup:' + userGroupId, userGroup.description, null, null)
}
Map<String, Object> syncUserGroup() {
String userGroupId = context.userGroupId
try {
EntityValue userGroup = ec.getEntity().find('UserGroup').condition('userGroupId', userGroupId).one()
String keycloakRoleName = 'UserGroup:' + userGroupId
Set<RoleRepresentation> wantedRoles = new HashSet<RoleRepresentation>()
List<EntityValue> userGroupPermissionList = ec.entity.find('UserGroupPermission')
.condition('userGroupId', userGroupId)
.useCache(false)
.disableAuthz()
.list()
.filterByDate('fromDate', 'thruDate', now)
wantedRoles.addAll(userGroupPermissionList*.userPermissionId.collect { userPermissionId -> syncUserPermission(userPermissionId).toRepresentation() })
configureClientRoleResource(keycloakRoleName, userGroup.description, wantedRoles, null)
} finally {
cleanupKeycloak()
}
return [:]
}
RoleRepresentation getClientRoleRepresentation(String roleName) {
Map<String, Object> sharedMap = ec.getContextRoot()
if (sharedMap['keycloak:clientRole[' + roleName + ']']) {
return sharedMap['keycloak:clientRole[' + roleName + ']'].toRepresentation()
}
ClientResource clientResource = getKeycloakClient()
RolesResource rolesResource = clientResource.roles()
RoleResource roleResource = rolesResource.get(roleName)
if (roleResource == null) {
rolesResource.create(new RoleRepresentation(roleName, null, false))
roleResource = rolesResource.get(roleName)
}
return roleResource.toRepresentation()
}
RoleResource configureClientRoleResource(String roleName, String description, Set<RoleRepresentation> wantedRoles, Closure updater) {
String keycloakClientId = getKeycloakClientId()
Map<String, Object> sharedMap = ec.getContextRoot()
if (sharedMap['keycloak:clientRole[' + roleName + ']']) {
return sharedMap['keycloak:clientRole[' + roleName + ']']
}
logger.info("configureClientRoleResource: ${roleName}: ${description}")
ClientResource clientResource = getKeycloakClient()
RolesResource rolesResource = clientResource.roles()
RoleResource roleResource = rolesResource.get(roleName)
try {
roleResource.toRepresentation()
} catch (javax.ws.rs.NotFoundException e) {
roleResource = null
}
//RoleRepresentation roleRepresentation = rolesResource.list(roleName, false)?[0]
boolean updated = false
//if (roleRepresentation == null) {
if (roleResource == null) {
rolesResource.create(new RoleRepresentation(roleName, description, false))
roleResource = rolesResource.get(roleName)
//roleRepresentation = rolesResource.list(roleName, false).get(0)
}
RoleRepresentation roleRepresentation = roleResource.toRepresentation()
if (roleRepresentation.getDescription() != description) {
roleRepresentation.setDescription(description)
updated = true
}
if (updater) {
updated |= updater(roleRepresentation)
}
if (updated) {
logger.info("Sending update: ${roleRepresentation}")
roleResource.update(roleRepresentation)
}
if (wantedRoles != null) {
Set<RoleRepresentation> existingRoles = roleResource.getClientRoleComposites(keycloakClientId)
Set<RoleRepresentation> toAdd = new HashSet<RoleRepresentation>(wantedRoles)
toAdd.removeAll(existingRoles)
Set<RoleRepresentation> toRemove = new HashSet<RoleRepresentation>(existingRoles)
toRemove.removeAll(wantedRoles)
if (!toRemove.isEmpty()) {
roleResource.deleteComposites(toRemove as List)
}
if (!wantedRoles.isEmpty()) {
roleResource.addComposites(wantedRoles as List)
}
}
sharedMap['keycloak:clientRole[' + roleName + ']'] = roleResource
return roleResource
}
RoleResource syncUserPermission(String userPermissionId) {
EntityValue userPermission = ec.getEntity().find('UserPermission').condition('userPermissionId', userPermissionId).one()
return configureClientRoleResource('UserPermission:' + userPermissionId, userPermission.description, null, null)
}
Map<String, Object> syncUserPermission() {
String userPermissionId = context.userPermissionId
try {
syncUserPermission(userPermissionId)
} finally {
cleanupKeycloak()
}
return [:]
}
RoleResource syncRoleType(String roleTypeId) {
EntityValue roleType = ec.getEntity().find('RoleType').condition('roleTypeId', roleTypeId).one()
return configureClientRoleResource('RoleType:' + roleTypeId, roleType.description, null, null)
}
Map<String, Object> syncRoleType() {
String roleTypeId = context.roleTypeId
try {
syncRoleType(roleTypeId)
} finally {
cleanupKeycloak()
}
return [:]
}
RoleResource syncPartyClassification(String partyClassificationId) {
EntityValue partyClassification = ec.getEntity().find('PartyClassification').condition('partyClassificationId', partyClassificationId).one()
return configureClientRoleResource('PartyClassification:' + partyClassificationId, partyClassification.description, null, null)
}
Map<String, Object> syncPartyClassification() {
String partyClassificationId = context.partyClassificationId
try {
syncPartyClassification(partyClassificationId)
} finally {
cleanupKeycloak()
}
return [:]
}
Map<String, RoleRepresentation> getClientRoles(RealmResource realm, ClientResource clientResource, Collection<String> roleList) {
//logger.info('keycloak client: ' + keycloakToJson(clientResource))
logger.info("roleList(${roleList.size()})=${roleList}")
Map<String, RoleRepresentation> result = [:]
for (String role: roleList) {
result[role] = null
}
RolesResource rolesResource = clientResource.roles()
for (RoleRepresentation roleRep: rolesResource.list()) {
String name = roleRep.getName()
if (result.containsKey(name)) {
result[name] = roleRep
}
}
for (Map.Entry<String, RoleRepresentation> resultEntry: result.entrySet()) {
logger.info("got role mapping: (${resultEntry.getKey()})=(${resultEntry.getValue()})")
}
for (Map.Entry<String, RoleRepresentation> resultEntry: result.entrySet()) {
String name = resultEntry.getKey()
if (resultEntry.getValue() == null) {
rolesResource.create(new RoleRepresentation(name, "", false))
resultEntry.setValue(rolesResource.get(name).toRepresentation())
}
}
return result
}
// return getKeycloakGroup(realm, "moqui:userGroup:${userGroup.userGroupId}", sync)
//}
void updateUser(String keycloakUserId, String userId) {
RealmResource realmResource = getKeycloakRealm()
String keycloakClientId = getKeycloakClientId()
ClientResource clientResource = getKeycloakClient()
UsersResource usersResource = realmResource.users()
UserResource userResource = usersResource.get(keycloakUserId)
Timestamp now = ec.user.nowTimestamp
EntityValue userAccount = ec.entity.find('UserAccount').condition('userId', userId).useCache(false).disableAuthz().one()
String partyId = userAccount.partyId
EntityValue person = ec.entity.find('Person').condition('partyId', partyId).useCache(false).disableAuthz().one()
Set<RoleRepresentation> wantedClientRoles = new HashSet<RoleRepresentation>()
List<EntityValue> userGroupMemberList = ec.entity.find('UserGroupMember')
.condition('userId', userId)
.useCache(false)
.disableAuthz()
.list()
.filterByDate('fromDate', 'thruDate', now)
Set<String> userGroupIds = new HashSet<String>(userGroupMemberList*.userGroupId)
logger.info("userGroupIds: ${userGroupIds}")
userGroupIds.add('ALL_USERS')
wantedClientRoles.addAll(userGroupIds.collect { userGroupId -> syncUserGroup(userGroupId).toRepresentation() })
UserRepresentation userRep = userResource.toRepresentation()
Map<String, List<String>> attributes = new HashMap(userRep.getAttributes() ?: [:])
attributes['moqui:now'] = [now.toString()]
logger.info("user[$userId]} attributes: " + attributes)
userRep.setAttributes(attributes)
if (person) {
userRep.setFirstName(person.firstName)
userRep.setLastName(person.lastName)
}
List<RoleRepresentation> toRemove = []
RoleMappingResource roleMappingResource = userResource.roles()
ClientMappingsRepresentation clientMappingsRespresentation = roleMappingResource.getAll().getClientMappings()?[keycloakClientId]
for (RoleRepresentation existingRoleRep: clientMappingsRespresentation?.getMappings()) {
if (!wantedClientRoles.remove(existingRoleRep.getName())) {
toRemove.add(existingRoleRep)
}
}
List<RoleRepresentation> toAdd = wantedClientRoles as List
logger.info("roles to remove: ${toRemove}")
logger.info("roles to add: ${toAdd}")
RoleScopeResource clientRoleScopeResource = roleMappingResource.clientLevel(keycloakClientId)
clientRoleScopeResource.remove(toRemove)
clientRoleScopeResource.add(toAdd)
userRep.setEnabled("N".equals(userAccount.disabled))
userResource.update(userRep)
}