added first draft of mapplication support

This commit is contained in:
2018-11-10 14:03:34 +01:00
parent c30af64604
commit 9ebb649458
6 changed files with 1045 additions and 808 deletions

View File

@ -1,287 +1,310 @@
package de.muehlencord.shared.account.business.account.boundary; package de.muehlencord.shared.account.business.account.boundary;
import de.muehlencord.shared.account.business.account.entity.AccountException; import de.muehlencord.shared.account.business.account.entity.AccountException;
import de.muehlencord.shared.account.business.account.entity.AccountStatus; import de.muehlencord.shared.account.business.account.entity.AccountStatus;
import de.muehlencord.shared.account.business.config.boundary.ConfigService; import de.muehlencord.shared.account.business.config.boundary.ConfigService;
import de.muehlencord.shared.account.business.mail.entity.MailException; import de.muehlencord.shared.account.business.mail.entity.MailException;
import de.muehlencord.shared.account.business.mail.boundary.MailService; import de.muehlencord.shared.account.business.mail.boundary.MailService;
import de.muehlencord.shared.account.business.account.entity.AccountEntity; import de.muehlencord.shared.account.business.account.entity.AccountEntity;
import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity;
import de.muehlencord.shared.account.business.config.entity.ConfigException; import de.muehlencord.shared.account.business.config.entity.ConfigException;
import de.muehlencord.shared.account.util.SecurityUtil; import de.muehlencord.shared.account.util.SecurityUtil;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.inject.Inject; import javax.inject.Inject;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.NoResultException; import javax.persistence.NoResultException;
import javax.persistence.Query; import javax.persistence.Query;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
/** /**
* *
* @author joern.muehlencord * @author joern.muehlencord
*/ */
@Stateless @Stateless
public class AccountControl implements Serializable { public class AccountControl implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountControl.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(AccountControl.class.getName());
private static final long serialVersionUID = 3424816272598108101L; private static final long serialVersionUID = 3424816272598108101L;
@EJB @EJB
private ConfigService configService; private ConfigService configService;
@EJB @EJB
private MailService mailService; private MailService mailService;
@Inject @Inject
EntityManager em; EntityManager em;
public List<AccountEntity> getAccounts() { /**
Query query = em.createQuery("SELECT a FROM AccountEntity a WHERE a.status <> :status", AccountEntity.class); * returns a list of active accounts
query.setParameter("status", AccountStatus.DISABLED.name()); *
return query.getResultList(); * @return a list of active accounts
} */
public List<AccountEntity> getActiveAccounts() {
public AccountEntity getAccountEntity(String userName, boolean loadRoles) { Query query = em.createQuery("SELECT a FROM AccountEntity a WHERE a.status <> :status", AccountEntity.class);
StringBuilder queryBuilder = new StringBuilder(); query.setParameter("status", AccountStatus.DISABLED.name());
queryBuilder.append("SELECT a FROM AccountEntity a "); return query.getResultList();
if (loadRoles) { }
queryBuilder.append("JOIN FETCH a.applicationRoleList ");
} /**
queryBuilder.append("WHERE a.username = :username"); * returns a list of active accounts
Query query = em.createQuery(queryBuilder.toString()); *
query.setParameter("username", userName); * @return a list of active accounts
try { */
return (AccountEntity) query.getSingleResult(); public List<AccountEntity> getAllAccounts() {
} catch (NoResultException ex) { Query query = em.createNamedQuery("AccountEntity.findAll");
return null; return query.getResultList();
} }
}
public List<AccountEntity> getAccounts(boolean includeDisabled) {
@Transactional if (includeDisabled) {
// TODO add role names from application because only application can know how its roles are named return getAllAccounts();
public AccountEntity saveAccount(AccountEntity account, boolean isAdmin) { } else {
Date now = new Date(); // Todo now in UTC return getActiveAccounts();
Subject currentUser = SecurityUtils.getSubject(); }
String currentLoggedInUser = currentUser.getPrincipal().toString(); }
account.setLastUpdatedBy(currentLoggedInUser); public AccountEntity getAccountEntity(String userName, boolean loadRoles) {
account.setLastUpdatedOn(now); StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("SELECT a FROM AccountEntity a ");
boolean newAccount = (account.getCreatedOn() == null); if (loadRoles) {
queryBuilder.append("JOIN FETCH a.applicationRoleList ");
// new account }
if (newAccount) { queryBuilder.append("WHERE a.username = :username");
account.setCreatedOn(now); Query query = em.createQuery(queryBuilder.toString());
account.setCreatedBy(currentLoggedInUser); query.setParameter("username", userName);
try {
// set default random password, user has to get password via lost passwort option afterwards return (AccountEntity) query.getSingleResult();
String randomPassword = RandomStringUtils.random(20, true, true); } catch (NoResultException ex) {
String hashedPassword = SecurityUtil.createPassword(randomPassword); return null;
account.setAccountPassword(hashedPassword); }
em.persist(account); }
} else {
em.merge(account); @Transactional
public AccountEntity saveAccount(AccountEntity account, List<ApplicationRoleEntity> applicationRoles) {
// reload account from db and join roles Date now = new Date(); // Todo now in UTC
account = getAccountEntity(account.getUsername(), true); Subject currentUser = SecurityUtils.getSubject();
} String currentLoggedInUser = currentUser.getPrincipal().toString();
// load Admin or User role from database account.setLastUpdatedBy(currentLoggedInUser);
String roleName = (isAdmin ? "Admin" : "User"); account.setLastUpdatedOn(now);
Query roleQuery = em.createNamedQuery("ApplicationRoleEntity.findByRoleName");
roleQuery.setParameter("roleName", roleName); boolean newAccount = (account.getCreatedOn() == null);
ApplicationRoleEntity role = (ApplicationRoleEntity) roleQuery.getSingleResult();
// new account
if (role != null) { if (newAccount) {
// add new user add required role account.setCreatedOn(now);
// do not request based on newUser variable; this way existing users with missing role (for whatever reason) account.setCreatedBy(currentLoggedInUser);
// will be fixed automatically
if (account.getApplicationRoleList() == null || account.getApplicationRoleList().isEmpty()) { // set default random password, user has to get password via lost passwort option afterwards
account.setApplicationRoleList(new ArrayList<>()); String randomPassword = RandomStringUtils.random(20, true, true);
account.getApplicationRoleList().add(role); String hashedPassword = SecurityUtil.createPassword(randomPassword);
em.merge(account); account.setAccountPassword(hashedPassword);
LOGGER.info("Added role " + roleName + " to user " + account.getUsername()); em.persist(account);
} else {
} else if (!account.getApplicationRoleList().get(0).equals(role)) { em.merge(account);
// change role from User to Admin and vice versa
// user already exists, has existing role // reload account from db and join roles
// check if existing role is different from current role and change it account = getAccountEntity(account.getUsername(), true);
// be carefull: this only works as long as a user has exactly one role! }
// he is either User or Admin
// TODO add "UserRole" to every user, make this default Role configurable // assign roles to account
// TODO add AdminRole in addtion if needed if (account.getApplicationRoleList() == null) {
account.getApplicationRoleList().remove(0); account.setApplicationRoleList(new ArrayList<>());
account.getApplicationRoleList().add(role); }
em.merge(account);
LOGGER.info("Switched role of user " + account.getUsername() + " to " + roleName); boolean roleSetupChanged = false;
// remove roles which are no longer listed
} for (ApplicationRoleEntity currentlyAssignedRole : account.getApplicationRoleList()) {
} if (!applicationRoles.contains (currentlyAssignedRole)) {
account.getApplicationRoleList().remove(currentlyAssignedRole);
return account; roleSetupChanged = true;
} if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Removed role {} from user {}", currentlyAssignedRole.getRoleName(), account.getUsername());
public void deleteAccount(AccountEntity account) throws AccountException { }
Date now = new Date(); // Todo now in UTC }
Subject currentUser = SecurityUtils.getSubject(); }
String currentUserName = currentUser.getPrincipal().toString();
// add newly added roles to role list
if (account.getUsername().equals(currentUserName)) { for (ApplicationRoleEntity applicationRole : applicationRoles) {
throw new AccountException("Cannot delete own account"); if (!account.getApplicationRoleList().contains(applicationRole)) {
} else { account.addApplicationRole (applicationRole);
account.setStatus(AccountStatus.DISABLED.name()); roleSetupChanged = true;
account.setLastUpdatedBy(currentUserName); if (LOGGER.isDebugEnabled()) {
account.setLastUpdatedOn(now); LOGGER.debug("Added role {} to account {}", applicationRole.getRoleName(), account.getUsername());
em.merge(account); }
} }
}
}
// update account in database if roles changed
public boolean initPasswordReset(String userName) { if (roleSetupChanged) {
try { em.merge(account);
AccountEntity account = getAccountEntity(userName, false); }
if (account == null) { return account;
LOGGER.warn("Account with name " + userName + " not found"); }
return false;
} @Transactional
public void deleteAccount(AccountEntity account) throws AccountException {
if (account.getStatus().equals(AccountStatus.BLOCKED.name())) { Date now = new Date(); // Todo now in UTC
LOGGER.warn("Account " + userName + " is locked, cannot initialize password reset"); Subject currentUser = SecurityUtils.getSubject();
return false; String currentUserName = currentUser.getPrincipal().toString();
}
if (account.getUsername().equals(currentUserName)) {
String randomString = RandomStringUtils.random(40, true, true); throw new AccountException("Cannot delete own account");
} else {
Date validTo = new Date(); // TODO now in UTC account.setStatus(AccountStatus.DISABLED.name());
validTo = new Date(validTo.getTime() + 1000 * 600); // 10 minutes to react account.setLastUpdatedBy(currentUserName);
account.setLastUpdatedOn(now);
account.setPasswordResetHash(randomString); em.merge(account);
account.setPasswordResetOngoing(true); }
account.setPasswordResetValidTo(validTo);
}
mailService.sendPasswortResetStartEmail(account, randomString);
public boolean initPasswordReset(String userName) {
em.merge(account); try {
return true; AccountEntity account = getAccountEntity(userName, false);
} catch (MailException ex) { if (account == null) {
LOGGER.error("Error while sending password reset mail. " + ex.toString()); LOGGER.warn("Account with name " + userName + " not found");
if (LOGGER.isDebugEnabled()) { return false;
LOGGER.debug("Error while sending password reset mail.", ex); }
}
return false; if (account.getStatus().equals(AccountStatus.BLOCKED.name())) {
} LOGGER.warn("Account " + userName + " is locked, cannot initialize password reset");
} return false;
}
public boolean resetPassword(String userName, String newPassword, String resetPasswordToken) {
AccountEntity account = getAccountEntity(userName, false); String randomString = RandomStringUtils.random(40, true, true);
if (account == null) { Date validTo = new Date(); // TODO now in UTC
LOGGER.warn("Error while resetting password, no account with username " + userName + " found"); validTo = new Date(validTo.getTime() + 1000 * 600); // 10 minutes to react
// TODO add extra logging for intrusion protection system like fail2ban
return false; account.setPasswordResetHash(randomString);
} account.setPasswordResetOngoing(true);
account.setPasswordResetValidTo(validTo);
if (account.getPasswordResetOngoing() && (account.getPasswordResetHash() != null) && (account.getPasswordResetValidTo() != null)) {
Date now = new Date(); // TODO now in UTC mailService.sendPasswortResetStartEmail(account, randomString);
String storedHash = account.getPasswordResetHash().trim();
if (account.getPasswordResetValidTo().after(now)) { em.merge(account);
if (storedHash.equals(resetPasswordToken)) { return true;
// everything ok, reset password } catch (MailException ex) {
executePasswordReset(account, newPassword); LOGGER.error("Error while sending password reset mail. " + ex.toString());
LOGGER.info("Updated password for user " + userName); if (LOGGER.isDebugEnabled()) {
return true; LOGGER.debug("Error while sending password reset mail.", ex);
} else { }
// token is not valid, refuse to change password return false;
LOGGER.warn("Trying to reset password for user " + userName + " but wrong token " + resetPasswordToken + " provided"); }
addLoginError(account); }
return false;
} public boolean resetPassword(String userName, String newPassword, String resetPasswordToken) {
} else { AccountEntity account = getAccountEntity(userName, false);
// password reset token no longer valid
LOGGER.warn("Trying to reset password for user " + userName + " but token is no longer valid"); if (account == null) {
addLoginError(account); LOGGER.warn("Error while resetting password, no account with username " + userName + " found");
return false; // TODO add extra logging for intrusion protection system like fail2ban
} return false;
} else { }
// user is not is password reset mode
LOGGER.warn("Trying to reset password for user " + userName + " but password reset was not requested"); if (account.getPasswordResetOngoing() && (account.getPasswordResetHash() != null) && (account.getPasswordResetValidTo() != null)) {
addLoginError(account); Date now = new Date(); // TODO now in UTC
return false; String storedHash = account.getPasswordResetHash().trim();
} if (account.getPasswordResetValidTo().after(now)) {
} if (storedHash.equals(resetPasswordToken)) {
// everything ok, reset password
private void executePasswordReset(AccountEntity account, String newPassword) { executePasswordReset(account, newPassword);
Date now = new Date(); // TODO now in UTC LOGGER.info("Updated password for user " + userName);
return true;
String hashedPassword = SecurityUtil.createPassword(newPassword); } else {
account.setAccountPassword(hashedPassword); // token is not valid, refuse to change password
LOGGER.warn("Trying to reset password for user " + userName + " but wrong token " + resetPasswordToken + " provided");
account.setPasswordResetOngoing(false); addLoginError(account);
account.setPasswordResetHash(null); return false;
account.setPasswordResetValidTo(null); }
} else {
account.setLastUpdatedBy(account.getUsername()); // password reset token no longer valid
account.setLastUpdatedOn(now); LOGGER.warn("Trying to reset password for user " + userName + " but token is no longer valid");
em.merge(account); addLoginError(account);
return false;
} }
} else {
public void updateLogin(AccountEntity account) { // user is not is password reset mode
Date now = new Date(); // TODO now in UTC LOGGER.warn("Trying to reset password for user " + userName + " but password reset was not requested");
// a scucessful login ends a password reset procedure addLoginError(account);
if (account.getPasswordResetOngoing()) { return false;
account.setPasswordResetOngoing(false); }
account.setPasswordResetHash(null); }
account.setPasswordResetValidTo(null);
account.setLastUpdatedOn(now); private void executePasswordReset(AccountEntity account, String newPassword) {
account.setLastUpdatedBy(account.getUsername()); Date now = new Date(); // TODO now in UTC
}
String hashedPassword = SecurityUtil.createPassword(newPassword);
account.setLastLogin(now); account.setAccountPassword(hashedPassword);
account.setFailureCount(0);
account.setStatus(AccountStatus.NORMAL.name()); account.setPasswordResetOngoing(false);
account.setPasswordResetHash(null);
em.merge(account); account.setPasswordResetValidTo(null);
}
account.setLastUpdatedBy(account.getUsername());
public void addLoginError(AccountEntity account) { account.setLastUpdatedOn(now);
try { em.merge(account);
Date now = new Date(); // TODO now in UTC
account.setLastFailedLogin(now); }
account.setFailureCount(account.getFailureCount() + 1);
public void updateLogin(AccountEntity account) {
int maxFailedLogins = Integer.parseInt(configService.getConfigValue("account.maxFailedLogins")); Date now = new Date(); // TODO now in UTC
if ((account.getFailureCount() >= maxFailedLogins) && (!account.getStatus().equals("LOCKED"))) { // TOD add status enum // a scucessful login ends a password reset procedure
// max failed logins reached, disabling user if (account.getPasswordResetOngoing()) {
LOGGER.info("Locking account " + account.getUsername() + " due to " + account.getFailureCount() + " failed logins"); account.setPasswordResetOngoing(false);
account.setStatus(AccountStatus.BLOCKED.name()); account.setPasswordResetHash(null);
} account.setPasswordResetValidTo(null);
account.setLastUpdatedOn(now);
// on a failed login request, disable password reset account.setLastUpdatedBy(account.getUsername());
account.setPasswordResetOngoing(false); }
account.setPasswordResetHash(null);
account.setPasswordResetValidTo(null); account.setLastLogin(now);
account.setFailureCount(0);
account.setLastUpdatedBy("system"); account.setStatus(AccountStatus.NORMAL.name());
account.setLastUpdatedOn(now);
em.merge(account); em.merge(account);
} catch (ConfigException ex) { }
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(ex.toString(), ex); public void addLoginError(AccountEntity account) {
} else { try {
LOGGER.error(ex.toString()); Date now = new Date(); // TODO now in UTC
} account.setLastFailedLogin(now);
} account.setFailureCount(account.getFailureCount() + 1);
}
int maxFailedLogins = Integer.parseInt(configService.getConfigValue("account.maxFailedLogins"));
} if ((account.getFailureCount() >= maxFailedLogins) && (!account.getStatus().equals("LOCKED"))) { // TOD add status enum
// max failed logins reached, disabling user
LOGGER.info("Locking account " + account.getUsername() + " due to " + account.getFailureCount() + " failed logins");
account.setStatus(AccountStatus.BLOCKED.name());
}
// on a failed login request, disable password reset
account.setPasswordResetOngoing(false);
account.setPasswordResetHash(null);
account.setPasswordResetValidTo(null);
account.setLastUpdatedBy("system");
account.setLastUpdatedOn(now);
em.merge(account);
} catch (ConfigException ex) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(ex.toString(), ex);
} else {
LOGGER.error(ex.toString());
}
}
}
}

View File

@ -1,354 +1,364 @@
package de.muehlencord.shared.account.business.account.entity; package de.muehlencord.shared.account.business.account.entity;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.ArrayList;
import java.util.List; import java.util.Date;
import java.util.UUID; import java.util.List;
import javax.persistence.Basic; import java.util.UUID;
import javax.persistence.CascadeType; import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.CascadeType;
import javax.persistence.Entity; import javax.persistence.Column;
import javax.persistence.FetchType; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.GeneratedValue;
import javax.persistence.JoinColumn; import javax.persistence.Id;
import javax.persistence.JoinTable; import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany; import javax.persistence.JoinTable;
import javax.persistence.NamedQueries; import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery; import javax.persistence.NamedQueries;
import javax.persistence.OneToMany; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.OneToMany;
import javax.persistence.Temporal; import javax.persistence.Table;
import javax.persistence.TemporalType; import javax.persistence.Temporal;
import javax.validation.constraints.NotNull; import javax.persistence.TemporalType;
import javax.validation.constraints.Size; import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement; import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.annotations.GenericGenerator; import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.Type; import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
/**
* /**
* @author joern.muehlencord *
*/ * @author joern.muehlencord
@Entity */
@Table(name = "account") @Entity
@XmlRootElement @Table(name = "account")
@NamedQueries({ @XmlRootElement
@NamedQuery(name = "AccountEntity.findAll", query = "SELECT a FROM AccountEntity a"), @NamedQueries({
@NamedQuery(name = "AccountEntity.findByUsername", query = "SELECT a FROM AccountEntity a WHERE a.username = :username"), @NamedQuery(name = "AccountEntity.findAll", query = "SELECT a FROM AccountEntity a ORDER by a.username"),
@NamedQuery(name = "AccountEntity.findByEmailaddress", query = "SELECT a FROM AccountEntity a WHERE a.emailaddress = :emailaddress"), @NamedQuery(name = "AccountEntity.findByUsername", query = "SELECT a FROM AccountEntity a WHERE a.username = :username"),
@NamedQuery(name = "AccountEntity.findByFirstname", query = "SELECT a FROM AccountEntity a WHERE a.firstname = :firstname"), @NamedQuery(name = "AccountEntity.findByEmailaddress", query = "SELECT a FROM AccountEntity a WHERE a.emailaddress = :emailaddress ORDER BY a.username"),
@NamedQuery(name = "AccountEntity.findByLastname", query = "SELECT a FROM AccountEntity a WHERE a.lastname = :lastname"), @NamedQuery(name = "AccountEntity.findByFirstname", query = "SELECT a FROM AccountEntity a WHERE a.firstname = :firstname ORDER BY a.username"),
@NamedQuery(name = "AccountEntity.findByAccountPassword", query = "SELECT a FROM AccountEntity a WHERE a.accountPassword = :accountPassword"), @NamedQuery(name = "AccountEntity.findByLastname", query = "SELECT a FROM AccountEntity a WHERE a.lastname = :lastname ORDER BY a.username"),
@NamedQuery(name = "AccountEntity.findByLastLogin", query = "SELECT a FROM AccountEntity a WHERE a.lastLogin = :lastLogin"), @NamedQuery(name = "AccountEntity.findByAccountPassword", query = "SELECT a FROM AccountEntity a WHERE a.accountPassword = :accountPassword"),
@NamedQuery(name = "AccountEntity.findByLastFailedLogin", query = "SELECT a FROM AccountEntity a WHERE a.lastFailedLogin = :lastFailedLogin"), @NamedQuery(name = "AccountEntity.findByLastLogin", query = "SELECT a FROM AccountEntity a WHERE a.lastLogin = :lastLogin"),
@NamedQuery(name = "AccountEntity.findByFailureCount", query = "SELECT a FROM AccountEntity a WHERE a.failureCount = :failureCount"), @NamedQuery(name = "AccountEntity.findByLastFailedLogin", query = "SELECT a FROM AccountEntity a WHERE a.lastFailedLogin = :lastFailedLogin"),
@NamedQuery(name = "AccountEntity.findByStatus", query = "SELECT a FROM AccountEntity a WHERE a.status = :status"), @NamedQuery(name = "AccountEntity.findByFailureCount", query = "SELECT a FROM AccountEntity a WHERE a.failureCount = :failureCount"),
@NamedQuery(name = "AccountEntity.findByPasswordResetOngoing", query = "SELECT a FROM AccountEntity a WHERE a.passwordResetOngoing = :passwordResetOngoing"), @NamedQuery(name = "AccountEntity.findByStatus", query = "SELECT a FROM AccountEntity a WHERE a.status = :status"),
@NamedQuery(name = "AccountEntity.findByPasswordResetValidTo", query = "SELECT a FROM AccountEntity a WHERE a.passwordResetValidTo = :passwordResetValidTo"), @NamedQuery(name = "AccountEntity.findByPasswordResetOngoing", query = "SELECT a FROM AccountEntity a WHERE a.passwordResetOngoing = :passwordResetOngoing"),
@NamedQuery(name = "AccountEntity.findByPasswordResetHash", query = "SELECT a FROM AccountEntity a WHERE a.passwordResetHash = :passwordResetHash"), @NamedQuery(name = "AccountEntity.findByPasswordResetValidTo", query = "SELECT a FROM AccountEntity a WHERE a.passwordResetValidTo = :passwordResetValidTo"),
@NamedQuery(name = "AccountEntity.findByCreatedOn", query = "SELECT a FROM AccountEntity a WHERE a.createdOn = :createdOn"), @NamedQuery(name = "AccountEntity.findByPasswordResetHash", query = "SELECT a FROM AccountEntity a WHERE a.passwordResetHash = :passwordResetHash"),
@NamedQuery(name = "AccountEntity.findByCreatedBy", query = "SELECT a FROM AccountEntity a WHERE a.createdBy = :createdBy"), @NamedQuery(name = "AccountEntity.findByCreatedOn", query = "SELECT a FROM AccountEntity a WHERE a.createdOn = :createdOn"),
@NamedQuery(name = "AccountEntity.findByLastUpdatedOn", query = "SELECT a FROM AccountEntity a WHERE a.lastUpdatedOn = :lastUpdatedOn"), @NamedQuery(name = "AccountEntity.findByCreatedBy", query = "SELECT a FROM AccountEntity a WHERE a.createdBy = :createdBy"),
@NamedQuery(name = "AccountEntity.findByLastUpdatedBy", query = "SELECT a FROM AccountEntity a WHERE a.lastUpdatedBy = :lastUpdatedBy")}) @NamedQuery(name = "AccountEntity.findByLastUpdatedOn", query = "SELECT a FROM AccountEntity a WHERE a.lastUpdatedOn = :lastUpdatedOn"),
public class AccountEntity implements Serializable, Account { @NamedQuery(name = "AccountEntity.findByLastUpdatedBy", query = "SELECT a FROM AccountEntity a WHERE a.lastUpdatedBy = :lastUpdatedBy")})
public class AccountEntity implements Serializable, Account {
private static final long serialVersionUID = 6216991757526150935L;
private static final long serialVersionUID = 6216991757526150935L;
@Id
@Basic(optional = false) @Id
@NotNull @Basic(optional = false)
@Column(name = "id") @NotNull
@GeneratedValue(generator = "uuid2") @Column(name = "id")
@GenericGenerator(name = "uuid2", strategy = "uuid2") @GeneratedValue(generator = "uuid2")
@Type(type = "pg-uuid") @GenericGenerator(name = "uuid2", strategy = "uuid2")
private UUID id; @Type(type = "pg-uuid")
@Basic(optional = false) private UUID id;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 32) @NotNull
@Column(name = "username") @Size(min = 1, max = 32)
private String username; @Column(name = "username")
@Basic(optional = false) private String username;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 200) @NotNull
@Column(name = "emailaddress") @Size(min = 1, max = 200)
private String emailaddress; @Column(name = "emailaddress")
@Basic(optional = false) private String emailaddress;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 100) @NotNull
@Column(name = "firstname") @Size(min = 1, max = 100)
private String firstname; @Column(name = "firstname")
@Basic(optional = false) private String firstname;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 100) @NotNull
@Column(name = "lastname") @Size(min = 1, max = 100)
private String lastname; @Column(name = "lastname")
@Basic(optional = false) private String lastname;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 200) @NotNull
@Column(name = "account_password", columnDefinition = "bpchar(200)") @Size(min = 1, max = 200)
private String accountPassword; @Column(name = "account_password", columnDefinition = "bpchar(200)")
@Column(name = "last_login") private String accountPassword;
@Temporal(TemporalType.TIMESTAMP) @Column(name = "last_login")
private Date lastLogin; @Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_failed_login") private Date lastLogin;
@Temporal(TemporalType.TIMESTAMP) @Column(name = "last_failed_login")
private Date lastFailedLogin; @Temporal(TemporalType.TIMESTAMP)
@Basic(optional = false) private Date lastFailedLogin;
@NotNull @Basic(optional = false)
@Column(name = "failure_count") @NotNull
private int failureCount; @Column(name = "failure_count")
@Basic(optional = false) private int failureCount;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 10) @NotNull
@Column(name = "status") @Size(min = 1, max = 10)
private String status; @Column(name = "status")
@Basic(optional = false) private String status;
@NotNull @Basic(optional = false)
@Column(name = "password_reset_ongoing") @NotNull
private boolean passwordResetOngoing; @Column(name = "password_reset_ongoing")
@Column(name = "password_reset_valid_to") private boolean passwordResetOngoing;
@Temporal(TemporalType.TIMESTAMP) @Column(name = "password_reset_valid_to")
private Date passwordResetValidTo; @Temporal(TemporalType.TIMESTAMP)
@Size(max = 200) private Date passwordResetValidTo;
@Column(name = "password_reset_hash", columnDefinition = "bpchar(200)") @Size(max = 200)
private String passwordResetHash; @Column(name = "password_reset_hash", columnDefinition = "bpchar(200)")
@Basic(optional = false) private String passwordResetHash;
@NotNull @Basic(optional = false)
@Column(name = "created_on") @NotNull
@Temporal(TemporalType.TIMESTAMP) @Column(name = "created_on")
private Date createdOn; @Temporal(TemporalType.TIMESTAMP)
@Basic(optional = false) private Date createdOn;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 32) @NotNull
@Column(name = "created_by") @Size(min = 1, max = 32)
private String createdBy; @Column(name = "created_by")
@Basic(optional = false) private String createdBy;
@NotNull @Basic(optional = false)
@Column(name = "last_updated_on") @NotNull
@Temporal(TemporalType.TIMESTAMP) @Column(name = "last_updated_on")
private Date lastUpdatedOn; @Temporal(TemporalType.TIMESTAMP)
@Basic(optional = false) private Date lastUpdatedOn;
@NotNull @Basic(optional = false)
@Size(min = 1, max = 32) @NotNull
@Column(name = "last_updated_by") @Size(min = 1, max = 32)
private String lastUpdatedBy; @Column(name = "last_updated_by")
@JoinTable(name = "account_role", joinColumns = { private String lastUpdatedBy;
@JoinColumn(name = "account", referencedColumnName = "id")}, inverseJoinColumns = { @JoinTable(name = "account_role", joinColumns = {
@JoinColumn(name = "account_role", referencedColumnName = "id")}) @JoinColumn(name = "account", referencedColumnName = "id")}, inverseJoinColumns = {
@ManyToMany(fetch = FetchType.LAZY) @JoinColumn(name = "account_role", referencedColumnName = "id")})
private List<ApplicationRoleEntity> applicationRoleList; @ManyToMany(fetch = FetchType.LAZY)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "accountId", fetch = FetchType.LAZY) private List<ApplicationRoleEntity> applicationRoleList;
private List<AccountHistoryEntity> accountHistoryList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "accountId", fetch = FetchType.LAZY)
private List<AccountHistoryEntity> accountHistoryList;
public AccountEntity() {
} public AccountEntity() {
}
public AccountEntity(UUID id) {
this.id = id; public AccountEntity(UUID id) {
} this.id = id;
}
public AccountEntity (String name) {
this.username = name; public AccountEntity (String name) {
} this.username = name;
}
public AccountEntity(UUID id, String username, String emailaddress, String firstname, String lastname, String accountPassword, int failureCount, String status, boolean passwordResetOngoing, Date createdOn, String createdBy, Date lastUpdatedOn, String lastUpdatedBy) {
this.id = id; public AccountEntity(UUID id, String username, String emailaddress, String firstname, String lastname, String accountPassword, int failureCount, String status, boolean passwordResetOngoing, Date createdOn, String createdBy, Date lastUpdatedOn, String lastUpdatedBy) {
this.username = username; this.id = id;
this.emailaddress = emailaddress; this.username = username;
this.firstname = firstname; this.emailaddress = emailaddress;
this.lastname = lastname; this.firstname = firstname;
this.accountPassword = accountPassword; this.lastname = lastname;
this.failureCount = failureCount; this.accountPassword = accountPassword;
this.status = status; this.failureCount = failureCount;
this.passwordResetOngoing = passwordResetOngoing; this.status = status;
this.createdOn = createdOn; this.passwordResetOngoing = passwordResetOngoing;
this.createdBy = createdBy; this.createdOn = createdOn;
this.lastUpdatedOn = lastUpdatedOn; this.createdBy = createdBy;
this.lastUpdatedBy = lastUpdatedBy; this.lastUpdatedOn = lastUpdatedOn;
} this.lastUpdatedBy = lastUpdatedBy;
}
public UUID getId() {
return id; public void addApplicationRole(ApplicationRoleEntity applicationRole) {
} if (applicationRoleList == null) {
applicationRoleList = new ArrayList<>();
public void setId(UUID id) { }
this.id = id; applicationRoleList.add (applicationRole);
} }
@Override /* **** getter / setter **** */
public String getUsername() {
return username; public UUID getId() {
} return id;
}
public void setUsername(String username) {
this.username = username; public void setId(UUID id) {
} this.id = id;
}
public String getEmailaddress() {
return emailaddress; @Override
} public String getUsername() {
return username;
public void setEmailaddress(String emailaddress) { }
this.emailaddress = emailaddress;
} public void setUsername(String username) {
this.username = username;
@Override }
public String getFirstname() {
return firstname; public String getEmailaddress() {
} return emailaddress;
}
public void setFirstname(String firstname) {
this.firstname = firstname; public void setEmailaddress(String emailaddress) {
} this.emailaddress = emailaddress;
}
@Override
public String getLastname() { @Override
return lastname; public String getFirstname() {
} return firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname; public void setFirstname(String firstname) {
} this.firstname = firstname;
}
public String getAccountPassword() {
return accountPassword; @Override
} public String getLastname() {
return lastname;
public void setAccountPassword(String accountPassword) { }
this.accountPassword = accountPassword;
} public void setLastname(String lastname) {
this.lastname = lastname;
public Date getLastLogin() { }
return lastLogin;
} public String getAccountPassword() {
return accountPassword;
public void setLastLogin(Date lastLogin) { }
this.lastLogin = lastLogin;
} public void setAccountPassword(String accountPassword) {
this.accountPassword = accountPassword;
public Date getLastFailedLogin() { }
return lastFailedLogin;
} public Date getLastLogin() {
return lastLogin;
public void setLastFailedLogin(Date lastFailedLogin) { }
this.lastFailedLogin = lastFailedLogin;
} public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
public int getFailureCount() { }
return failureCount;
} public Date getLastFailedLogin() {
return lastFailedLogin;
public void setFailureCount(int failureCount) { }
this.failureCount = failureCount;
} public void setLastFailedLogin(Date lastFailedLogin) {
this.lastFailedLogin = lastFailedLogin;
public String getStatus() { }
return status;
} public int getFailureCount() {
return failureCount;
public void setStatus(String status) { }
this.status = status;
} public void setFailureCount(int failureCount) {
this.failureCount = failureCount;
public boolean getPasswordResetOngoing() { }
return passwordResetOngoing;
} public String getStatus() {
return status;
public void setPasswordResetOngoing(boolean passwordResetOngoing) { }
this.passwordResetOngoing = passwordResetOngoing;
} public void setStatus(String status) {
this.status = status;
public Date getPasswordResetValidTo() { }
return passwordResetValidTo;
} public boolean getPasswordResetOngoing() {
return passwordResetOngoing;
public void setPasswordResetValidTo(Date passwordResetValidTo) { }
this.passwordResetValidTo = passwordResetValidTo;
} public void setPasswordResetOngoing(boolean passwordResetOngoing) {
this.passwordResetOngoing = passwordResetOngoing;
public String getPasswordResetHash() { }
return passwordResetHash;
} public Date getPasswordResetValidTo() {
return passwordResetValidTo;
public void setPasswordResetHash(String passwordResetHash) { }
this.passwordResetHash = passwordResetHash;
} public void setPasswordResetValidTo(Date passwordResetValidTo) {
this.passwordResetValidTo = passwordResetValidTo;
public Date getCreatedOn() { }
return createdOn;
} public String getPasswordResetHash() {
return passwordResetHash;
public void setCreatedOn(Date createdOn) { }
this.createdOn = createdOn;
} public void setPasswordResetHash(String passwordResetHash) {
this.passwordResetHash = passwordResetHash;
public String getCreatedBy() { }
return createdBy;
} public Date getCreatedOn() {
return createdOn;
public void setCreatedBy(String createdBy) { }
this.createdBy = createdBy;
} public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
public Date getLastUpdatedOn() { }
return lastUpdatedOn;
} public String getCreatedBy() {
return createdBy;
public void setLastUpdatedOn(Date lastUpdatedOn) { }
this.lastUpdatedOn = lastUpdatedOn;
} public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
public String getLastUpdatedBy() { }
return lastUpdatedBy;
} public Date getLastUpdatedOn() {
return lastUpdatedOn;
public void setLastUpdatedBy(String lastUpdatedBy) { }
this.lastUpdatedBy = lastUpdatedBy;
} public void setLastUpdatedOn(Date lastUpdatedOn) {
this.lastUpdatedOn = lastUpdatedOn;
@XmlTransient }
public List<ApplicationRoleEntity> getApplicationRoleList() {
return applicationRoleList; public String getLastUpdatedBy() {
} return lastUpdatedBy;
}
public void setApplicationRoleList(List<ApplicationRoleEntity> applicationRoleList) {
this.applicationRoleList = applicationRoleList; public void setLastUpdatedBy(String lastUpdatedBy) {
} this.lastUpdatedBy = lastUpdatedBy;
}
@XmlTransient
public List<AccountHistoryEntity> getAccountHistoryList() { @XmlTransient
return accountHistoryList; public List<ApplicationRoleEntity> getApplicationRoleList() {
} return applicationRoleList;
}
public void setAccountHistoryList(List<AccountHistoryEntity> accountHistoryList) {
this.accountHistoryList = accountHistoryList; public void setApplicationRoleList(List<ApplicationRoleEntity> applicationRoleList) {
} this.applicationRoleList = applicationRoleList;
}
@Override
public int hashCode() { @XmlTransient
int hash = 0; public List<AccountHistoryEntity> getAccountHistoryList() {
hash += (id != null ? id.hashCode() : 0); return accountHistoryList;
return hash; }
}
public void setAccountHistoryList(List<AccountHistoryEntity> accountHistoryList) {
@Override this.accountHistoryList = accountHistoryList;
public boolean equals(Object object) { }
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AccountEntity)) { @Override
return false; public int hashCode() {
} int hash = 0;
AccountEntity other = (AccountEntity) object; hash += (id != null ? id.hashCode() : 0);
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return hash;
return false; }
}
return true; @Override
} public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
@Override if (!(object instanceof AccountEntity)) {
public String toString() { return false;
return "de.muehlencord.shared.account.entity.Account[ id=" + id + " ]"; }
} AccountEntity other = (AccountEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
} return false;
}
return true;
}
@Override
public String toString() {
return "de.muehlencord.shared.account.entity.Account[ id=" + id + " ]";
}
}

View File

@ -1,15 +1,26 @@
package de.muehlencord.shared.account.business.account.entity; package de.muehlencord.shared.account.business.account.entity;
/** import java.util.ArrayList;
* import java.util.List;
* @author joern.muehlencord
*/ /**
public enum AccountStatus { *
* @author joern.muehlencord
NEW, // account is created but never used */
NORMAL, // normal account, at least on login, neither blocked or disabled public enum AccountStatus {
BLOCKED, // account is blocked after too many login failures or other security related events
DISABLED; // account is disabled and cannot be used anymore NEW, // account is created but never used
NORMAL, // normal account, at least on login, neither blocked or disabled
BLOCKED, // account is blocked after too many login failures or other security related events
} DISABLED; // account is disabled and cannot be used anymore
public static List<String> getAllStatusNames() {
List<String> statusNames = new ArrayList<>();
for (AccountStatus currentStatus : AccountStatus.values()) {
statusNames.add (currentStatus.name());
}
return statusNames;
}
}

View File

@ -1,152 +1,165 @@
package de.muehlencord.shared.account.business.account.entity; package de.muehlencord.shared.account.business.account.entity;
import java.io.Serializable; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.util.List; import java.io.Serializable;
import java.util.UUID; import java.util.List;
import javax.persistence.Basic; import java.util.UUID;
import javax.persistence.Column; import javax.persistence.Basic;
import javax.persistence.Entity; import javax.persistence.Column;
import javax.persistence.GeneratedValue; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.GeneratedValue;
import javax.persistence.JoinColumn; import javax.persistence.Id;
import javax.persistence.JoinTable; import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany; import javax.persistence.JoinTable;
import javax.persistence.NamedQueries; import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.NamedQueries;
import javax.validation.constraints.NotNull; import javax.persistence.NamedQuery;
import javax.validation.constraints.Size; import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement; import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlTransient; import javax.validation.constraints.Size;
import org.hibernate.annotations.GenericGenerator; import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.annotations.Type; import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.GenericGenerator;
/** import org.hibernate.annotations.Type;
*
* @author joern.muehlencord /**
*/ *
@Entity * @author joern.muehlencord
@Table(name = "application_role") */
@XmlRootElement @Entity
@NamedQueries({ @Table(name = "application_role")
@NamedQuery(name = "ApplicationRoleEntity.findAll", query = "SELECT a FROM ApplicationRoleEntity a ORDER BY a.roleName") @XmlRootElement
, @NamedQuery(name = "ApplicationRoleEntity.findByRoleName", query = "SELECT a FROM ApplicationRoleEntity a WHERE a.roleName = :roleName") @NamedQueries({
, @NamedQuery(name = "ApplicationRoleEntity.findByRoleDescription", query = "SELECT a FROM ApplicationRoleEntity a WHERE a.roleDescription = :roleDescription")}) @NamedQuery(name = "ApplicationRoleEntity.findAll", query = "SELECT a FROM ApplicationRoleEntity a ORDER BY a.roleName")
, @NamedQuery(name = "ApplicationRoleEntity.findByRoleName", query = "SELECT a FROM ApplicationRoleEntity a WHERE a.roleName = :roleName")
public class ApplicationRoleEntity implements Serializable { , @NamedQuery(name = "ApplicationRoleEntity.findByRoleDescription", query = "SELECT a FROM ApplicationRoleEntity a WHERE a.roleDescription = :roleDescription")})
private static final long serialVersionUID = -8324054525780893823L; public class ApplicationRoleEntity implements Serializable {
@Id private static final long serialVersionUID = -8324054525780893823L;
@Basic(optional = false)
@NotNull @Id
@Column(name = "id") @Basic(optional = false)
@GeneratedValue(generator = "uuid2") @NotNull
@GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(name = "id")
@Type(type = "pg-uuid") @GeneratedValue(generator = "uuid2")
private UUID id; @GenericGenerator(name = "uuid2", strategy = "uuid2")
@Basic(optional = false) @Type(type = "pg-uuid")
@NotNull private UUID id;
@Size(min = 1, max = 80) @Basic(optional = false)
@Column(name = "role_name") @NotNull
private String roleName; @Size(min = 1, max = 80)
@Basic(optional = false) @Column(name = "role_name")
@NotNull private String roleName;
@Size(min = 1, max = 200) @Basic(optional = false)
@Column(name = "role_description") @NotNull
private String roleDescription; @Size(min = 1, max = 200)
@ManyToMany(mappedBy = "applicationRoleList") @Column(name = "role_description")
private List<AccountEntity> accountList; private String roleDescription;
@JoinTable(name = "role_permission", joinColumns = { @ManyToMany(mappedBy = "applicationRoleList")
@JoinColumn(name = "application_role", referencedColumnName = "id")}, inverseJoinColumns = { private List<AccountEntity> accountList;
@JoinColumn(name = "role_permission", referencedColumnName = "id")}) @JoinTable(name = "role_permission", joinColumns = {
@ManyToMany @JoinColumn(name = "application_role", referencedColumnName = "id")}, inverseJoinColumns = {
private List<ApplicationPermissionEntity> applicationPermissionList; @JoinColumn(name = "role_permission", referencedColumnName = "id")})
@ManyToMany
public ApplicationRoleEntity() { private List<ApplicationPermissionEntity> applicationPermissionList;
} @JoinColumn(name = "application", referencedColumnName = "id")
@ManyToOne(optional = false)
public ApplicationRoleEntity(UUID id) { private ApplicationEntity application;
this.id = id;
} public ApplicationRoleEntity() {
}
public ApplicationRoleEntity(String roleName, String roleDescription) {
this.id = null; public ApplicationRoleEntity(UUID id) {
this.roleName = roleName; this.id = id;
this.roleDescription = roleDescription; }
}
public ApplicationRoleEntity(String roleName, String roleDescription) {
public ApplicationRoleEntity(UUID id, String roleName, String roleDescription) { this.id = null;
this.id = id; this.roleName = roleName;
this.roleName = roleName; this.roleDescription = roleDescription;
this.roleDescription = roleDescription; }
}
public ApplicationRoleEntity(UUID id, String roleName, String roleDescription) {
public UUID getId() { this.id = id;
return id; this.roleName = roleName;
} this.roleDescription = roleDescription;
}
public void setId(UUID id) {
this.id = id; public UUID getId() {
} return id;
}
public String getRoleName() {
return roleName; public void setId(UUID id) {
} this.id = id;
}
public void setRoleName(String roleName) {
this.roleName = roleName; public String getRoleName() {
} return roleName;
}
public String getRoleDescription() {
return roleDescription; public void setRoleName(String roleName) {
} this.roleName = roleName;
}
public void setRoleDescription(String roleDescription) {
this.roleDescription = roleDescription; public String getRoleDescription() {
} return roleDescription;
}
@XmlTransient
public List<AccountEntity> getAccountList() { public void setRoleDescription(String roleDescription) {
return accountList; this.roleDescription = roleDescription;
} }
public void setAccountList(List<AccountEntity> accountList) { @XmlTransient
this.accountList = accountList; public List<AccountEntity> getAccountList() {
} return accountList;
}
@XmlTransient
public List<ApplicationPermissionEntity> getApplicationPermissionList() { public void setAccountList(List<AccountEntity> accountList) {
return applicationPermissionList; this.accountList = accountList;
} }
public void setApplicationPermissionList(List<ApplicationPermissionEntity> applicationPermissionList) { @XmlTransient
this.applicationPermissionList = applicationPermissionList; public List<ApplicationPermissionEntity> getApplicationPermissionList() {
} return applicationPermissionList;
}
@Override
public int hashCode() { public void setApplicationPermissionList(List<ApplicationPermissionEntity> applicationPermissionList) {
int hash = 0; this.applicationPermissionList = applicationPermissionList;
hash += (id != null ? id.hashCode() : 0); }
return hash;
} public ApplicationEntity getApplication() {
return application;
@Override }
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set public void setApplication(ApplicationEntity application) {
if (!(object instanceof ApplicationRoleEntity)) { this.application = application;
return false; }
}
ApplicationRoleEntity other = (ApplicationRoleEntity) object; @Override
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { public int hashCode() {
return false; int hash = 0;
} hash += (id != null ? id.hashCode() : 0);
return true; return hash;
} }
@Override @Override
public String toString() { public boolean equals(Object object) {
return "de.muehlencord.shared.account.entity.ApplicationRole[ id=" + id + " ]"; // TODO: Warning - this method won't work in the case the id fields are not set
} if (!(object instanceof ApplicationRoleEntity)) {
return false;
} }
ApplicationRoleEntity other = (ApplicationRoleEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "de.muehlencord.shared.account.entity.ApplicationRole[ id=" + id + " ]";
}
}

View File

@ -0,0 +1,73 @@
package de.muehlencord.shared.account.business.application.boundary;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Joern Muehlencord <joern at muehlencord.de>
*/
@Stateless
public class ApplicationService implements Serializable {
private static final long serialVersionUID = 4262608935325326191L;
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationService.class);
@Inject
EntityManager em;
public List<ApplicationEntity> getAllApplications() {
Query query = em.createNamedQuery("ApplicationEntity.findAll");
List<ApplicationEntity> resultList = query.getResultList();
if (resultList == null) {
return new ArrayList<>();
} else {
return resultList;
}
}
@Transactional
public ApplicationEntity createOrUpdate(ApplicationEntity app) {
if (app == null) {
// TODO add error handling
return null;
} else {
if (app.getId() == null) {
em.persist(app);
ApplicationEntity returnValue = findByApplicationName(app.getApplicationName());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Application {} created", app.getApplicationName());
}
return returnValue;
} else {
ApplicationEntity returnValue = em.merge(app);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Applicateion {} updated", app.getApplicationName());
}
return returnValue;
}
}
}
public ApplicationEntity findByApplicationName(String applicationName) {
Query query = em.createNamedQuery("ApplicationEntity.findByApplicationName");
query.setParameter("applicationName", applicationName);
List<ApplicationEntity> resultList = query.getResultList();
if ((resultList == null) || (resultList.isEmpty())) {
return null;
} else {
return resultList.get(0);
}
}
}

View File

@ -0,0 +1,107 @@
package de.muehlencord.shared.account.business.application.entity;
import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
/**
*
* @author Joern Muehlencord <joern at muehlencord.de>
*/
@Entity
@Table(name = "application")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ApplicationEntity.findAll", query = "SELECT a FROM ApplicationEntity a"),
@NamedQuery(name = "ApplicationEntity.findByApplicationName", query = "SELECT a FROM ApplicationEntity a WHERE a.applicationName = :applicationName")})
public class ApplicationEntity implements Serializable {
private static final long serialVersionUID = -6407525020014743727L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Type(type = "pg-uuid")
private UUID id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "application_name", unique = true)
private String applicationName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "application")
private List<ApplicationRoleEntity> applicationRoleEntityList;
public ApplicationEntity() {
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@XmlTransient
public List<ApplicationRoleEntity> getApplicationRoleEntityList() {
return applicationRoleEntityList;
}
public void setApplicationRoleEntityList(List<ApplicationRoleEntity> applicationRoleEntityList) {
this.applicationRoleEntityList = applicationRoleEntityList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ApplicationEntity)) {
return false;
}
ApplicationEntity other = (ApplicationEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "de.muehlencord.shared.account.business.application.entity.ApplicationEntity[ id=" + id + " ]";
}
}