Search in sources :

Example 6 with ApplicationFormItem

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

Example 7 with ApplicationFormItem

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

the class RegistrarManagerImpl method copyFormFromGroupToGroup.

@Override
public void copyFormFromGroupToGroup(PerunSession sess, Group fromGroup, Group toGroup) throws PerunException {
    Vo fromVO = perun.getVosManagerBl().getVoById(registrarSession, fromGroup.getVoId());
    if ((!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, fromGroup) && !AuthzResolver.isAuthorized(sess, Role.VOADMIN, fromGroup) && !AuthzResolver.isAuthorized(sess, Role.TOPGROUPCREATOR, fromVO)) || (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, toGroup) && !AuthzResolver.isAuthorized(sess, Role.VOADMIN, toGroup))) {
        throw new PrivilegeException(sess, "copyFormFromGroupToGroup");
    }
    List<ApplicationFormItem> items = getFormItems(sess, getFormForGroup(fromGroup));
    for (ApplicationFormItem item : items) {
        // reset order, id is always new inside add method
        item.setOrdnum(null);
        addFormItem(sess, getFormForGroup(toGroup), item);
    }
}
Also used : ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem)

Example 8 with ApplicationFormItem

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

the class RegistrarManagerImpl method getFormItemById.

@Override
public ApplicationFormItem getFormItemById(int id) {
    ApplicationFormItem item;
    item = jdbc.queryForObject(FORM_ITEM_SELECT + " where id=?", ITEM_MAPPER, id);
    if (item != null) {
        List<ItemTexts> texts = jdbc.query(FORM_ITEM_TEXTS_SELECT + " where item_id=?", ITEM_TEXTS_MAPPER, item.getId());
        for (ItemTexts itemTexts : texts) {
            item.getI18n().put(itemTexts.getLocale(), itemTexts);
        }
        List<AppType> appTypes = jdbc.query(APP_TYPE_SELECT + " where item_id=?", APP_TYPE_MAPPER, item.getId());
        item.setApplicationTypes(appTypes);
    }
    return item;
}
Also used : ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) ItemTexts(cz.metacentrum.perun.registrar.model.ApplicationFormItem.ItemTexts) AppType(cz.metacentrum.perun.registrar.model.Application.AppType)

Example 9 with ApplicationFormItem

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

the class RegistrarManagerImpl method getFormItems.

@Override
public List<ApplicationFormItem> getFormItems(PerunSession sess, ApplicationForm form, AppType appType) throws PerunException {
    // authz
    if (form.getGroup() == null) {
        if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, form.getVo()) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, form.getVo())) {
            throw new PrivilegeException("getFormItems");
        }
    } else {
        if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, form.getVo()) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, form.getVo()) && !AuthzResolver.isAuthorized(sess, Role.TOPGROUPCREATOR, form.getVo()) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, form.getGroup())) {
            throw new PrivilegeException("getFormItems");
        }
    }
    List<ApplicationFormItem> items;
    if (appType == null) {
        items = jdbc.query(FORM_ITEM_SELECT + " where form_id=? order by ordnum asc", ITEM_MAPPER, form.getId());
    } else {
        items = jdbc.query(FORM_ITEM_SELECT + " i,application_form_item_apptypes t where form_id=? and i.id=t.item_id and t.apptype=? order by ordnum asc", ITEM_MAPPER, form.getId(), appType.toString());
    }
    for (ApplicationFormItem item : items) {
        List<ItemTexts> texts = jdbc.query(FORM_ITEM_TEXTS_SELECT + " where item_id=?", ITEM_TEXTS_MAPPER, item.getId());
        for (ItemTexts itemTexts : texts) {
            item.getI18n().put(itemTexts.getLocale(), itemTexts);
        }
        List<AppType> appTypes = jdbc.query(APP_TYPE_SELECT + " where item_id=?", APP_TYPE_MAPPER, item.getId());
        item.setApplicationTypes(appTypes);
    }
    return items;
}
Also used : ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) ItemTexts(cz.metacentrum.perun.registrar.model.ApplicationFormItem.ItemTexts) AppType(cz.metacentrum.perun.registrar.model.Application.AppType)

Example 10 with ApplicationFormItem

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

the class RegistrarManagerImpl method updateFormItems.

@Override
@Transactional(rollbackFor = Exception.class)
public int updateFormItems(PerunSession sess, ApplicationForm form, List<ApplicationFormItem> items) throws PrivilegeException, InternalErrorException {
    if (form.getGroup() == null) {
        // VO application
        if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, form.getVo())) {
            throw new PrivilegeException(sess, "updateFormItems");
        }
    } else {
        if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, form.getVo()) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, form.getGroup())) {
            throw new PrivilegeException(sess, "updateFormItems");
        }
    }
    if (items == null) {
        throw new NullPointerException("ApplicationFormItems to update can't be null");
    }
    int finalResult = 0;
    for (ApplicationFormItem item : items) {
        // is item to create ? => create
        if (item.getId() == 0 && !item.isForDelete()) {
            if (addFormItem(sess, form, item) != null) {
                finalResult++;
            }
            continue;
        }
        // is item for deletion ? => delete on cascade
        if (item.isForDelete()) {
            finalResult += jdbc.update("delete from application_form_items where id=?", item.getId());
            // continue to next item
            continue;
        }
        // else update form item
        int result = jdbc.update("update application_form_items set ordnum=?,shortname=?,required=?,type=?,fed_attr=?,dst_attr=?,regex=? where id=?", item.getOrdnum(), item.getShortname(), item.isRequired() ? "1" : "0", item.getType().toString(), item.getFederationAttribute(), item.getPerunDestinationAttribute(), item.getRegex(), item.getId());
        finalResult += result;
        if (result == 0) {
            // skip whole set if not found for update
            continue;
        }
        // update form item texts (easy way = delete and new insert)
        // delete
        jdbc.update("delete from application_form_item_texts where item_id=?", item.getId());
        // insert new
        for (Locale locale : item.getI18n().keySet()) {
            ItemTexts itemTexts = item.getTexts(locale);
            jdbc.update("insert into application_form_item_texts(item_id,locale,label,options,help,error_message) values (?,?,?,?,?,?)", item.getId(), locale.getLanguage(), itemTexts.getLabel(), itemTexts.getOptions(), itemTexts.getHelp(), itemTexts.getErrorMessage());
        }
        // update form item app types (easy way = delete and new insert)
        // delete
        jdbc.update("delete from application_form_item_apptypes where item_id=?", item.getId());
        // insert new
        for (AppType appType : item.getApplicationTypes()) {
            jdbc.update("insert into application_form_item_apptypes (item_id,apptype) values (?,?)", item.getId(), appType.toString());
        }
    }
    perun.getAuditer().log(sess, "Application form ID=" + form.getId() + " voID=" + form.getVo().getId() + ((form.getGroup() != null) ? (" groupID=" + form.getGroup().getId()) : "") + " has had its items updated.");
    // return number of updated rows
    return finalResult;
}
Also used : ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) ItemTexts(cz.metacentrum.perun.registrar.model.ApplicationFormItem.ItemTexts) AppType(cz.metacentrum.perun.registrar.model.Application.AppType) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

ApplicationFormItem (cz.metacentrum.perun.registrar.model.ApplicationFormItem)13 ApplicationFormItemData (cz.metacentrum.perun.registrar.model.ApplicationFormItemData)5 AppType (cz.metacentrum.perun.registrar.model.Application.AppType)4 SQLException (java.sql.SQLException)4 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)4 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)4 RegistrarException (cz.metacentrum.perun.registrar.exceptions.RegistrarException)3 ItemTexts (cz.metacentrum.perun.registrar.model.ApplicationFormItem.ItemTexts)3 MailException (org.springframework.mail.MailException)3 Transactional (org.springframework.transaction.annotation.Transactional)3 RegistrarModule (cz.metacentrum.perun.registrar.RegistrarModule)2 ApplicationForm (cz.metacentrum.perun.registrar.model.ApplicationForm)2 ApplicationFormItemWithPrefilledValue (cz.metacentrum.perun.registrar.model.ApplicationFormItemWithPrefilledValue)2 MailType (cz.metacentrum.perun.registrar.model.ApplicationMail.MailType)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 PerunClient (cz.metacentrum.perun.core.api.PerunClient)1 PerunPrincipal (cz.metacentrum.perun.core.api.PerunPrincipal)1 PerunSession (cz.metacentrum.perun.core.api.PerunSession)1 Application (cz.metacentrum.perun.registrar.model.Application)1