Search in sources :

Example 6 with ApplicationFormItemData

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

the class RegistrarManagerImpl method updateUserNameTitles.

/**
	 * If titles before / after name are part of application form and User exists,
	 * update titles for user according to application.
	 *
	 * This method doesn't clear titles from users name if sent empty in order to prevent
	 * accidental removal when user log-in with different IDP without titles provided.
	 *
	 * @param app Application to update user's titles for.
	 * @throws PerunException
	 */
private void updateUserNameTitles(Application app) {
    try {
        User user = usersManager.getUserById(registrarSession, app.getUser().getId());
        List<ApplicationFormItemData> data = registrarManager.getApplicationDataById(registrarSession, app.getId());
        boolean found = false;
        // first check for display name
        for (ApplicationFormItemData item : data) {
            if (URN_USER_DISPLAY_NAME.equals(item.getFormItem().getPerunDestinationAttribute())) {
                if (item.getValue() != null && !item.getValue().isEmpty()) {
                    Map<String, String> commonName = Utils.parseCommonName(item.getValue());
                    if (commonName.get("titleBefore") != null && !commonName.get("titleBefore").isEmpty()) {
                        user.setTitleBefore(commonName.get("titleBefore"));
                        found = true;
                    }
                    if (commonName.get("titleAfter") != null && !commonName.get("titleAfter").isEmpty()) {
                        user.setTitleAfter(commonName.get("titleAfter"));
                        found = true;
                    }
                }
                break;
            }
        }
        // overwrite by specific before/after name title
        for (ApplicationFormItemData item : data) {
            if (URN_USER_TITLE_BEFORE.equals(item.getFormItem().getPerunDestinationAttribute())) {
                if (item.getValue() != null && !item.getValue().isEmpty()) {
                    user.setTitleBefore(item.getValue());
                    found = true;
                }
            }
            if (URN_USER_TITLE_AFTER.equals(item.getFormItem().getPerunDestinationAttribute())) {
                if (item.getValue() != null && !item.getValue().isEmpty()) {
                    user.setTitleAfter(item.getValue());
                    found = true;
                }
            }
        }
        // titles were part of application form
        if (found) {
            log.debug("[REGISTRAR] User to update titles: {}", user);
            usersManager.updateNameTitles(registrarSession, user);
        }
    } catch (Exception ex) {
        log.error("[REGISTRAR] Exception when updating titles: {}", ex);
    }
}
Also used : ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) SQLException(java.sql.SQLException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException)

Example 7 with ApplicationFormItemData

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

the class BBMRI method getCollectionIDsFromApplication.

/**
	 * Gets collection IDs from a field on the application form with short name.
	 *
	 * @return collection IDs set
	 */
private Set<String> getCollectionIDsFromApplication(PerunSession session, Application app) throws PerunException {
    String collectionsString = null;
    List<ApplicationFormItemData> formData = registrar.getApplicationDataById(session, app.getId());
    for (ApplicationFormItemData field : formData) {
        if (BIOBANK_IDS_FIELD.equals(field.getShortname())) {
            collectionsString = field.getValue();
            break;
        }
    }
    if (collectionsString == null) {
        throw new InternalErrorException("There is no field with biobank IDs on the registration form.");
    }
    // get set of collection IDs from application
    Set<String> collectionIDsInApplication = new HashSet<>();
    for (String collection : collectionsString.split("[,\n ]+")) {
        collectionIDsInApplication.add(collection.trim());
    }
    return collectionIDsInApplication;
}
Also used : ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Example 8 with ApplicationFormItemData

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

the class DuSoft method canBeApproved.

@Override
public void canBeApproved(PerunSession session, Application app) throws PerunException {
    // warn before approval on non-academic
    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;
    // 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;
    } 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 9 with ApplicationFormItemData

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

the class MailManagerImpl method getLanguageFromAppData.

/**
	 * Return preferred Locale from application
	 * (return EN if not found)
	 *
	 * @param data
	 * @return
	 */
private String getLanguageFromAppData(Application app, List<ApplicationFormItemData> data) {
    String language = "en";
    // if user present - get preferred language
    if (app.getUser() != null) {
        try {
            User u = usersManager.getUserById(registrarSession, app.getUser().getId());
            Attribute a = attrManager.getAttribute(registrarSession, u, URN_USER_PREFERRED_LANGUAGE);
            if (a != null && a.getValue() != null) {
                language = BeansUtils.attributeValueToString(a);
            }
        } catch (Exception ex) {
            log.error("[MAIL MANAGER] Exception thrown when getting preferred language for {}: {}", app.getUser(), ex);
        }
    }
    // if preferred language specified on application - rewrite
    for (ApplicationFormItemData item : data) {
        if (item.getFormItem() != null) {
            if (item.getFormItem().getPerunDestinationAttribute() != null && item.getFormItem().getPerunDestinationAttribute().equals(URN_USER_PREFERRED_LANGUAGE)) {
                if (item.getValue() == null || item.getValue().isEmpty()) {
                    // return default
                    return language;
                } else {
                    // or return value
                    return item.getValue();
                }
            }
        }
    }
    // return default
    return language;
}
Also used : ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) SQLException(java.sql.SQLException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RegistrarException(cz.metacentrum.perun.registrar.exceptions.RegistrarException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) MailException(org.springframework.mail.MailException)

Example 10 with ApplicationFormItemData

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

the class MailManagerImpl method sendMessage.

@Override
public void sendMessage(Application app, MailType mailType, String reason, List<Exception> exceptions) {
    try {
        // get form
        ApplicationForm form;
        if (app.getGroup() != null) {
            form = registrarManager.getFormForGroup(app.getGroup());
        } else {
            form = registrarManager.getFormForVo(app.getVo());
        }
        // get mail definition
        ApplicationMail mail = getMailByParams(form.getId(), app.getType(), mailType);
        if (mail == null) {
            log.error("[MAIL MANAGER] Mail not sent. Definition (or mail text) for: {} do not exists for VO: " + app.getVo() + " and Group: " + app.getGroup(), mailType.toString());
            // mail not found
            return;
        } else if (mail.getSend() == false) {
            log.info("[MAIL MANAGER] Mail not sent. Disabled by VO admin for: " + mail.getMailType() + " / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup());
            // sending this mail is disabled by VO admin
            return;
        }
        // get app data
        List<ApplicationFormItemData> data = registrarManager.getApplicationDataById(registrarSession, app.getId());
        // get language
        Locale lang = new Locale(getLanguageFromAppData(app, data));
        // get localized subject and text
        MailText mt = mail.getMessage(lang);
        String mailText = "";
        String mailSubject = "";
        if (mt.getText() != null && !mt.getText().isEmpty()) {
            mailText = mt.getText();
        }
        if (mt.getSubject() != null && !mt.getSubject().isEmpty()) {
            mailSubject = mt.getSubject();
        }
        // different behavior based on mail type
        MailType type = mail.getMailType();
        if (MailType.APP_CREATED_USER.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            setUsersMailAsTo(message, app, data);
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            message.setText(mailText);
            try {
                // send mail
                mailSender.send(message);
                log.info("[MAIL MANAGER] Sending mail: APP_CREATED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
            } catch (MailException ex) {
                log.error("[MAIL MANAGER] Sending mail: APP_CREATED_USER failed because of exception: {}", ex);
            }
        } else if (MailType.APP_CREATED_VO_ADMIN.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set language independent on user's preferred language.
            lang = new Locale("en");
            try {
                if (app.getGroup() == null) {
                    // VO
                    Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                } else {
                    Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                }
            } catch (Exception ex) {
                log.error("Error when resolving notification default language: {}", ex);
            }
            MailText mt2 = mail.getMessage(lang);
            String mailText2 = "";
            String mailSubject2 = "";
            if (mt2.getText() != null && !mt2.getText().isEmpty()) {
                mailText2 = mt2.getText();
            }
            if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
                mailSubject2 = mt2.getSubject();
            }
            // substitute common strings
            mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
            mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject2);
            message.setText(mailText2);
            // send message to all VO or Group admins
            List<String> toEmail = getToMailAddresses(app);
            for (String email : toEmail) {
                message.setTo(email);
                try {
                    mailSender.send(message);
                    log.info("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
                } catch (MailException ex) {
                    log.error("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN failed because of exception: {}", ex);
                }
            }
        } else if (MailType.MAIL_VALIDATION.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            // empty = not sent
            message.setTo("");
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            // send to all emails, which needs to be validated
            for (ApplicationFormItemData d : data) {
                ApplicationFormItem item = d.getFormItem();
                String value = d.getValue();
                // if mail field and not validated
                if (ApplicationFormItem.Type.VALIDATED_EMAIL.equals(item.getType()) && !"1".equals(d.getAssuranceLevel())) {
                    if (value != null && !value.isEmpty()) {
                        // set TO
                        message.setTo(value);
                        // get validation link params
                        String i = Integer.toString(d.getId(), Character.MAX_RADIX);
                        String m = getMessageAuthenticationCode(i);
                        // replace new validation link
                        if (mailText.contains("{validationLink-")) {
                            Pattern pattern = Pattern.compile("\\{validationLink-[^\\}]+\\}");
                            Matcher matcher = pattern.matcher(mailText);
                            while (matcher.find()) {
                                // whole "{validationLink-something}"
                                String toSubstitute = matcher.group(0);
                                // new login value to replace in text
                                String newValue = "";
                                Pattern namespacePattern = Pattern.compile("\\-(.*?)\\}");
                                Matcher m2 = namespacePattern.matcher(toSubstitute);
                                while (m2.find()) {
                                    // only namespace "fed", "cert",...
                                    String namespace = m2.group(1);
                                    newValue = getPerunUrl(app.getVo(), app.getGroup());
                                    if (newValue != null && !newValue.isEmpty()) {
                                        if (!newValue.endsWith("/"))
                                            newValue += "/";
                                        newValue += namespace + "/registrar/";
                                        newValue += "?vo=" + getEncodedString(app.getVo().getShortName());
                                        newValue += ((app.getGroup() != null) ? "&group=" + getEncodedString(app.getGroup().getName()) : "");
                                        try {
                                            newValue += "&i=" + URLEncoder.encode(i, "UTF-8") + "&m=" + URLEncoder.encode(m, "UTF-8");
                                        } catch (UnsupportedEncodingException ex) {
                                            newValue += "&i=" + i + "&m=" + m;
                                        }
                                    }
                                }
                                // substitute {validationLink-authz} with actual value or empty string
                                mailText = mailText.replace(toSubstitute, newValue);
                            }
                        }
                        if (mailText.contains("{validationLink}")) {
                            // new backup if validation URL is missing
                            String url = getPerunUrl(app.getVo(), app.getGroup());
                            if (url != null && !url.isEmpty()) {
                                if (!url.endsWith("/"))
                                    url += "/";
                                url += "registrar/";
                            }
                            if (url != null && !url.isEmpty())
                                url = url + "?vo=" + getEncodedString(app.getVo().getShortName());
                            if (app.getGroup() != null) {
                                // append group name for
                                if (url != null && !url.isEmpty())
                                    url += "&group=" + getEncodedString(app.getGroup().getName());
                            }
                            // construct whole url
                            StringBuilder url2 = new StringBuilder(url);
                            if (url.contains("?")) {
                                if (!url.endsWith("?")) {
                                    url2.append("&");
                                }
                            } else {
                                if (!url2.toString().isEmpty())
                                    url2.append("?");
                            }
                            try {
                                if (!url2.toString().isEmpty())
                                    url2.append("i=").append(URLEncoder.encode(i, "UTF-8")).append("&m=").append(URLEncoder.encode(m, "UTF-8"));
                            } catch (UnsupportedEncodingException ex) {
                                if (!url2.toString().isEmpty())
                                    url2.append("i=").append(i).append("&m=").append(m);
                            }
                            // replace validation link
                            mailText = mailText.replace("{validationLink}", url2.toString());
                        }
                        // set replaced text
                        message.setText(mailText);
                        try {
                            mailSender.send(message);
                            log.info("[MAIL MANAGER] Sending mail: MAIL_VALIDATION to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
                        } catch (MailException ex) {
                            log.error("[MAIL MANAGER] Sending mail: MAIL_VALIDATION failed because of exception: {}", ex);
                        }
                    } else {
                        log.error("[MAIL MANAGER] Sending mail: MAIL_VALIDATION failed. Not valid value of VALIDATED_MAIL field: {}", value);
                    }
                }
            }
        } else if (type.equals(MailType.APP_APPROVED_USER)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            setUsersMailAsTo(message, app, data);
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            message.setText(mailText);
            try {
                // send mail
                mailSender.send(message);
                log.info("[MAIL MANAGER] Sending mail: APP_APPROVED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
            } catch (MailException ex) {
                log.error("[MAIL MANAGER] Sending mail: APP_APPROVED_USER failed because of exception: {}", ex);
            }
        } else if (type.equals(MailType.APP_REJECTED_USER)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            setUsersMailAsTo(message, app, data);
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            message.setText(mailText);
            try {
                // send mail
                mailSender.send(message);
                log.info("[MAIL MANAGER] Sending mail: APP_REJECTED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
            } catch (MailException ex) {
                log.error("[MAIL MANAGER] Sending mail: APP_REJECTED_USER failed because of exception: {}", ex);
            }
        } else if (MailType.APP_ERROR_VO_ADMIN.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set language independent on user's preferred language.
            lang = new Locale("en");
            try {
                if (app.getGroup() == null) {
                    // VO
                    Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                } else {
                    Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                }
            } catch (Exception ex) {
                log.error("Error when resolving notification default language: {}", ex);
            }
            MailText mt2 = mail.getMessage(lang);
            String mailText2 = "";
            String mailSubject2 = "";
            if (mt2.getText() != null && !mt2.getText().isEmpty()) {
                mailText2 = mt2.getText();
            }
            if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
                mailSubject2 = mt2.getSubject();
            }
            // substitute common strings
            mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
            mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject2);
            message.setText(mailText2);
            // send message to all VO or Group admins
            List<String> toEmail = getToMailAddresses(app);
            for (String email : toEmail) {
                message.setTo(email);
                try {
                    mailSender.send(message);
                    log.info("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
                } catch (MailException ex) {
                    log.error("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN failed because of exception: {}", ex);
                }
            }
        } else {
            log.error("[MAIL MANAGER] Sending mail type: {} is not supported.", type);
        }
    } catch (Exception ex) {
        // all exceptions are catched and logged to: perun-registrar.log
        log.error("[MAIL MANAGER] Exception thrown when sending email: {}", ex);
    }
}
Also used : ApplicationForm(cz.metacentrum.perun.registrar.model.ApplicationForm) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) MailType(cz.metacentrum.perun.registrar.model.ApplicationMail.MailType) SQLException(java.sql.SQLException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RegistrarException(cz.metacentrum.perun.registrar.exceptions.RegistrarException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) MailException(org.springframework.mail.MailException) ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MailText(cz.metacentrum.perun.registrar.model.ApplicationMail.MailText) MailException(org.springframework.mail.MailException) ApplicationMail(cz.metacentrum.perun.registrar.model.ApplicationMail)

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