Search in sources :

Example 1 with Type

use of cz.metacentrum.perun.registrar.model.ApplicationFormItem.Type in project perun by CESNET.

the class RegistrarManagerImpl method createApplicationInternal.

@Override
@Transactional(rollbackFor = ApplicationNotCreatedException.class)
public Application createApplicationInternal(PerunSession session, Application application, List<ApplicationFormItemData> data) throws PerunException {
    // exceptions to send to vo admin with new app created email
    List<Exception> exceptions = new ArrayList<Exception>();
    boolean applicationNotCreated = false;
    try {
        // 1) create application
        int appId = Utils.getNewId(jdbc, "APPLICATION_ID_SEQ");
        application.setId(appId);
        application.setState(AppState.NEW);
        // optional group
        Integer groupId = null;
        Integer userId = null;
        if (application.getGroup() != null) {
            groupId = application.getGroup().getId();
        }
        if (application.getUser() != null) {
            userId = application.getUser().getId();
        }
        jdbc.update("insert into application(id,vo_id,group_id,user_id,apptype,fed_info,extSourceName,extSourceType,extSourceLoa,state,created_by,modified_by) values (?,?,?,?,?,?,?,?,?,?,?,?)", appId, application.getVo().getId(), groupId, userId, application.getType().toString(), application.getFedInfo(), application.getExtSourceName(), application.getExtSourceType(), application.getExtSourceLoa(), application.getState().toString(), application.getCreatedBy(), application.getCreatedBy());
        // 2) process & store app data
        for (ApplicationFormItemData itemData : data) {
            Type itemType = itemData.getFormItem().getType();
            if (itemType == HTML_COMMENT || itemType == SUBMIT_BUTTON || itemType == AUTO_SUBMIT_BUTTON || itemType == PASSWORD || itemType == HEADING)
                continue;
            // Check if mails needs to be validated
            if (itemType == VALIDATED_EMAIL) {
                // default = mail not same as pre-filled
                itemData.setAssuranceLevel("");
                // We must use contains, because IdP can send more than one email, emails are separated by semi-colon
                if (itemData.getPrefilledValue() != null && itemData.getValue() != null && !itemData.getValue().isEmpty()) {
                    if (itemData.getPrefilledValue().toLowerCase().contains(itemData.getValue().toLowerCase())) {
                        itemData.setAssuranceLevel("1");
                    }
                }
                // it's save, empty attributes are not set to DB nor any notification is sent
                if (!itemData.getFormItem().isRequired() && (itemData.getValue() == null || itemData.getValue().isEmpty())) {
                    itemData.setAssuranceLevel("1");
                }
            }
            try {
                itemData.setId(Utils.getNewId(jdbc, "APPLICATION_DATA_ID_SEQ"));
                jdbc.update("insert into application_data(id,app_id,item_id,shortname,value,assurance_level) values (?,?,?,?,?,?)", itemData.getId(), appId, itemData.getFormItem().getId(), itemData.getFormItem().getShortname(), itemData.getValue(), itemData.getAssuranceLevel());
            } catch (Exception ex) {
                // log and store exception so vo manager could see error in notification.
                log.error("[REGISTRAR] Storing form item {} caused exception {}", itemData, ex);
                exceptions.add(ex);
            }
        }
        // 3) process all logins and passwords
        // create list of logins and passwords to process
        List<ApplicationFormItemData> logins = new ArrayList<ApplicationFormItemData>();
        for (ApplicationFormItemData itemData : data) {
            Type itemType = itemData.getFormItem().getType();
            if (itemType == USERNAME || itemType == PASSWORD) {
                // skip unchanged pre-filled logins, since they must have been handled last time
                if (itemData.getValue().equals(itemData.getPrefilledValue()) && itemType != PASSWORD)
                    continue;
                logins.add(itemData);
            }
        }
        for (ApplicationFormItemData loginItem : logins) {
            if (loginItem.getFormItem().getType() == USERNAME) {
                // values to store
                String login = loginItem.getValue();
                // filled later
                String pass = "";
                // Get login namespace
                String dstAttr = loginItem.getFormItem().getPerunDestinationAttribute();
                AttributeDefinition loginAttribute = attrManager.getAttributeDefinition(registrarSession, dstAttr);
                String loginNamespace = loginAttribute.getFriendlyNameParameter();
                // try to book new login in namespace if the application hasn't been approved yet
                if (perun.getUsersManagerBl().isLoginAvailable(registrarSession, loginNamespace, login)) {
                    try {
                        // Reserve login
                        jdbc.update("insert into application_reserved_logins(login,namespace,app_id,created_by,created_at) values(?,?,?,?,?)", login, loginNamespace, appId, application.getCreatedBy(), new Date());
                        log.debug("[REGISTRAR] Added login reservation for login: {} in namespace: {}.", login, loginNamespace);
                        // process password for this login
                        for (ApplicationFormItemData passItem : logins) {
                            ApplicationFormItem item = passItem.getFormItem();
                            if (item.getType() == PASSWORD && item.getPerunDestinationAttribute() != null) {
                                if (item.getPerunDestinationAttribute().equals(dstAttr)) {
                                    pass = passItem.getValue();
                                    try {
                                        // reserve password
                                        perun.getUsersManagerBl().reservePassword(registrarSession, login, loginNamespace, pass);
                                        log.debug("[REGISTRAR] Password for login: {} in namespace: {} successfully reserved in external system.", login, loginNamespace);
                                    } catch (Exception ex) {
                                        // login reservation fail must cause rollback !!
                                        log.error("[REGISTRAR] Unable to reserve password for login: {} in namespace: {} in external system. Exception: " + ex, login, loginNamespace);
                                        throw new ApplicationNotCreatedException("Application was not created. Reason: Unable to reserve password for login: " + login + " in namespace: " + loginNamespace + " in external system. Please contact support to fix this issue before new application submission.", login, loginNamespace);
                                    }
                                    // use first pass with correct namespace
                                    break;
                                }
                            }
                        }
                    } catch (ApplicationNotCreatedException ex) {
                        // re-throw
                        throw ex;
                    } catch (Exception ex) {
                        // unable to book login
                        log.error("[REGISTRAR] Unable to reserve login: {} in namespace: {}. Exception: " + ex, login, loginNamespace);
                        exceptions.add(ex);
                    }
                } else {
                    // login is not available
                    log.error("[REGISTRAR] Login: " + login + " in namespace: " + loginNamespace + " is already occupied but it shouldn't (race condition).");
                    exceptions.add(new InternalErrorException("Login: " + login + " in namespace: " + loginNamespace + " is already occupied but it shouldn't."));
                }
            }
        }
        // call registrar module before auto validation so createAction is trigerred first
        RegistrarModule module;
        if (application.getGroup() != null) {
            module = getRegistrarModule(getFormForGroup(application.getGroup()));
        } else {
            module = getRegistrarModule(getFormForVo(application.getVo()));
        }
        if (module != null) {
            module.createApplication(session, application, data);
        }
    } catch (ApplicationNotCreatedException ex) {
        // prevent action in finally block
        applicationNotCreated = true;
        // re-throw
        throw ex;
    } catch (Exception ex) {
        // any exception during app creation process => add it to list
        // exceptions when handling logins are catched before
        log.error("{}", ex);
        exceptions.add(ex);
    } finally {
        // process rest only if it was not exception related to PASSWORDS creation
        if (!applicationNotCreated) {
            getMailManager().sendMessage(application, MailType.APP_CREATED_USER, null, null);
            getMailManager().sendMessage(application, MailType.APP_CREATED_VO_ADMIN, null, exceptions);
            // if there were exceptions, throw some to let know GUI about it
            if (!exceptions.isEmpty()) {
                RegistrarException ex = new RegistrarException("Your application (ID=" + application.getId() + ") has been created with errors. Administrator of " + application.getVo().getName() + " has been notified. If you want, you can use \"Send report to RT\" button to send this information to administrators directly.");
                log.error("[REGISTRAR] New application {} created with errors {}. This is case of PerunException {}", new Object[] { application, exceptions, ex.getErrorId() });
                throw ex;
            }
            log.info("New application {} created.", application);
            perun.getAuditer().log(session, "New {} created.", application);
        }
    }
    // return stored data
    return application;
}
Also used : ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) SQLException(java.sql.SQLException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) MailType(cz.metacentrum.perun.registrar.model.ApplicationMail.MailType) Type(cz.metacentrum.perun.registrar.model.ApplicationFormItem.Type) AppType(cz.metacentrum.perun.registrar.model.Application.AppType) RegistrarModule(cz.metacentrum.perun.registrar.RegistrarModule) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

RegistrarModule (cz.metacentrum.perun.registrar.RegistrarModule)1 AppType (cz.metacentrum.perun.registrar.model.Application.AppType)1 ApplicationFormItem (cz.metacentrum.perun.registrar.model.ApplicationFormItem)1 Type (cz.metacentrum.perun.registrar.model.ApplicationFormItem.Type)1 ApplicationFormItemData (cz.metacentrum.perun.registrar.model.ApplicationFormItemData)1 MailType (cz.metacentrum.perun.registrar.model.ApplicationMail.MailType)1 SQLException (java.sql.SQLException)1 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)1 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)1 Transactional (org.springframework.transaction.annotation.Transactional)1