Search in sources :

Example 41 with UserType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.UserType 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);
}
Also used : SecurityQuestionDefinitionType(com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionDefinitionType) HashMap(java.util.HashMap) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonNode(com.fasterxml.jackson.databind.JsonNode) MissingNode(com.fasterxml.jackson.databind.node.MissingNode) IOException(java.io.IOException) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) PrismObject(com.evolveum.midpoint.prism.PrismObject) SecurityQuestionsAuthenticationContext(com.evolveum.midpoint.model.api.context.SecurityQuestionsAuthenticationContext) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) SecurityQuestionAnswerType(com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionAnswerType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 42 with UserType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.UserType 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();
        }
    };
}
Also used : PrismObject(com.evolveum.midpoint.prism.PrismObject) LoadableModel(com.evolveum.midpoint.gui.api.model.LoadableModel) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Example 43 with UserType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.UserType in project midpoint by Evolveum.

the class PersonalInfoPanel method loadPersonalInfo.

private PersonalInfoDto loadPersonalInfo() {
    UserType user = SecurityUtils.getPrincipalUser().getUser();
    CredentialsType credentials = user.getCredentials();
    PersonalInfoDto dto = new PersonalInfoDto();
    if (credentials != null) {
        PasswordType password = credentials.getPassword();
        if (password.getPreviousSuccessfulLogin() != null) {
            dto.setLastLoginDate(MiscUtil.asDate(password.getPreviousSuccessfulLogin().getTimestamp()));
            dto.setLastLoginFrom(password.getPreviousSuccessfulLogin().getFrom());
        }
        if (password.getLastFailedLogin() != null) {
            dto.setLastFailDate(MiscUtil.asDate(password.getLastFailedLogin().getTimestamp()));
            dto.setLastFailFrom(password.getLastFailedLogin().getFrom());
        }
    }
    if (user.getActivation() != null) {
        //todo fix, this is not password expiration date...
        dto.setPasswordExp(MiscUtil.asDate(user.getActivation().getValidTo()));
    }
    return dto;
}
Also used : CredentialsType(com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType) PersonalInfoDto(com.evolveum.midpoint.web.page.admin.home.dto.PersonalInfoDto) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) PasswordType(com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType)

Example 44 with UserType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.UserType in project midpoint by Evolveum.

the class PageMyPasswordQuestions method loadUserWrapper.

private ObjectWrapper loadUserWrapper(PrismObject<UserType> userToEdit) {
    OperationResult result = new OperationResult(OPERATION_LOAD_USER);
    PrismObject<UserType> user = null;
    Task task = createSimpleTask(OPERATION_LOAD_USER);
    try {
        Collection options = SelectorOptions.createCollection(UserType.F_CREDENTIALS, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
        user = getModelService().getObject(UserType.class, SecurityUtils.getPrincipalUser().getOid(), options, task, result);
        result.recordSuccess();
    } catch (Exception ex) {
        result.recordFatalError("Couldn't get user.", ex);
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load user PageMyQuestions", ex);
    }
    showResult(result, false);
    if (user == null) {
        throw new RestartResponseException(PageDashboard.class);
    }
    ContainerStatus status = ContainerStatus.MODIFYING;
    ObjectWrapperFactory owf = new ObjectWrapperFactory(this);
    ObjectWrapper wrapper;
    try {
        wrapper = owf.createObjectWrapper("pageMyPasswordQuestions.userDetails", null, user, status, task);
    } catch (Exception ex) {
        result.recordFatalError("Couldn't get user.", ex);
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load user", ex);
        wrapper = owf.createObjectWrapper("pageMyPasswordQuestions.userDetails", null, user, null, null, status, false);
    }
    //        ObjectWrapper wrapper = new ObjectWrapper("pageUser.userDetails", null, user, status);
    showResult(wrapper.getResult(), false);
    return wrapper;
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ContainerStatus(com.evolveum.midpoint.web.component.prism.ContainerStatus) RestartResponseException(org.apache.wicket.RestartResponseException) Collection(java.util.Collection) ObjectWrapper(com.evolveum.midpoint.web.component.prism.ObjectWrapper) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectWrapperFactory(com.evolveum.midpoint.web.component.prism.ObjectWrapperFactory) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) RestartResponseException(org.apache.wicket.RestartResponseException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException)

Example 45 with UserType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.UserType in project midpoint by Evolveum.

the class PageMyPasswordQuestions method updateQuestions.

private void updateQuestions(String useroid, AjaxRequestTarget target) {
    Task task = createSimpleTask(OPERATION_SAVE_QUESTIONS);
    OperationResult result = new OperationResult(OPERATION_SAVE_QUESTIONS);
    SchemaRegistry registry = getPrismContext().getSchemaRegistry();
    SecurityQuestionAnswerType[] answerTypeList = new SecurityQuestionAnswerType[questionNumber];
    try {
        int listnum = 0;
        for (Iterator iterator = pqPanels.iterator(); iterator.hasNext(); ) {
            MyPasswordQuestionsPanel type = (MyPasswordQuestionsPanel) iterator.next();
            SecurityQuestionAnswerType answerType = new SecurityQuestionAnswerType();
            ProtectedStringType answer = new ProtectedStringType();
            answer.setClearValue(((TextField<String>) type.get(MyPasswordQuestionsPanel.F_ANSWER)).getModelObject());
            answerType.setQuestionAnswer(answer);
            //used apache's unescapeHtml method for special chars like \'
            String results = StringEscapeUtils.unescapeHtml((type.get(MyPasswordQuestionsPanel.F_QUESTION)).getDefaultModelObjectAsString());
            answerType.setQuestionIdentifier(getQuestionIdentifierFromQuestion(results));
            answerTypeList[listnum] = answerType;
            listnum++;
        }
        //if(answerTypeList.length !=)
        // fill in answerType data here
        ItemPath path = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER);
        ObjectDelta<UserType> objectDelta = ObjectDelta.createModificationReplaceContainer(UserType.class, useroid, path, getPrismContext(), answerTypeList);
        Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(objectDelta);
        getModelService().executeChanges(deltas, null, task, result);
        /*			
			System.out.println("getModel");
			 Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
			PasswordQuestionsDto dto = new PasswordQuestionsDto();
			 PrismObjectDefinition objDef =registry.findObjectDefinitionByCompileTimeClass(UserType.class);
			 Class<? extends ObjectType> type =  UserType.class;

			 final ItemPath valuePath = new ItemPath(SchemaConstantsGenerated.C_CREDENTIALS,
	                  CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER); 
			 SecurityQuestionAnswerType secQuesAnsType= new SecurityQuestionAnswerType();
			 ProtectedStringType protStrType= new ProtectedStringType();
			 protStrType.setClearValue("deneme");
			 secQuesAnsType.setQuestionAnswer(protStrType);
			 dto.setSecurityAnswers(new ArrayList<SecurityQuestionAnswerType>());
			 dto.getSecurityAnswers().add(secQuesAnsType);

			PropertyDelta delta = PropertyDelta.createModificationReplaceProperty(valuePath, objDef, dto.getSecurityAnswers().get(0).getQuestionAnswer());
		//	PropertyDelta delta= PropertyDelta.createModifica

			 System.out.println("Update Questions3");
			deltas.add(ObjectDelta.createModifyDelta(useroid, delta, type, getPrismContext()));
			System.out.println("Update Questions4");
			getModelService().executeChanges(deltas, null, createSimpleTask(OPERATION_SAVE_QUESTIONS), result);
			System.out.println("Update Questions5");

			 */
        success(getString("message.success"));
        target.add(getFeedbackPanel());
    } catch (Exception ex) {
        error(getString("message.error"));
        target.add(getFeedbackPanel());
        ex.printStackTrace();
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) RestartResponseException(org.apache.wicket.RestartResponseException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) Iterator(java.util.Iterator) MyPasswordQuestionsPanel(com.evolveum.midpoint.web.page.admin.home.component.MyPasswordQuestionsPanel) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) SchemaRegistry(com.evolveum.midpoint.prism.schema.SchemaRegistry) SecurityQuestionAnswerType(com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionAnswerType) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Aggregations

UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)1275 Test (org.testng.annotations.Test)1093 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1079 Task (com.evolveum.midpoint.task.api.Task)962 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)403 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)379 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)235 ObjectType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)227 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)224 ArrayList (java.util.ArrayList)138 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)115 DummyAccount (com.evolveum.icf.dummy.resource.DummyAccount)114 PrismObject (com.evolveum.midpoint.prism.PrismObject)88 ObjectReferenceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType)88 AbstractModelIntegrationTest (com.evolveum.midpoint.model.test.AbstractModelIntegrationTest)85 TestValidityRecomputeTask (com.evolveum.midpoint.model.intest.sync.TestValidityRecomputeTask)77 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)77 QName (javax.xml.namespace.QName)66 OperationResultType (com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType)64 PrismPropertyDefinition (com.evolveum.midpoint.prism.PrismPropertyDefinition)63