Search in sources :

Example 11 with ApplicationFormItemData

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

the class RegistrarManagerImpl method storeApplicationLoginAttributes.

/**
	 * Store only login attributes from application to user.
	 *
	 * New values are set only if old are empty to prevent overwrite when joining identities.
	 * Empty new values are skipped.
	 *
	 * User must already exists !!
	 *
	 * @param app Application to process attributes for
	 * @throws PerunException
	 */
private void storeApplicationLoginAttributes(Application app) throws PerunException {
    // user must exists
    User user = usersManager.getUserById(registrarSession, app.getUser().getId());
    // get all app items
    List<ApplicationFormItemData> items = getApplicationDataById(registrarSession, app.getId());
    // attributes to set
    List<Attribute> attributes = new ArrayList<Attribute>();
    for (ApplicationFormItemData item : items) {
        String destAttr = item.getFormItem().getPerunDestinationAttribute();
        String newValue = item.getValue();
        // do not store null or empty values at all
        if (newValue == null || newValue.isEmpty())
            continue;
        // if correct destination attribute
        if (destAttr != null && !destAttr.isEmpty()) {
            // get login attribute (for user only)
            Attribute a = null;
            if (destAttr.contains(AttributesManager.NS_USER_ATTR_DEF + ":login-namespace:")) {
                a = attrManager.getAttribute(registrarSession, user, destAttr);
            } else {
                continue;
            }
            // if attribute exists
            if (a != null) {
                // skip if login already existed
                if (a.getValue() != null && !((String) a.getValue()).isEmpty()) {
                    continue;
                } else {
                    // set login attribute if initial (new) value
                    a.setValue(newValue);
                    attributes.add(a);
                }
            }
        }
    }
    // set attributes
    if (!attributes.isEmpty()) {
        // set them if not empty (user)
        attrManager.setAttributes(registrarSession, user, attributes);
    }
}
Also used : ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData)

Example 12 with ApplicationFormItemData

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

the class Metacentrum method approveApplication.

/**
	 * Add all new Metacentrum members to "storage" group.
	 */
@Override
public Application approveApplication(PerunSession session, Application app) throws PerunException {
    // get perun from session
    Perun perun = session.getPerun();
    if (Application.AppType.INITIAL.equals(app.getType())) {
        Vo vo = app.getVo();
        User user = app.getUser();
        Group group = perun.getGroupsManager().getGroupByName(session, vo, "storage");
        Member mem = perun.getMembersManager().getMemberByUser(session, vo, user);
        try {
            perun.getGroupsManager().addMember(session, group, mem);
        } catch (AlreadyMemberException ex) {
        }
    }
    // Support statistic groups
    String statisticGroupName = "";
    List<ApplicationFormItemData> formData = registrar.getApplicationDataById(session, app.getId());
    for (ApplicationFormItemData item : formData) {
        if (Objects.equals("urn:perun:user:attribute-def:def:researchGroupStatistic", item.getFormItem().getPerunDestinationAttribute())) {
            statisticGroupName = item.getValue();
            break;
        }
    }
    if (statisticGroupName != null && !statisticGroupName.isEmpty()) {
        Group group;
        try {
            group = perun.getGroupsManager().getGroupByName(session, app.getVo(), statisticGroupName);
        } catch (GroupNotExistsException ex) {
            // user filled non existing group, just skip adding
            return app;
        } catch (InternalErrorException ex) {
            // wrong group name
            return app;
        }
        Attribute isStatisticGroup = perun.getAttributesManager().getAttribute(session, group, "urn:perun:group:attribute-def:def:statisticGroup");
        Attribute isStatisticGroupAutoFill = perun.getAttributesManager().getAttribute(session, group, "urn:perun:group:attribute-def:def:statisticGroupAutoFill");
        boolean statisticGroup = (isStatisticGroup.getValue() != null) ? (Boolean) isStatisticGroup.getValue() : false;
        boolean statisticGroupAutoFill = (isStatisticGroupAutoFill.getValue() != null) ? (Boolean) isStatisticGroupAutoFill.getValue() : false;
        if (statisticGroup && statisticGroupAutoFill) {
            try {
                Member mem = perun.getMembersManager().getMemberByUser(session, app.getVo(), app.getUser());
                perun.getGroupsManager().addMember(session, group, mem);
            } catch (AlreadyMemberException ex) {
            }
        }
    }
    return app;
}
Also used : GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) AlreadyMemberException(cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException) ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Example 13 with ApplicationFormItemData

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

the class Metacentrum method canBeApproved.

@Override
public void canBeApproved(PerunSession session, Application app) throws PerunException {
    // allow hostel with loa=2
    if (Objects.equals(app.getExtSourceName(), "https://idp.hostel.eduid.cz/idp/shibboleth") && app.getExtSourceLoa() == 2)
        return;
    List<ApplicationFormItemData> data = registrar.getApplicationDataById(session, app.getId());
    String category = "";
    String affiliation = "";
    for (ApplicationFormItemData item : data) {
        if (item.getFormItem() != null && Objects.equals("md_entityCategory", item.getFormItem().getFederationAttribute())) {
            if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
                category = item.getValue();
                break;
            }
        }
    }
    for (ApplicationFormItemData item : data) {
        if (item.getFormItem() != null && Objects.equals("affiliation", item.getFormItem().getFederationAttribute())) {
            if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
                affiliation = item.getValue();
                break;
            }
        }
    }
    if (category.contains("http://eduid.cz/uri/idp-group/university")) {
        if (affiliation.contains("employee@") || affiliation.contains("faculty@") || affiliation.contains("member@") || affiliation.contains("student@") || affiliation.contains("staff@"))
            return;
    } else if (category.contains("http://eduid.cz/uri/idp-group/avcr")) {
        if (affiliation.contains("member@"))
            return;
    } else if (category.contains("http://eduid.cz/uri/idp-group/library")) {
        if (affiliation.contains("employee@"))
            return;
    } else if (category.contains("http://eduid.cz/uri/idp-group/hospital")) {
        if (affiliation.contains("employee@"))
            return;
    } else if (category.contains("http://eduid.cz/uri/idp-group/other")) {
        if (affiliation.contains("employee@") || affiliation.contains("member@"))
            return;
    }
    throw new CantBeApprovedException("User is not active academia member", "NOT_ACADEMIC", category, affiliation, true);
}
Also used : CantBeApprovedException(cz.metacentrum.perun.registrar.exceptions.CantBeApprovedException) ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData)

Example 14 with ApplicationFormItemData

use of cz.metacentrum.perun.registrar.model.ApplicationFormItemData 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)

Example 15 with ApplicationFormItemData

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

the class Du method beforeApprove.

@Override
public Application beforeApprove(PerunSession session, Application app) throws PerunException {
    List<ApplicationFormItemData> data = registrar.getApplicationDataById(session, app.getId());
    // if hostel with LoA = 2 => OK
    if (Objects.equals(app.getExtSourceName(), "https://idp.hostel.eduid.cz/idp/shibboleth") && app.getExtSourceLoa() == 2)
        return app;
    // For others check IdP attributes
    String category = "";
    String affiliation = "";
    for (ApplicationFormItemData item : data) {
        if (item.getFormItem() != null && Objects.equals("md_entityCategory", item.getFormItem().getFederationAttribute())) {
            if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
                category = item.getValue();
                break;
            }
        }
    }
    for (ApplicationFormItemData item : data) {
        if (item.getFormItem() != null && Objects.equals("affiliation", item.getFormItem().getFederationAttribute())) {
            if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
                affiliation = item.getValue();
                break;
            }
        }
    }
    if (category.contains("http://eduid.cz/uri/idp-group/university")) {
        if (affiliation.contains("employee@") || affiliation.contains("faculty@") || affiliation.contains("member@") || affiliation.contains("student@") || affiliation.contains("staff@"))
            return app;
    } else if (category.contains("http://eduid.cz/uri/idp-group/avcr")) {
        if (affiliation.contains("member@"))
            return app;
    } else if (category.contains("http://eduid.cz/uri/idp-group/library")) {
        if (affiliation.contains("employee@"))
            return app;
    } else if (category.contains("http://eduid.cz/uri/idp-group/hospital")) {
        if (affiliation.contains("employee@"))
            return app;
    } else if (category.contains("http://eduid.cz/uri/idp-group/other")) {
        if (affiliation.contains("employee@") || affiliation.contains("member@"))
            return app;
    }
    throw new CantBeApprovedException("User is not active academia member", "NOT_ACADEMIC", category, affiliation);
}
Also used : CantBeApprovedException(cz.metacentrum.perun.registrar.exceptions.CantBeApprovedException) ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData)

Aggregations

ApplicationFormItemData (cz.metacentrum.perun.registrar.model.ApplicationFormItemData)16 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)7 SQLException (java.sql.SQLException)6 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)6 ApplicationFormItem (cz.metacentrum.perun.registrar.model.ApplicationFormItem)5 RegistrarException (cz.metacentrum.perun.registrar.exceptions.RegistrarException)4 MailException (org.springframework.mail.MailException)4 CantBeApprovedException (cz.metacentrum.perun.registrar.exceptions.CantBeApprovedException)3 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)2 Application (cz.metacentrum.perun.registrar.model.Application)2 MailType (cz.metacentrum.perun.registrar.model.ApplicationMail.MailType)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 AlreadyMemberException (cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException)1 ExtSourceNotExistsException (cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException)1 GroupNotExistsException (cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException)1 PerunException (cz.metacentrum.perun.core.api.exceptions.PerunException)1 PrivilegeException (cz.metacentrum.perun.core.api.exceptions.PrivilegeException)1 RegistrarModule (cz.metacentrum.perun.registrar.RegistrarModule)1 AppType (cz.metacentrum.perun.registrar.model.Application.AppType)1