base.jee.api.cassandra.SignUp Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of base Show documentation
Show all versions of base Show documentation
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.
/*
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.JeeBase;
import base.jee.api.model.Email;
import base.template.TemplateManager;
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.KeyValue;
import base.Query;
import base.jee.api.Settings;
import base.email.EmailAddressParse;
import base.jee.Constants;
import base.json.Json;
import base.security.PermissionException;
import base.security.User;
import base.text.StringHelper;
import static base.jee.api.cassandra.util.Log.log;
public class SignUp extends Query {
private CassandraAPI api;
private TemplateManager templateManager;
private String site;
private String firstName;
private String lastName;
private String email;
private String username;
private String password;
private String ip;
private User user;
public SignUp(CassandraAPI api, TemplateManager templateManager, User user, String site, String firstName, String lastName, String email, String username, String password, String ip) throws PermissionException {
if(api == null) {
throw new IllegalArgumentException("Invalid parameter: api");
}
if(templateManager == null) {
throw new IllegalArgumentException("Invalid parameter: templateManager");
}
if(user == null) {
throw new IllegalArgumentException("Invalid parameter: user");
}
if(firstName == null || firstName.trim().length() == 0) {
throw new IllegalArgumentException("Invalid parameter: firstName");
}
if(lastName == null || lastName.trim().length() == 0) {
throw new IllegalArgumentException("Invalid parameter: lastName");
}
if(email == null || email.trim().length() == 0) {
throw new IllegalArgumentException("Invalid parameter: email");
}
if(password == null || password.length() == 0) {
throw new IllegalArgumentException("Must specify a password.");
}
if(ip == null || ip.length() == 0) {
throw new IllegalArgumentException("Must specify a IP.");
}
if(username != null && username.trim().length() > Constants.MAX_USERNAME_LENGTH) {
throw new IllegalArgumentException("Please choose a shorter username. Usernames should not have more than " + Constants.MAX_USERNAME_LENGTH + " characters.");
}
if(password.trim().length() > Constants.MAX_PASSWORD_LENGTH) {
throw new IllegalArgumentException("Please choose a shorter password. Passwords should not have more than " + Constants.MAX_PASSWORD_LENGTH + " characters.");
}
if(firstName.trim().length() > Constants.MAX_FIRST_NAME_LENGTH) {
throw new IllegalArgumentException("Please choose a shorter first name. First name should not have more than " + Constants.MAX_FIRST_NAME_LENGTH + " characters.");
}
if(lastName.trim().length() > Constants.MAX_LAST_NAME_LENGTH) {
throw new IllegalArgumentException("Please choose a shorter last name. Last name should not have more than " + Constants.MAX_FIRST_NAME_LENGTH + " characters.");
}
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.templateManager = templateManager;
this.site = site;
this.firstName = firstName.trim();
this.lastName = lastName.trim();
this.email = email.trim().toLowerCase();
this.password = password;
this.user = user;
this.ip = ip;
if(username != null) {
this.username = username.trim().toLowerCase();
}
}
public SignUp() {
}
@Override
public Query newWithParameters(Map parameters) throws IOException, PermissionException {
return new SignUp(
(CassandraAPI)parameters.get("api"),
((JeeBase)parameters.get("jee")).getTemplateManager(),
(User)parameters.get("user"),
(String)parameters.get("site"),
(String)parameters.get("first_name"),
(String)parameters.get("last_name"),
(String)parameters.get("email"),
(String)parameters.get("username"),
(String)parameters.get("password"),
((User)parameters.get("user")).getIp());
}
@Override
protected List execute() throws IOException {
List results = new LinkedList<>();
Settings settings = api.getSettingsCache();
Session s = api.getCassandraSession();
// Self sign up must be enabled.
String supportTeam = settings.get("support_team.name");
String supportEmail = settings.get("support_team.email");
boolean selfSignup = settings.get("self.signup").equals("true");
if(!selfSignup) {
log(s, "WARN", user, "Self sign up attempted while self sign up is disabled. Email: " + email);
results.add(new KeyValue("error", "Self sign up is not available at this time."));
return results;
}
// Check email address is an allowed form of email address
EmailAddressParse parse = new EmailAddressParse();
if(!parse.isValid(email)) {
results.add(new KeyValue("error", "Invalid email address. " + parse.getError()));
return results;
}
// Check this email is not already registered
PreparedStatement p = s.prepare("select email from person where email=?");
if(s.execute(p.bind(email)).iterator().hasNext()) {
results.add(new KeyValue("error", "Person already exists with this email address."));
return results;
}
// If username specified, username must not conflict with an existing username.
if(username != null && username.length() > 0) {
p = s.prepare("select username from person where or username=?");
if(s.execute(p.bind(username)).iterator().hasNext()) {
log(s, "FINEST", user, "Registration attempted using already registered email: " + email);
results.add(new KeyValue("error", "Person already exists with this username."));
return results;
}
}
// Generate and store an authorisation token to verify this email accounts identity.
String token = UUID.randomUUID().toString();
log(s, "FINEST", user, "Storing sign up confirmation token " + token + " for person " + email);
p = s.prepare("insert into request_token (uid, person_uuid, type, ip, expiry, data) values(?,?,'signup_confirmation',?,?,?)");
UUID personUuid = new base.uuid.UUID().toJavaUUID();
s.execute(p.bind(token, personUuid, ip, new Date().getTime()/1000,
"{\"site\":\""+Json.escape(site)+"\"," +
"\"first_name\":\""+Json.escape(firstName)+"\"," +
"\"last_name\":\""+Json.escape(lastName)+"\"," +
"\"person_uuid\":\"" + personUuid.toString() + "\"," +
"\"email\":\""+Json.escape(this.email)+"\"," +
(username != null && username.length() > 0 ?"\"username\":\""+Json.escape(username)+"\",":"") +
"\"password\":\""+Json.escape(password)+"\"}"));
ST html = templateManager.getCurrentTemplate(site).getInstanceOf("signup_confirmation_email_html");
html.add("first_name", firstName);
html.add("last_name", lastName);
html.add("email", this.email);
html.add("token", token);
html.add("formurl", api.getSettingsCache().get("base.url"));
ST text = templateManager.getCurrentTemplate(site).getInstanceOf("signup_confirmation_email_text");
text.add("first_name", firstName);
text.add("last_name", lastName);
text.add("email", this.email);
text.add("token", token);
text.add("formurl", api.getSettingsCache().get("base.url"));
Email email = new Email();
email.setTo(firstName + " " + lastName + " <" + this.email + ">");
email.setFrom(supportTeam + " <" + supportEmail + ">");
email.setText(text.render());
email.setHtml(html.render());
email.setSubject("Signup confirmation");
// Schedule the email to be delivered via the email delivery queue
Connection c = null;
java.sql.PreparedStatement ps = null;
try {
c = api.getDataSource().getConnection();
ps = c.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, "WARN", user, "Inserting registration email into email delvery table failed: " + email.getTo() + ". " + StringHelper.exceptionToString(e, "|"));
} finally {
if(ps != null) { try { ps.close(); } catch(SQLException e) {} }
if(c != null) { try { c.close(); } catch(SQLException e) {} }
}
results.add(new KeyValue("success", "ok"));
return results;
}
@Override
public String getJsonParameters() {
return "{" +
"\"first_name\":\"" + Json.escape(firstName)+ "\"," +
"\"last_name\":\"" + Json.escape(lastName)+ "\"," +
(username != null && username.length() > 0 ? "\"username\":\"" + Json.escape(email)+ "\",":"") +
"\"email\":\"" + Json.escape(email)+ "\"" +
"}";
}
}