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

base.jee.api.cassandra.Authenticate 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.

The 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 java.security.NoSuchAlgorithmException;

import base.KeyValue;
import base.Query;
import base.jee.api.Settings;
import base.jee.api.model.Location;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.naming.NamingException;

import base.jee.Constants;
import base.json.Json;
import base.ldap.LdapHelper;
import base.security.PermissionException;
import base.security.User;
import base.text.Password;
import base.text.StringHelper;

import static base.jee.api.cassandra.util.AddPerson.addPerson;
import static base.jee.api.cassandra.util.CreateSession.createSession;
import static base.jee.api.cassandra.util.IpLocation.ipLocation;
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;
import static base.jee.api.cassandra.util.UpdatePersonFromLdap.updatePersonFromLdap;
import static base.text.StringHelper.chomp;

/**
 */
public class Authenticate extends Query {

	private CassandraAPI api;
	private String site;
	private String currentToken;
	private String email;
	private String password;
	private String ip;

	public Authenticate() {
	}

	public Authenticate(CassandraAPI api, String site, String currentToken, String email, String password, String ip) {

		if(api == null) {
			throw new IllegalArgumentException("Invalid parameter: api");
		}
		if(email == null) {
			throw new IllegalArgumentException("Invalid parameter: email");
		}
		if(password == null) {
			throw new IllegalArgumentException("Invalid parameter: password");
		}

		if(currentToken != null && currentToken.trim().length() > Constants.MAX_TOKEN_LENGTH) {
			throw new IllegalArgumentException("Invalid token.");
		}
		if(chomp(email).length() > Constants.MAX_USERNAME_LENGTH) {
			throw new IllegalArgumentException("Invalid email address. Email address should not have more than " + Constants.MAX_USERNAME_LENGTH + " characters.");
		}
		if(password.trim().length() > Constants.MAX_PASSWORD_LENGTH) {
			throw new IllegalArgumentException("Invalid password. Passwords should not have more than " + Constants.MAX_PASSWORD_LENGTH + " characters.");
		}
		if(ip != null && ip.trim().length() > Constants.MAX_IP_ADDRESS_LENGTH) {
			throw new IllegalArgumentException("Invalid IP address. IP address should not have more than " + Constants.MAX_IP_ADDRESS_LENGTH + " characters.");
		}

		this.api = api;
		this.site = site;
		this.currentToken = currentToken;
		this.email = chomp(email).toLowerCase();
		this.password = password.trim();
		this.ip = ip == null?null:ip.trim();
	}

	@Override
	public Query newWithParameters(Map parameters) throws IOException, PermissionException {
		String email = (String)parameters.get("email");
		if(email == null) {
			email = (String)parameters.get("username");
		}

		return new Authenticate(
				(CassandraAPI)parameters.get("api"),
				((User)parameters.get("user")).getSite(),
				(String)parameters.get("current_token"),
				email,
				(String)parameters.get("password"),
				((User)parameters.get("user")).getIp());
	}

	public List execute() throws IOException {
		List results = new LinkedList<>();
		String token;

		if(password.trim().length() < Constants.MIN_PASSWORD_LENGTH) {
			results.add(new KeyValue("error", "Invalid password."));
			return results;
		}

		try {
			Session s = api.getCassandraSession();
			Settings settings = api.getSettingsCache();

			if(isThrottled(s, ip, "ip", settings)) {
				log(s, "SEVERE", User.userWithIp(ip, site), "Blocked authentication for throttled IP address: " + ip);
				results.add(new KeyValue("error", "Sign-in from this IP address is temporarily disabled due to repated sign in failures. Please try again shortly."));
				return results;
			}

			if(isThrottled(s, email, "auth", settings)) {
				log(s, "SEVERE", User.userWithIp(ip, site), "Blocked authentication for throttled email: " + email);
				results.add(new KeyValue("error", "Sign-in using this account is temporarily disabled due to repated sign in failures. Please try again shortly."));
				return results;
			}

			UUID personUuid = null;
			String firstName = null;
			String lastName = null;

			PreparedStatement p = s.prepare("select uuid, password, first_name, last_name from person where site=? and " + (email.contains("@") ? "email" : "username") + "=?");
			for(Row r : s.execute(p.bind(site, email))) {
				personUuid = r.getUUID(0);
				firstName = r.getString(2);
				lastName = r.getString(3);

				// If password hash does not match password, we forget this search result,
				// this enables a lookup on LDAP (below).
				if(!Password.verifyPassword(r.getString(1), password)) {
					personUuid = null;
				}

			}

			// Internal password check failed. Do LDAP lookup if this feature is configured to be enabled.
			if(personUuid == null) {
				boolean ldapEnabled = false;
				String ldapUrl = null;
				String ldapUserDn = null;

				if(!email.contains("@")) {
					String e = settings.get("ldap.enabled", "false");
					ldapEnabled = e.equalsIgnoreCase("true") || e.equalsIgnoreCase("y") || e.equalsIgnoreCase("yes");
					ldapUrl = settings.get("ldap.url");
					ldapUserDn = settings.get("ldap.userdn");
				}

				if(ldapEnabled) {
					String user = ldapUserDn.replace("{u}", email);
					LdapHelper ldap;
					Map attributes;
					try {
						ldap = new LdapHelper(ldapUrl, user, password, true);
						attributes = ldap.getAttributes(user);
					} catch (NamingException | IOException e) {
						if(e.getCause() instanceof javax.naming.AuthenticationException) {
							log(s, "FINE", User.userWithIp(ip, site), "Invalid internal and/or ldap username or password. Username: " + email);
							results.add(new KeyValue("error", "Invalid username or password."));
							return results;
						} else {
							log(s, "SEVERE", User.userWithIp(ip, site), "Problem communicating with LDAP server. user=" + user + " - " + StringHelper.exceptionToString(e, "\n    "));
							results.add(new KeyValue("error", "Authentication temporarily unavailable."));
							return results;
						}
					}
					firstName = attributes.get("givenName");
					lastName = attributes.get("sn");
					personUuid = createOrUpdatePersonUsingLdapAttributes(s, site, email, attributes);
				}

				if(personUuid == null) {
					if(ip != null) {
						markForThrottling(s, ip, "ip", settings);
					}
					markForThrottling(s, email, "auth", settings);
					if(ldapEnabled) {
						results.add(new KeyValue("error", "Invalid username or password."));
						log(s, "FINE", User.userWithIp(ip, site), "Invalid username or password. Username: " + email);
					} else {
						results.add(new KeyValue("error", "Invalid email address or password."));
						log(s, "FINE", User.userWithIp(ip, site), "Invalid email address or password. Email: " + email);
					}
					return results;
				}
			}

			if(password.length() == 0) {
				log(s, "SEVERE", User.userWithUuidAndIp(personUuid, ip, site), "Blocked authentication for account with no password. Email: " + email);
				results.add(new KeyValue("error", "This user account has no password."));
				return results;
			}

			p = s.prepare("update person set last_auth=?,last_auth_ip=? where site=? and uuid=?");
			s.execute(p.bind(new Date().getTime(), ip, site, personUuid));

			token = createSession(s, site, personUuid, firstName, lastName, currentToken, ip, Long.parseLong(settings.get("session.expiry")));

			Location l = ipLocation(s, ip);
			log(s, "INFO", User.userWithUuidAndIp(personUuid, ip, site), "Authentication success. Location: " + (l == null?"unknown":l.toString()));

		} catch(NoSuchAlgorithmException e) {
			throw new IOException(e);
		}
		results.add(new KeyValue("token", token));
		return results;
	}

	private UUID createOrUpdatePersonUsingLdapAttributes(Session s, String site, String username, Map attributes) throws IOException {
		UUID personUuid = null;

		String firstName = attributes.get("givenName");
		String lastName = attributes.get("sn");
		String email = attributes.get("mail");

		PreparedStatement p = s.prepare("select uuid, first_name, last_name from person where site=? and username=?");
		ResultSet rs = s.execute(p.bind(site, username));
		for(Row r : rs) {
			personUuid = r.getUUID(0);
			if((email != null && !email.equals(r.getString(4)))
				|| (firstName != null && !firstName.equals(r.getString(2)))
				|| (lastName != null && !lastName.equals(r.getString(3)))
					) {
				if(email.equals(r.getString(4))) {
					email = null;
				}
				if(firstName.equals(r.getString(2))) {
					firstName = null;
				}
				if(lastName.equals(r.getString(3))) {
					lastName = null;
				}
				updatePersonFromLdap(s, User.userWithUuidAndIp(personUuid, ip, site), firstName, lastName, email);
			}
			return personUuid;
		}
		personUuid = addPerson(s, site, firstName, lastName, email, username, null, null);
		log(s, "INFO", User.userWithUuidAndIp(personUuid, ip, site), "Auto created user account using LDAP date for username=" + username);

		return personUuid;
	}

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

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy