All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.jee.api.cassandra.RequestPasswordResetEmail Maven / Gradle / Ivy

Go to download

A collection of basic java utility classes that provide basic features for a standalone/simple JEE application. Backed by a Cassandra, MySQL, or SQLite database, it provides, web page templates, user and group management, and a searchable online audit log of all user activity.

There is a newer version: 1.5.4
Show newest version
/*
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.jee.api.cassandra;

import java.io.IOException;

import base.jee.api.model.Email;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.PreparedStatement;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


import org.stringtemplate.v4.ST;

import base.Query;
import base.jee.api.Settings;
import base.StringQueryResult;
import base.jee.Constants;
import base.json.Json;
import base.security.PermissionException;
import base.security.User;
import base.template.TemplateManager;
import base.text.StringHelper;

import static base.jee.api.cassandra.util.IsThrottled.isThrottled;
import static base.jee.api.cassandra.util.Log.log;
import static base.jee.api.cassandra.util.MarkForThrottling.markForThrottling;

/**
 * Request that an email be sent to an email address associated with a user of the system, that enables
 * resetting of this users password. Password reset requests are also throttled, they considered to be an
 * authentication request.
 */
public class RequestPasswordResetEmail extends Query {

	private CassandraAPI c;
	private TemplateManager templates;
	private String site;
	private String email;
	private String ip;

	/**
	 *
	 * @param c
	 * @param templates A template manager with template files 'password_reset_email_html.txt' and 'password_reset_email_text.txt'
	 * @param email Email address corresponding with the users account.
	 * @param ip
	 */
	public RequestPasswordResetEmail(CassandraAPI c, TemplateManager templates, String site, String email, String ip) {
		if(c == null) {
			throw new IllegalArgumentException("Invalid parameter: c");
		}
		if(ip == null) {
			throw new IllegalArgumentException("Invalid parameter: ip");
		}
		if(templates == null) {
			throw new IllegalArgumentException("Invalid parameter: templates");
		}
		if(email == null) {
			throw new IllegalArgumentException("Invalid parameter: email");
		}

		if(email.trim().length() > Constants.MAX_EMAIL_LENGTH) {
			throw new IllegalArgumentException("Please choose a shorter email address. Email should not have more than " + Constants.MAX_EMAIL_LENGTH + " characters.");
		}

		this.c = c;
		this.templates = templates;
		this.site = site;
		this.email = email.trim().toLowerCase();
		this.ip = ip;
	}

	public List execute() throws IOException {
		List results = new LinkedList<>();
		User u = null;

		Settings settings = c.getSettingsCache();
		Session s = c.getCassandraSession();

		if(isThrottled(s, email, "auth", settings)) {
			log(s, "SEVERE", User.userWithIp(ip, site), "Blocked password reset request for throttled address: " + email);
			throw new IllegalStateException("This account is temporarily disabled due to repated sign in failures. Please try again shortly.");
		}

		String supportTeam = settings.get("support_team.name");
		String supportEmail = settings.get("support_team.email");

		PreparedStatement p = s.prepare("select uuid, first_name, last_name from person where email=?");
		for(Row r : s.execute(p.bind(email))) {
			u = new User(r.getUUID(0),
					r.getString(1),
					r.getString(2),
					null,
					null,
					site,
					null,
					ip);
		}

		if(u == null) {
			markForThrottling(s, "password_reset_" + email, "auth", settings);
			log(s, "FINE", User.userWithIp(ip, site), "Invalid email: " + email);
			results.add(new StringQueryResult("error"));
			return results;
		}

		String token = UUID.randomUUID().toString();
		log(s, "DEBUG", u, "Storing token " + token + " for person " + email);
		p = s.prepare("insert into request_token (uid, person_uuid, type, ip, expiry) values(?,?,'password_reset',?,?)");
		s.execute(p.bind(token, u.getPersonUuid(), ip, (new Date()).getTime()/1000));

		ST html = templates.getCurrentTemplate(site).getInstanceOf("password_reset_email_html");
		html.add("name", u.getDisplayName());
		html.add("email", this.email);
		html.add("token", token);
		html.add("formurl", settings.get("base.url"));

		ST text = templates.getCurrentTemplate(site).getInstanceOf("password_reset_email_text");
		text.add("name", u.getDisplayName());
		text.add("email", this.email);
		text.add("token", token);
		text.add("formurl", settings.get("base.url"));

		Email email = new Email();
		email.setTo(u.getDisplayName() + " <" + this.email + ">");
		email.setFrom(supportTeam + " <" + supportEmail + ">");
		email.setText(text.render());
		email.setHtml(html.render());
		email.setSubject("Password reset request verification");

		try(Connection ec = c.getDataSource().getConnection()) {
			try(java.sql.PreparedStatement ps = ec.prepareStatement("insert into email (uuid, to_address,email,retries,attempt_at,in_progress) values(?,?,?,0,?,0)")) {
				ps.setString(1, new base.uuid.UUID().toString());
				ps.setString(2, email.getTo());
				ps.setString(3, email.toJson());
				ps.setLong(4, new Date().getTime());
				ps.execute();
			}
		} catch (SQLException e) {
			log(s, "SEVERE", "Failed inserting email into queue. Email never sent. " + StringHelper.exceptionToString(e, "|"));
		}

		log(s, "INFO", u, "Sending password reset request for " + this.email + " with token " + token);

		results.add(new StringQueryResult(token));
		return results;
	}

	@Override
	public String getJsonParameters() {
		return "{" +
				"\"email\":\"" + Json.escape(email) + "\"," +
				"\"ip\":\"" + Json.escape(ip) + "\"" +
				"}";
	}

	@Override
	public Query newWithParameters(Map parameters) throws IOException, PermissionException {
		throw new IllegalArgumentException("RequestPasswordResetEmail may not be instantiated using a parameter map");
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy