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

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

/*
 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.sql;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 base.jee.api.Settings;
import org.stringtemplate.v4.ST;

import base.Query;
import base.StringQueryResult;
import base.jee.Constants;
import base.jee.api.model.Email;
import base.json.Json;
import base.security.PermissionException;
import base.security.User;
import base.template.TemplateManager;

import static base.jee.api.sql.util.Log.log;

/**
 * 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 SqlAPI api;
	private TemplateManager templates;
	private Settings settings;
	private String site;
	private String email;
	private String ip;

	/**
	 *
	 * @param api
	 * @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(SqlAPI api, TemplateManager templates, Settings settings, String site, String email, String ip) {
		if(api == null) {
			throw new IllegalArgumentException("Invalid parameter: api");
		}
		if(ip == null) {
			throw new IllegalArgumentException("Invalid parameter: ip");
		}
		if(templates == null) {
			throw new IllegalArgumentException("Invalid parameter: templates");
		}
		if(settings == null) {
			throw new IllegalArgumentException("Invalid parameter: settings");
		}
		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.api = api;
		this.templates = templates;
		this.settings = settings;
		this.site = site;
		this.email = email.trim().toLowerCase();
	}

	public List execute() throws IOException {
		List results = new LinkedList<>();
		Connection c = null;
		PreparedStatement s = null;
		ResultSet r = null;
		User u = null;

		try {
			c = api.getDataSource().getConnection();
			c.setAutoCommit(false);

			if(isThrottled(c, email)) {
				log(c, "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 = null;
			String supportEmail = null;
			s = c.prepareStatement("select uuid, first_name, last_name, (select value from setting where name='support_team.name'), (select value from setting where name='support_team.email'), expiry from person where email=?");
			s.setString(1, email);
			r = s.executeQuery();
			if(r.next()) {
				// Construct a user object for the purposes of making the user
				// info available in the email template.
				u = new User(
						UUID.fromString(r.getString(1)),
						r.getString(2),
						r.getString(3),
						null,
						null,
						site,
						null,
						ip);
				supportTeam = r.getString(4);
				supportEmail = r.getString(5);
				//6

				if(r.getLong(6) > 0 && new Date(r.getLong(6)).getTime() < new Date().getTime()) {
					log(c, "FINE", u, "Password reset attempted from account that is expired.");
					throw new IllegalStateException("Password reset is not allowed for expired accounts.");
				}

			}
			r.close();
			r = null;
			s.close();
			s = null;

			if(u == null) {
				markForThrottling(c, "password_reset_" + email);
				log(c, "FINE", User.userWithIp(ip, site), "Invalid email: " + email);
				c.commit();
				c.close();
				c = null;
				return null;
			}

			String token = UUID.randomUUID().toString();
			log(c, "DEBUG", u, "Storing token " + token + " for person " + email);
			s = c.prepareStatement("insert into request_token (site, token, person_uuid, type, ip, expiry) values(?,?,?,'password_reset',?,?)");
			s.setString(1, site);
			s.setString(2, token);
			s.setString(3, u.getPersonUuid().toString());
			s.setString(4, ip);
			s.setLong(5, (new Date()).getTime()/1000);
			s.executeUpdate();
			s.close();
			s = null;

			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");

			s = c.prepareStatement("insert into email (uuid,to_address,email,retries,attempt_at,in_progress) values(?,?,?,0,?,0)");
			s.setString(1, new base.uuid.UUID().toString());
			s.setString(2, email.getTo());
			s.setString(3, email.toJson());
			s.setLong(4, new Date().getTime());
			s.execute();
			s.close();
			s = null;

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

			c.commit();
			c.close();
			c = null;

			results.add(new StringQueryResult(token));
		} catch(SQLException e) {
			throw new IOException(e);
		} finally {
			if(r != null) { try { r.close(); } catch(Exception e) {} }
			if(s != null) { try { s.close(); } catch(Exception e) {} }
			if(c != null) {
				try { c.rollback(); } catch (SQLException e) { }
				try { c.close(); } catch (SQLException e) { }
			}
		}

		return results;
	}

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

	public boolean isThrottled(Connection c, String key) throws SQLException {
		PreparedStatement q = null;
		PreparedStatement q2 = null;
		ResultSet r = null;

		try {
			q = c.prepareStatement("select updated + (select value from setting where name='throttle.auth.lockout') from throttle where key_value=? and attempts>=(select value from setting where name='throttle.auth.attempts')");
			q.setString(1, key);
			r = q.executeQuery();
			if(r.next()) {
				if((new Date().getTime()/1000) < r.getLong(1)) {
					return true;
				} else {
					q2 = c.prepareStatement("delete from throttle where key_value=?");
					q2.setString(1, key);
					q2.execute();
					return false;
				}
			} else {
				return false;
			}
		} finally {
			try { if(r != null) { r.close(); } } catch(Exception e) {}
			try { if(q != null) { q.close(); } } catch(Exception e) {}
			try { if(q2 != null) { q2.close(); } } catch(Exception e) {}
		}

	}

	public void markForThrottling(Connection c, String key) throws SQLException {
		PreparedStatement q = null;
		PreparedStatement q2 = null;
		PreparedStatement q3 = null;
		ResultSet r = null;

		try {
			q = c.prepareStatement("select attempts,updated from throttle where key_value=?");
			q.setString(1, key);
			r = q.executeQuery();
			if(!r.next()) {
				// Insert new throttle
				q3 = c.prepareStatement("insert into throttle (key_value,attempts,updated) values(?,1,?)");
				q3.setString(1, key);
				q3.setLong(2, new Date().getTime()/1000);
				q3.executeUpdate();
				return;
			} else {
				long updated = r.getLong(2);
				r.close();
				r = null;
				q2 = c.prepareStatement("select value from setting where name = 'throttle.auth.window'");
				r = q2.executeQuery();
				if(!r.next()) {
					throw new IllegalStateException("System configuration setting 'throttle.auth.window' is missing.");
				}
				if(updated < (new Date().getTime()/1000)-r.getLong(1)) {
					// Marking outside the throttle window, reset the attempt counter
					q3 = c.prepareStatement("update throttle set attempts=1,updated=? where key_value=?");
					q3.setLong(1, new Date().getTime()/1000);
					q3.setString(2, key);
					q3.executeUpdate();
				} else {
					// Marking within the throttle window, just increment the attempts counter
					q3 = c.prepareStatement("update throttle set attempts=attempts+1 where key_value=?");
					q3.setString(1, key);
					q3.executeUpdate();
					return;
				}

			}
		} finally {
			try { if(r != null) { r.close(); } } catch(Exception e) {}
			try { if(q != null) { q.close(); } } catch(Exception e) {}
			try { if(q2 != null) { q2.close(); } } catch(Exception e) {}
			try { if(q3 != null) { q3.close(); } } catch(Exception e) {}
		}
	}

	@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