<commit_before>/*
 * Copyright 2010 - 2017 Wyona
 */
package org.wyona.yanel.resources.registration;

import org.wyona.yanel.core.util.MailUtil;

import org.wyona.yanel.impl.resources.BasicXMLResource;

import org.wyona.commons.xml.XMLHelper;

import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.NodeType;
import org.wyona.yarep.util.YarepUtil;

import org.wyona.security.core.api.User;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.URL;
import java.util.Date;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import javax.mail.internet.InternetAddress;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

/**
 * A resource to register new users
 */
public class UserRegistrationResource extends BasicXMLResource {
    
    private static Logger log = LogManager.getLogger(UserRegistrationResource.class);

    static String NAMESPACE = "http://www.wyona.org/yanel/user-registration/1.0";

    private static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

    private static final long  DEFAULT_TOTAL_VALID_HRS = 24L;

    private static final String FROM_ADDRESS_PROP_NAME = "fromEmail";

    private static final String ONE_OR_MORE_INPUTS_NOT_VALID = "one-or-more-inputs-not-valid";

    private static final String ADMIN_CONFIRMATION_KEY = "admin-confirmation-key";
    private static final String ADMINISTRATOR_CONFIRMED = "administrator-confirmed";

    protected static final String EMAIL = "email";
    protected static final String FIRSTNAME = "firstname";
    protected static final String LASTNAME = "lastname";
    protected static final String STREET = "street";
    protected static final String CITY = "location";
    protected static final String ZIP = "zip";
    protected static final String GENDER = "gender";
    protected static final String LANGUAGE = "language";
    protected static final String SALUTATION = "salutation";
    protected static final String PHONE = "phone";
    protected static final String COMPANY = "company";

    private static final String IS_PRE_AUTH_ATTR_NAME = "is-pre-authenticated";
    private static final String PRE_AUTH_USERNAME_ATTR_NAME = "pre-authenticated-username";
    private static final String PASSWORD_ELEMENT_NAME = "password";

    protected static final String PASSWORD = "password";
    protected static final String PASSWORD_CONFIRMED = "<PASSWORD>";
    
    /**
     * @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
     */
    @Override
    protected InputStream getContentXML(String viewId) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("requested viewId: " + viewId);
        }

        java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
        org.wyona.commons.xml.XMLHelper.writeDocument(generateResponseDocument(), baout);
        return new java.io.ByteArrayInputStream(baout.toByteArray());
    }

    /**
     * Check whether email address is valid
     */
    private boolean isEmailValid(String email) {
        if (email != null && email.length() > 0 && email.indexOf("@") > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether password is valid
     */
    private boolean isPasswordValid(String password) {
        if (password != null && password.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether first name is valid
     * @param firstname First name
     * @return true when first name is valid and false otherwise
     */
    private boolean isFirstnameValid(String firstname) {
        if (firstname != null && firstname.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether lastname is valid
     */
    private boolean isLastnameValid(String lastname) {
        if (lastname != null && lastname.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether street is valid
     */
    private boolean isStreetValid(String street) {
        if (street != null && street.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether zip code is neither null nor has zero length
     */
    private boolean isZipNotEmpty(String zipCode) {
        if (zipCode != null && zipCode.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether format of zip code is valid
     * @param zipCode ZIP code
     * @return valid zip code or null if not valid
     */
    protected String isZipValid(String zipCode) {
        Pattern pzip = Pattern.compile("[1-9][0-9]{3}"); // INFO: Example of valid ZIP: 1234, Example of not-valid ZIP: 01234
        Matcher mzip = pzip.matcher(zipCode);
        if(mzip.find()) {
            return mzip.group(0);
        } else {
            log.warn("Format of ZIP '" + zipCode + "' is not valid!");
            return null;
        }
    }

    /**
     * Check whether city is valid
     */
    private boolean isCityValid(String city) {
        if (city != null && city.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether phone number is valid
     */
    private boolean isPhoneValid(String phone) {
        if (phone != null && phone.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether gender is valid
     * @return Either 'm' or 'f' and otherwise null
     */
    private String isGenderValid(String gender) {
        if (gender != null && gender.length() > 0) {
            if (gender.equals("male")) {
                return "m";
            } else if (gender.equals("female")) {
                return "f";
            }
        }
        log.error("No such gender: " + gender);
        return null;
    }

    /**
     * Check whether company is valid
     * @return Either company name or null
     */
    private String isCompanyValid(String company) {
        if (company != null && company.length() > 0) {
            return company;
        }
        return null;
    }

    /**
     * Check whether language is valid
     * @return Either language or null
     */
    private String isLanguageValid(String language) {
        if (language != null && language.length() == 2) {
            return language;
        }
        return null;
    }

    /**
     * Check whether fax number is valid
     * @return Either fax number or null
     */
    private String isFaxValid(String fax) {
        if (fax != null && fax.length() > 0) {
            return fax;
        }
        return null;
    }

    /**
     * Exists?
     */
    public boolean exists() {
        return true;
    }

    /**
     * Send email containing a confirmation link
     * @param userRegBean Bean containing all information about user registration
     */
    private void sendConfirmationLinkEmail(Document doc, UserRegistrationBean userRegBean) {
        log.info("Do not register user right away, but send an email to '" + userRegBean.getEmail() + "' containing a confirmation link...");
        Element rootElement = doc.getDocumentElement();

        try {
            Element element = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "confirmation-link-email"));
            element.setAttribute("sent-by-yanel", "false");
            if (sendNotificationsEnabled()) {
                if (administratorConfirmationRequired()) {
                    String adminConfirmationKey = java.util.UUID.randomUUID().toString();
                    setAdminConfirmationKey(userRegBean.getUUID(), adminConfirmationKey);

                    StringBuilder body = new StringBuilder();
                    body.append("A user with email address '" + userRegBean.getEmail() + "' has sent a registration request.");
                    body.append("\n\nPlease confirm the request by clicking on the following link:");
                    body.append("\n\n" + getActivationURL(userRegBean) + "&" + ADMIN_CONFIRMATION_KEY + "=" + adminConfirmationKey);<commit_msg>link for checking whether email is blacklisted<commit_after>/*
 * Copyright 2010 - 2018 Wyona
 */
package org.wyona.yanel.resources.registration;

import org.wyona.yanel.core.util.MailUtil;

import org.wyona.yanel.impl.resources.BasicXMLResource;

import org.wyona.commons.xml.XMLHelper;

import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.NodeType;
import org.wyona.yarep.util.YarepUtil;

import org.wyona.security.core.api.User;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.URL;
import java.util.Date;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import javax.mail.internet.InternetAddress;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

/**
 * A resource to register new users
 */
public class UserRegistrationResource extends BasicXMLResource {
    
    private static Logger log = LogManager.getLogger(UserRegistrationResource.class);

    static String NAMESPACE = "http://www.wyona.org/yanel/user-registration/1.0";

    private static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

    private static final long  DEFAULT_TOTAL_VALID_HRS = 24L;

    private static final String FROM_ADDRESS_PROP_NAME = "fromEmail";

    private static final String ONE_OR_MORE_INPUTS_NOT_VALID = "one-or-more-inputs-not-valid";

    private static final String ADMIN_CONFIRMATION_KEY = "admin-confirmation-key";
    private static final String ADMINISTRATOR_CONFIRMED = "administrator-confirmed";

    protected static final String EMAIL = "email";
    protected static final String FIRSTNAME = "firstname";
    protected static final String LASTNAME = "lastname";
    protected static final String STREET = "street";
    protected static final String CITY = "location";
    protected static final String ZIP = "zip";
    protected static final String GENDER = "gender";
    protected static final String LANGUAGE = "language";
    protected static final String SALUTATION = "salutation";
    protected static final String PHONE = "phone";
    protected static final String COMPANY = "company";

    private static final String IS_PRE_AUTH_ATTR_NAME = "is-pre-authenticated";
    private static final String PRE_AUTH_USERNAME_ATTR_NAME = "pre-authenticated-username";
    private static final String PASSWORD_ELEMENT_NAME = "password";

    protected static final String PASSWORD = "password";
    protected static final String PASSWORD_CONFIRMED = "<PASSWORD>";
    
    /**
     * @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
     */
    @Override
    protected InputStream getContentXML(String viewId) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("requested viewId: " + viewId);
        }

        java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream();
        org.wyona.commons.xml.XMLHelper.writeDocument(generateResponseDocument(), baout);
        return new java.io.ByteArrayInputStream(baout.toByteArray());
    }

    /**
     * Check whether email address is valid
     */
    private boolean isEmailValid(String email) {
        if (email != null && email.length() > 0 && email.indexOf("@") > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether password is valid
     */
    private boolean isPasswordValid(String password) {
        if (password != null && password.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether first name is valid
     * @param firstname First name
     * @return true when first name is valid and false otherwise
     */
    private boolean isFirstnameValid(String firstname) {
        if (firstname != null && firstname.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether lastname is valid
     */
    private boolean isLastnameValid(String lastname) {
        if (lastname != null && lastname.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether street is valid
     */
    private boolean isStreetValid(String street) {
        if (street != null && street.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether zip code is neither null nor has zero length
     */
    private boolean isZipNotEmpty(String zipCode) {
        if (zipCode != null && zipCode.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether format of zip code is valid
     * @param zipCode ZIP code
     * @return valid zip code or null if not valid
     */
    protected String isZipValid(String zipCode) {
        Pattern pzip = Pattern.compile("[1-9][0-9]{3}"); // INFO: Example of valid ZIP: 1234, Example of not-valid ZIP: 01234
        Matcher mzip = pzip.matcher(zipCode);
        if(mzip.find()) {
            return mzip.group(0);
        } else {
            log.warn("Format of ZIP '" + zipCode + "' is not valid!");
            return null;
        }
    }

    /**
     * Check whether city is valid
     */
    private boolean isCityValid(String city) {
        if (city != null && city.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether phone number is valid
     */
    private boolean isPhoneValid(String phone) {
        if (phone != null && phone.length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * Check whether gender is valid
     * @return Either 'm' or 'f' and otherwise null
     */
    private String isGenderValid(String gender) {
        if (gender != null && gender.length() > 0) {
            if (gender.equals("male")) {
                return "m";
            } else if (gender.equals("female")) {
                return "f";
            }
        }
        log.error("No such gender: " + gender);
        return null;
    }

    /**
     * Check whether company is valid
     * @return Either company name or null
     */
    private String isCompanyValid(String company) {
        if (company != null && company.length() > 0) {
            return company;
        }
        return null;
    }

    /**
     * Check whether language is valid
     * @return Either language or null
     */
    private String isLanguageValid(String language) {
        if (language != null && language.length() == 2) {
            return language;
        }
        return null;
    }

    /**
     * Check whether fax number is valid
     * @return Either fax number or null
     */
    private String isFaxValid(String fax) {
        if (fax != null && fax.length() > 0) {
            return fax;
        }
        return null;
    }

    /**
     * Exists?
     */
    public boolean exists() {
        return true;
    }

    /**
     * Send email containing a confirmation link
     * @param userRegBean Bean containing all information about user registration
     */
    private void sendConfirmationLinkEmail(Document doc, UserRegistrationBean userRegBean) {
        log.info("Do not register user right away, but send an email to '" + userRegBean.getEmail() + "' containing a confirmation link...");
        Element rootElement = doc.getDocumentElement();

        try {
            Element element = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "confirmation-link-email"));
            element.setAttribute("sent-by-yanel", "false");
            if (sendNotificationsEnabled()) {
                if (administratorConfirmationRequired()) {
                    String adminConfirmationKey = java.util.UUID.randomUUID().toString();
                    setAdminConfirmationKey(userRegBean.getUUID(), adminConfirmationKey);

                    StringBuilder body = new StringBuilder();
                    body.append("A user with email address '" + userRegBean.getEmail() + "' has sent a registration request.");
                    body.append("\n\nYou might want to check first whether this email address is blacklisted: https://cleantalk.org/blacklists/" + userRegBean.getEmail());
                    body.append("\n\nIf not, then please confirm the request by clicking on the following link:");
                    body.append("\n\n" + getActivationURL(userRegBean) + "&" + ADMIN_CONFIRMATION_KEY + "=" + adminConfirmationKey);
{'fraction_non_alphanumeric': 0.1036427732079906, 'fraction_numerical': 0.005170387779083431, 'mean_word_length': 2.417871485943775, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 29, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4235987', 'n_tokens_mistral': 4829, 'n_tokens_neox': 4635, 'n_words': 1326}