use of com.evolveum.midpoint.prism.PrismObject in project midpoint by Evolveum.
the class ProjectionCredentialsProcessor method processProjectionPasswordMapping.
private <F extends FocusType> void processProjectionPasswordMapping(LensContext<F> context, final LensProjectionContext projCtx, final ValuePolicyType passwordPolicy, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException {
LensFocusContext<F> focusContext = context.getFocusContext();
PrismObject<F> userNew = focusContext.getObjectNew();
if (userNew == null) {
// This must be a user delete or something similar. No point in proceeding
LOGGER.trace("userNew is null, skipping credentials processing");
return;
}
PrismObjectDefinition<ShadowType> accountDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class);
PrismPropertyDefinition<ProtectedStringType> projPasswordPropertyDefinition = accountDefinition.findPropertyDefinition(SchemaConstants.PATH_PASSWORD_VALUE);
ResourceShadowDiscriminator rsd = projCtx.getResourceShadowDiscriminator();
RefinedObjectClassDefinition refinedProjDef = projCtx.getStructuralObjectClassDefinition();
if (refinedProjDef == null) {
LOGGER.trace("No RefinedObjectClassDefinition, therefore also no password outbound definition, skipping credentials processing for projection {}", rsd);
return;
}
List<MappingType> outboundMappingTypes = refinedProjDef.getPasswordOutbound();
if (outboundMappingTypes == null || outboundMappingTypes.isEmpty()) {
LOGGER.trace("No outbound password mapping for {}, skipping credentials processing", rsd);
return;
}
// HACK
if (!projCtx.isDoReconciliation() && !projCtx.isAdd() && !isActivated(outboundMappingTypes, focusContext.getDelta())) {
LOGGER.trace("Outbound password mappings not activated for type {}, skipping credentials processing", rsd);
return;
}
final ObjectDelta<ShadowType> projDelta = projCtx.getDelta();
final PropertyDelta<ProtectedStringType> projPasswordDelta;
if (projDelta != null && projDelta.getChangeType() == MODIFY) {
projPasswordDelta = projDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
} else {
projPasswordDelta = null;
}
checkExistingDeltaSanity(projCtx, projPasswordDelta);
boolean evaluateWeak = getEvaluateWeak(projCtx);
final ItemDeltaItem<PrismPropertyValue<PasswordType>, PrismPropertyDefinition<ProtectedStringType>> userPasswordIdi = focusContext.getObjectDeltaObject().findIdi(SchemaConstants.PATH_PASSWORD_VALUE);
StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {
@Override
public void setOutputPath(ItemPath outputPath) {
}
@Override
public void setOutputDefinition(ItemDefinition outputDefinition) {
}
@Override
public StringPolicyType resolve() {
if (passwordPolicy == null) {
return null;
}
return passwordPolicy.getStringPolicy();
}
};
MappingInitializer<PrismPropertyValue<ProtectedStringType>, PrismPropertyDefinition<ProtectedStringType>> initializer = (builder) -> {
builder.defaultTargetDefinition(projPasswordPropertyDefinition);
builder.defaultSource(new Source<>(userPasswordIdi, ExpressionConstants.VAR_INPUT));
builder.stringPolicyResolver(stringPolicyResolver);
return builder;
};
MappingOutputProcessor<PrismPropertyValue<ProtectedStringType>> processor = (mappingOutputPath, outputStruct) -> {
PrismValueDeltaSetTriple<PrismPropertyValue<ProtectedStringType>> outputTriple = outputStruct.getOutputTriple();
if (outputTriple == null) {
LOGGER.trace("Credentials 'password' expression resulted in null output triple, skipping credentials processing for {}", rsd);
return false;
}
boolean projectionIsNew = projDelta != null && (projDelta.getChangeType() == ChangeType.ADD || projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.ADD);
Collection<PrismPropertyValue<ProtectedStringType>> newValues = outputTriple.getPlusSet();
if (projectionIsNew) {
newValues = outputTriple.getNonNegativeValues();
} else {
newValues = outputTriple.getPlusSet();
}
if (!canGetCleartext(newValues)) {
ObjectDelta<ShadowType> projectionPrimaryDelta = projCtx.getPrimaryDelta();
if (projectionPrimaryDelta != null) {
PropertyDelta<ProtectedStringType> passwordPrimaryDelta = projectionPrimaryDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
if (passwordPrimaryDelta != null) {
// We have only hashed value coming from the mapping. There are not very useful
// for provisioning. But we have primary projection delta - and that is very likely
// to be better.
// Skip all password mappings in this case. Primary delta trumps everything.
// No weak, normal or even strong mapping can change that.
// We need to disregard even strong mapping in this case. If we would heed the strong
// mapping then account initialization won't be possible.
LOGGER.trace("We have primary password delta in projection, skipping credentials processing");
return false;
}
}
}
return true;
};
mappingEvaluator.evaluateOutboundMapping(context, projCtx, outboundMappingTypes, SchemaConstants.PATH_PASSWORD_VALUE, SchemaConstants.PATH_PASSWORD_VALUE, initializer, processor, now, true, evaluateWeak, "password mapping", task, result);
}
use of com.evolveum.midpoint.prism.PrismObject in project midpoint by Evolveum.
the class UserProfileServiceImpl method findByUsername.
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.size());
if (list.size() != 1) {
return null;
}
return list.get(0);
}
use of com.evolveum.midpoint.prism.PrismObject in project midpoint by Evolveum.
the class MidpointRestSecurityQuestionsAuthenticator method createAuthenticationContext.
@Override
protected SecurityQuestionsAuthenticationContext createAuthenticationContext(AuthorizationPolicy policy, ContainerRequestContext requestCtx) {
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(f);
JsonNode node = null;
try {
node = mapper.readTree(policy.getAuthorization());
} catch (IOException e) {
RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, "{" + USER_CHALLENGE + "}");
return null;
}
JsonNode userNameNode = node.findPath("user");
if (userNameNode instanceof MissingNode) {
RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, "{" + USER_CHALLENGE + "}");
return null;
}
String userName = userNameNode.asText();
policy.setUserName(userName);
JsonNode answerNode = node.findPath("answer");
if (answerNode instanceof MissingNode) {
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("restapi", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
SearchResultList<PrismObject<UserType>> users = null;
try {
users = searchUser(userName);
} finally {
SecurityContextHolder.getContext().setAuthentication(null);
}
if (users.size() != 1) {
requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Security question authentication failed. Incorrect username and/or password").build());
return null;
}
PrismObject<UserType> user = users.get(0);
PrismContainer<SecurityQuestionAnswerType> questionAnswerContainer = user.findContainer(SchemaConstants.PATH_SECURITY_QUESTIONS_QUESTION_ANSWER);
if (questionAnswerContainer == null || questionAnswerContainer.isEmpty()) {
requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Security question authentication failed. Incorrect username and/or password").build());
return null;
}
String questionChallenge = "";
List<SecurityQuestionDefinitionType> questions = null;
try {
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("restapi", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
questions = getQuestions(user);
} finally {
SecurityContextHolder.getContext().setAuthentication(null);
}
Collection<SecurityQuestionAnswerType> questionAnswers = questionAnswerContainer.getRealValues();
Iterator<SecurityQuestionAnswerType> questionAnswerIterator = questionAnswers.iterator();
while (questionAnswerIterator.hasNext()) {
SecurityQuestionAnswerType questionAnswer = questionAnswerIterator.next();
SecurityQuestionDefinitionType question = questions.stream().filter(q -> q.getIdentifier().equals(questionAnswer.getQuestionIdentifier())).findFirst().get();
String challenge = QUESTION.replace(Q_ID, question.getIdentifier());
questionChallenge += challenge.replace(Q_TXT, question.getQuestionText());
if (questionAnswerIterator.hasNext()) {
questionChallenge += ",";
}
}
String userChallenge = USER_CHALLENGE.replace("username", userName);
String challenge = "{" + userChallenge + ", \"answer\" : [" + questionChallenge + "]}";
RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, challenge);
return null;
}
ArrayNode answers = (ArrayNode) answerNode;
Iterator<JsonNode> answersList = answers.elements();
Map<String, String> questionAnswers = new HashMap<>();
while (answersList.hasNext()) {
JsonNode answer = answersList.next();
String questionId = answer.findPath("qid").asText();
String questionAnswer = answer.findPath("qans").asText();
questionAnswers.put(questionId, questionAnswer);
}
return new SecurityQuestionsAuthenticationContext(userName, questionAnswers);
}
use of com.evolveum.midpoint.prism.PrismObject in project midpoint by Evolveum.
the class SelectableBeanObjectDataProvider method internalIterator.
@Override
public Iterator<SelectableBean<O>> internalIterator(long offset, long pageSize) {
LOGGER.trace("begin::iterator() offset {} pageSize {}.", new Object[] { offset, pageSize });
// if (pageSize > 1000000) {
// // Failsafe. Do not even try this. This can have huge impact on the resource. (MID-3336)
// throw new IllegalArgumentException("Requested huge page size: "+pageSize);
// }
preprocessSelectedData();
OperationResult result = new OperationResult(OPERATION_SEARCH_OBJECTS);
try {
ObjectPaging paging = createPaging(offset, pageSize);
Task task = getPage().createSimpleTask(OPERATION_SEARCH_OBJECTS);
ObjectQuery query = getQuery();
if (query == null) {
if (emptyListOnNullQuery) {
return new ArrayList<SelectableBean<O>>().iterator();
}
query = new ObjectQuery();
}
query.setPaging(paging);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Query {} with {}", type.getSimpleName(), query.debugDump());
}
if (ResourceType.class.equals(type) && (options == null || options.isEmpty())) {
options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch());
}
List<PrismObject<? extends O>> list = (List) getModel().searchObjects(type, query, options, task, result);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Query {} resulted in {} objects", type.getSimpleName(), list.size());
}
for (PrismObject<? extends O> object : list) {
getAvailableData().add(createDataObjectWrapper(object.asObjectable()));
}
// result.recordSuccess();
} catch (Exception ex) {
result.recordFatalError("Couldn't list objects.", ex);
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't list objects", ex);
return handleNotSuccessOrHandledErrorInIterator(result);
} finally {
result.computeStatusIfUnknown();
}
LOGGER.trace("end::iterator() {}", result);
return getAvailableData().iterator();
}
use of com.evolveum.midpoint.prism.PrismObject in project midpoint by Evolveum.
the class TargetUserSelectorComponent method getTargetUsersButtonTitle.
private IModel<String> getTargetUsersButtonTitle() {
return new LoadableModel<String>(true) {
public String load() {
if (getRoleCatalogStorage().isSelfRequest()) {
return createStringResource("AssignmentCatalogPanel.requestForMe").getString();
}
List<PrismObject<UserType>> targetUsersList = getRoleCatalogStorage().getTargetUserList();
if (targetUsersList.size() == 1) {
return createStringResource("AssignmentCatalogPanel.requestFor").getString() + " " + targetUsersList.get(0).getName().getOrig();
}
StringBuilder sb = new StringBuilder(createStringResource("AssignmentCatalogPanel.requestForMultiple", targetUsersList.size()).getString());
sb.append(System.lineSeparator());
if (getRoleCatalogStorage().isMultiUserRequest()) {
List<PrismObject<UserType>> sortedList = getRoleCatalogStorage().getTargetUserList();
Collections.sort(sortedList, new Comparator<PrismObject<UserType>>() {
@Override
public int compare(PrismObject<UserType> u1, PrismObject<UserType> u2) {
return String.CASE_INSENSITIVE_ORDER.compare(u1.getName().getOrig(), u2.getName().getOrig());
}
});
int columnsAmount = sortedList.size() / TARGET_USERS_TITLE_ROWS;
Iterator<PrismObject<UserType>> it = sortedList.iterator();
while (it.hasNext()) {
for (int i = 0; i <= columnsAmount; i++) {
if (it.hasNext()) {
PrismObject user = it.next();
sb.append(user.getName().getOrig());
if (it.hasNext()) {
sb.append(",\t");
}
}
}
sb.append(System.lineSeparator());
}
}
return sb.toString();
}
};
}
Aggregations