-
Notifications
You must be signed in to change notification settings - Fork 188
/
UserProfileServiceImpl.java
347 lines (299 loc) · 15.2 KB
/
UserProfileServiceImpl.java
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
/*
* Copyright (c) 2010-2016 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.model.impl.security;
import com.evolveum.midpoint.common.ActivationComputer;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.model.api.PolicyViolationException;
import com.evolveum.midpoint.model.api.context.EvaluatedAssignment;
import com.evolveum.midpoint.model.common.expression.ItemDeltaItem;
import com.evolveum.midpoint.model.common.expression.ObjectDeltaObject;
import com.evolveum.midpoint.model.common.mapping.MappingFactory;
import com.evolveum.midpoint.model.impl.UserComputer;
import com.evolveum.midpoint.model.impl.lens.AssignmentEvaluator;
import com.evolveum.midpoint.model.impl.lens.LensContext;
import com.evolveum.midpoint.model.impl.lens.LensContextPlaceholder;
import com.evolveum.midpoint.model.impl.lens.LensUtil;
import com.evolveum.midpoint.model.impl.lens.projector.MappingEvaluator;
import com.evolveum.midpoint.prism.PrismContainerDefinition;
import com.evolveum.midpoint.prism.PrismContainerValue;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.EqualFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.AdminGuiConfigTypeUtil;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.ObjectResolver;
import com.evolveum.midpoint.security.api.Authorization;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.UserProfileService;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author lazyman
* @author semancik
*/
@Service(value = "userDetailsService")
public class UserProfileServiceImpl implements UserProfileService, UserDetailsService, UserDetailsContextMapper {
private static final Trace LOGGER = TraceManager.getTrace(UserProfileServiceImpl.class);
@Autowired(required = true)
private transient RepositoryService repositoryService;
@Autowired(required = true)
private ObjectResolver objectResolver;
@Autowired(required = true)
private MappingFactory mappingFactory;
@Autowired(required = true)
private MappingEvaluator mappingEvaluator;
@Autowired(required = true)
private UserComputer userComputer;
@Autowired(required = true)
private ActivationComputer activationComputer;
@Autowired(required = true)
private Clock clock;
@Autowired(required = true)
private PrismContext prismContext;
@Autowired(required = true)
private TaskManager taskManager;
@Override
public MidPointPrincipal getPrincipal(String username) throws ObjectNotFoundException {
OperationResult result = new OperationResult(OPERATION_GET_PRINCIPAL);
PrismObject<UserType> user = null;
try {
user = findByUsername(username, result);
} catch (ObjectNotFoundException ex) {
LOGGER.trace("Couldn't find user with name '{}', reason: {}.",
new Object[]{username, ex.getMessage(), ex});
throw ex;
} catch (Exception ex) {
LOGGER.warn("Error getting user with name '{}', reason: {}.",
new Object[]{username, ex.getMessage(), ex});
throw new SystemException(ex.getMessage(), ex);
}
return createPrincipal(user, result);
}
@Override
public MidPointPrincipal getPrincipal(PrismObject<UserType> user) {
OperationResult result = new OperationResult(OPERATION_GET_PRINCIPAL);
return createPrincipal(user, result);
}
private MidPointPrincipal createPrincipal(PrismObject<UserType> user, OperationResult result) {
if (user == null) {
return null;
}
PrismObject<SystemConfigurationType> systemConfiguration = null;
try {
systemConfiguration = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(),
null, result);
} catch (ObjectNotFoundException | SchemaException e) {
LOGGER.warn("No system configuration: {}", e.getMessage(), e);
}
userComputer.recompute(user);
MidPointPrincipal principal = new MidPointPrincipal(user.asObjectable());
initializePrincipalFromAssignments(principal, systemConfiguration);
return principal;
}
@Override
public void updateUser(MidPointPrincipal principal) {
OperationResult result = new OperationResult(OPERATION_UPDATE_USER);
try {
save(principal, result);
} catch (Exception ex) {
LOGGER.warn("Couldn't save user '{}, ({})', reason: {}.",
new Object[]{principal.getFullName(), principal.getOid(), ex.getMessage(), ex});
}
}
private PrismObject<UserType> findByUsername(String username, OperationResult result) throws SchemaException, ObjectNotFoundException {
PolyString usernamePoly = new PolyString(username);
ObjectQuery query = ObjectQueryUtil.createNormNameQuery(usernamePoly, prismContext);
LOGGER.trace("Looking for user, query:\n" + query.debugDump());
List<PrismObject<UserType>> list = repositoryService.searchObjects(UserType.class, query, null,
result);
LOGGER.trace("Users found: {}.", (list != null ? list.size() : 0));
if (list == null || list.size() != 1) {
return null;
}
return list.get(0);
}
private void initializePrincipalFromAssignments(MidPointPrincipal principal, PrismObject<SystemConfigurationType> systemConfiguration) {
UserType userType = principal.getUser();
Collection<Authorization> authorizations = principal.getAuthorities();
Collection<AdminGuiConfigurationType> adminGuiConfigurations = new ArrayList<>();
Task task = taskManager.createTaskInstance(UserProfileServiceImpl.class.getName() + ".addAuthorizations");
OperationResult result = task.getResult();
principal.setApplicableSecurityPolicy(locateSecurityPolicy(principal, systemConfiguration, task, result));
if (userType.getAssignment().isEmpty()) {
if (systemConfiguration != null) {
principal.setAdminGuiConfiguration(systemConfiguration.asObjectable().getAdminGuiConfiguration());
}
return;
}
AssignmentEvaluator<UserType> assignmentEvaluator = new AssignmentEvaluator<>();
assignmentEvaluator.setRepository(repositoryService);
assignmentEvaluator.setFocusOdo(new ObjectDeltaObject<UserType>(userType.asPrismObject(), null, userType.asPrismObject()));
assignmentEvaluator.setChannel(null);
assignmentEvaluator.setObjectResolver(objectResolver);
assignmentEvaluator.setPrismContext(prismContext);
assignmentEvaluator.setMappingFactory(mappingFactory);
assignmentEvaluator.setMappingEvaluator(mappingEvaluator);
assignmentEvaluator.setActivationComputer(activationComputer);
assignmentEvaluator.setNow(clock.currentTimeXMLGregorianCalendar());
// We do need only authorizations. Therefore we not need to evaluate constructions,
// so switching it off is faster. It also avoids nasty problems with resources being down,
// resource schema not available, etc.
assignmentEvaluator.setEvaluateConstructions(false);
// We do not have real lens context here. But the push methods in ModelExpressionThreadLocalHolder
// will need something to push on the stack. So give them context placeholder.
LensContext<UserType> lensContext = new LensContextPlaceholder<>(prismContext);
assignmentEvaluator.setLensContext(lensContext);
for(AssignmentType assignmentType: userType.getAssignment()) {
try {
ItemDeltaItem<PrismContainerValue<AssignmentType>,PrismContainerDefinition<AssignmentType>> assignmentIdi = new ItemDeltaItem<>();
assignmentIdi.setItemOld(LensUtil.createAssignmentSingleValueContainerClone(assignmentType));
assignmentIdi.recompute();
EvaluatedAssignment<UserType> assignment = assignmentEvaluator.evaluate(assignmentIdi, false, userType, userType.toString(), task, result);
if (assignment.isValid()) {
authorizations.addAll(assignment.getAuthorizations());
adminGuiConfigurations.addAll(assignment.getAdminGuiConfigurations());
}
} catch (SchemaException e) {
LOGGER.error("Schema violation while processing assignment of {}: {}; assignment: {}",
new Object[]{userType, e.getMessage(), assignmentType, e});
} catch (ObjectNotFoundException e) {
LOGGER.error("Object not found while processing assignment of {}: {}; assignment: {}",
new Object[]{userType, e.getMessage(), assignmentType, e});
} catch (ExpressionEvaluationException e) {
LOGGER.error("Evaluation error while processing assignment of {}: {}; assignment: {}",
new Object[]{userType, e.getMessage(), assignmentType, e});
} catch (PolicyViolationException e) {
LOGGER.error("Policy violation while processing assignment of {}: {}; assignment: {}",
new Object[]{userType, e.getMessage(), assignmentType, e});
}
}
principal.setAdminGuiConfiguration(AdminGuiConfigTypeUtil.compileAdminGuiConfiguration(adminGuiConfigurations, systemConfiguration));
}
private SecurityPolicyType locateSecurityPolicy(MidPointPrincipal principal, PrismObject<SystemConfigurationType> systemConfiguration, Task task, OperationResult result) {
if (systemConfiguration == null) {
return null;
}
ObjectReferenceType globalSecurityPolicyRef = systemConfiguration.asObjectable().getGlobalSecurityPolicyRef();
if (globalSecurityPolicyRef == null) {
return null;
}
try {
return objectResolver.resolve(globalSecurityPolicyRef, SecurityPolicyType.class, null, "global security policy reference in system configuration", task, result);
} catch (ObjectNotFoundException | SchemaException e) {
LOGGER.error(e.getMessage(), e);
return null;
}
}
private MidPointPrincipal save(MidPointPrincipal person, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
UserType oldUserType = getUserByOid(person.getOid(), result);
PrismObject<UserType> oldUser = oldUserType.asPrismObject();
PrismObject<UserType> newUser = person.getUser().asPrismObject();
ObjectDelta<UserType> delta = oldUser.diff(newUser);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Updating user {} with delta:\n{}", newUser, delta.debugDump());
}
repositoryService.modifyObject(UserType.class, delta.getOid(), delta.getModifications(),
new OperationResult(OPERATION_UPDATE_USER));
return person;
}
private UserType getUserByOid(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException {
ObjectType object = repositoryService.getObject(UserType.class, oid,
null, result).asObjectable();
if (object != null && (object instanceof UserType)) {
return (UserType) object;
}
return null;
}
@Override
public <F extends FocusType, O extends ObjectType> PrismObject<F> resolveOwner(PrismObject<O> object) {
if (object == null || object.getOid() == null) {
return null;
}
PrismObject<F> owner = null;
if (object.canRepresent(ShadowType.class)) {
owner = repositoryService.searchShadowOwner(object.getOid(), null, new OperationResult(UserProfileServiceImpl.class+".resolveOwner"));
} else if (object.canRepresent(AbstractRoleType.class)) {
ObjectReferenceType ownerRef = ((AbstractRoleType)(object.asObjectable())).getOwnerRef();
if (ownerRef != null && ownerRef.getOid() != null && ownerRef.getType() != null) {
OperationResult result = new OperationResult(UserProfileService.class.getName() + ".resolveOwner");
try {
owner = (PrismObject<F>) repositoryService.getObject(ObjectTypes.getObjectTypeFromTypeQName(ownerRef.getType()).getClassDefinition(),
ownerRef.getOid(), null, result);
} catch (ObjectNotFoundException | SchemaException e) {
LOGGER.warn("Cannot resolve owner of {}: {}", object, e.getMessage(), e);
}
}
}
if (owner == null) {
return null;
}
if (owner.canRepresent(UserType.class)) {
userComputer.recompute((PrismObject<UserType>)owner);
}
return owner;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
return getPrincipal(username);
} catch (ObjectNotFoundException e) {
throw new UsernameNotFoundException(e.getMessage(), e);
}
}
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
try {
return getPrincipal(username);
} catch (ObjectNotFoundException e) {
throw new UsernameNotFoundException(e.getMessage(), e);
}
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
// TODO Auto-generated method stub
}
}