
base.jee.api.cassandra.CreatePerson 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.Query;
import base.jee.api.Settings;
import base.UuidQueryResult;
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.text.ParseException;
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.email.EmailAddressParse;
import base.jee.Constants;
import base.jee.JeeBase;
import base.json.Json;
import base.security.PermissionException;
import base.security.ResourceUid;
import base.security.User;
import base.text.StringHelper;
import static base.jee.api.cassandra.util.AddPerson.addPerson;
import static base.jee.api.cassandra.util.Log.log;
import static base.jee.api.cassandra.util.UpsertResourceRole.upsertResourceRole;
import static base.jee.api.cassandra.util.UpsertRole.upsertRole;
import static base.text.StringHelper.chomp;
import static base.text.TagsToArray.tagsToArray;
public class CreatePerson extends Query {
private CassandraAPI c;
private User user;
private TemplateManager templateManager;
private String site;
private String firstName;
private String lastName;
private String email;
private String username;
private String password;
private String[] initialRoles;
private Date expiry;
public CreatePerson(CassandraAPI c, TemplateManager templateManager, User user, String firstName, String lastName, String email, String username, String password, String initialRoles, String expiry) throws PermissionException {
if(c == null) {
throw new IllegalArgumentException("Invalid parameter: c");
}
if(templateManager == null) {
throw new IllegalArgumentException("Invalid parameter: templateManager");
}
if(user == null || !user.isAuthenticated()) {
throw new PermissionException(getClass().getSimpleName(), user, "Requires authenticated user.", Constants.PERSON_MANAGE_ROLE);
}
if(firstName == null || chomp(firstName).length() == 0) {
throw new IllegalArgumentException("Invalid parameter: firstName");
}
if(lastName == null || chomp(lastName).length() == 0) {
throw new IllegalArgumentException("Invalid parameter: lastName");
}
if(email == null || chomp(email).length() == 0) {
throw new IllegalArgumentException("Please specify an email address.");
}
if(chomp(email).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.");
}
EmailAddressParse parse = new EmailAddressParse();
if(!parse.isValid(chomp(email).toLowerCase())) {
throw new IllegalArgumentException("Invalid email address. " + parse.getError());
}
if(username != null && chomp(username).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 != null && password.length() < Constants.MIN_PASSWORD_LENGTH) {
throw new IllegalArgumentException("Please choose a longer password. Passwords should contain at least " + Constants.MIN_PASSWORD_LENGTH + " characters.");
}
if(password != null && password.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(chomp(firstName).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(chomp(lastName).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(initialRoles != null && chomp(initialRoles).length() > Constants.MAX_PERSON_INITIAL_ROLES_LENGTH) {
throw new IllegalArgumentException("List of initial roles is too long. Initial roles list should not have more than " + Constants.MAX_PERSON_INITIAL_ROLES_LENGTH + " characters.");
}
if(expiry != null && expiry.length() > 0) {
try {
this.expiry = Constants.DATE_FORMAT.parse(expiry);
} catch (ParseException e1) {
throw new IllegalArgumentException("Please leave expiry field empty, or enter date using date format: " + Constants.DATE_FORMAT_STRING);
}
}
this.c = c;
this.templateManager = templateManager;
this.site = user.getSite();
this.firstName = chomp(firstName);
this.lastName = chomp(lastName);
this.email = chomp(email).toLowerCase();
this.password = password;
this.user = user;
if(initialRoles != null) {
this.initialRoles = tagsToArray(initialRoles);
for(String i : this.initialRoles) {
if(i.length() > Constants.MAX_ROLE_NAME_LENGTH) {
throw new IllegalArgumentException("Invalid initial role name. Role names do not exceed" + Constants.MAX_ROLE_NAME_LENGTH + " characters.");
}
}
} else {
this.initialRoles = new String[]{};
}
if(username != null) {
this.username = chomp(username).toLowerCase();
}
}
public CreatePerson() {
}
@Override
public Query newWithParameters(Map parameters) throws IOException, PermissionException {
return new CreatePerson(
(CassandraAPI)parameters.get("api"),
((JeeBase)parameters.get("jee")).getTemplateManager(),
(User)parameters.get("user"),
(String)parameters.get("first_name"),
(String)parameters.get("last_name"),
(String)parameters.get("email"),
(String)parameters.get("username"),
(String)parameters.get("password"),
(String)parameters.get("initial_roles"),
(String)parameters.get("expiry"));
}
@Override
protected List execute() throws IOException {
List results = new LinkedList<>();
Settings settings = c.getSettingsCache();
Session s = c.getCassandraSession();
if(!user.hasRole(Constants.PERSON_MANAGE_ROLE)) {
log(s, "WARN", user, "Permission denied invoking: " + CreatePerson.class.getSimpleName() + " " + getJsonParameters());
throw new PermissionException(this.getClass().getSimpleName(), user, "You do not have permission to create new user accounts.", Constants.PERSON_MANAGE_ROLE);
}
UUID uuid = addPerson(s, site, firstName, lastName, email, username, password, expiry);
for(String role : initialRoles) {
if(role.contains(":")) {
String[] parts = role.split(":");
if(parts.length == 3) {
upsertResourceRole(s, uuid, parts[1], parts[2], parts[0], user);
}
} else {
upsertRole(s, uuid, role, user);
}
}
log(s, "INFO", user, "Created new account " + firstName + " " + lastName + ", " + email, new ResourceUid("Person", uuid.toString()));
if(username == null || username.length() == 0 || c.getSettingsCache().get("ldap.enabled", "true").equals("false")) {
String supportTeam = settings.get("support_team.name");
String supportEmail = settings.get("support_team.email");
String token = UUID.randomUUID().toString();
log(s, "FINEST", user, "Storing account activation token " + token + " for person " + email);
PreparedStatement p = s.prepare("insert into request_token (uid, person_uuid, type, ip, expiry, site) values(?,?,'account_activation',?,?,?)");
s.execute(p.bind(token, uuid, user.getIp(), (new Date()).getTime()/1000, site));
ST html = templateManager.getCurrentTemplate(site).getInstanceOf("account_activation_email_html");
html.add("first_name", firstName);
html.add("last_name", lastName);
html.add("email", this.email);
html.add("user", user);
html.add("token", token);
html.add("formurl", c.getSettingsCache().get("base.url"));
ST text = templateManager.getCurrentTemplate(site).getInstanceOf("account_activation_email_text");
text.add("first_name", firstName);
text.add("last_name", lastName);
text.add("email", this.email);
text.add("user", user);
text.add("token", token);
text.add("formurl", c.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("Account activation");
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, "|"));
}
}
results.add(new UuidQueryResult(uuid));
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)+ "\"" +
"}";
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy