completed update of account, splitted login from account

This commit is contained in:
2018-11-14 17:16:12 +01:00
parent 939f043b01
commit 765589afdf
27 changed files with 3383 additions and 3157 deletions

View File

@ -1,140 +1,145 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<artifactId>shared</artifactId> <artifactId>shared</artifactId>
<groupId>de.muehlencord</groupId> <groupId>de.muehlencord</groupId>
<version>1.1-SNAPSHOT</version> <version>1.1-SNAPSHOT</version>
</parent> </parent>
<groupId>de.muehlencord.shared</groupId> <groupId>de.muehlencord.shared</groupId>
<artifactId>shared-account-ui</artifactId> <artifactId>shared-account-ui</artifactId>
<version>1.1-SNAPSHOT</version> <version>1.1-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>shared-account-ui</name> <name>shared-account-ui</name>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<timestamp>${maven.build.timestamp}</timestamp> <timestamp>${maven.build.timestamp}</timestamp>
<maven.compiler.source>10</maven.compiler.source> <maven.compiler.source>10</maven.compiler.source>
<maven.compiler.target>10</maven.compiler.target> <maven.compiler.target>10</maven.compiler.target>
<!-- defaul filter if not selected via profile --> <!-- defaul filter if not selected via profile -->
<filter.name>development</filter.name> <filter.name>development</filter.name>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.primefaces</groupId> <groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId> <artifactId>primefaces</artifactId>
</dependency> </dependency>
<!-- Admin faces template --> <!-- Admin faces template -->
<dependency> <dependency>
<groupId>com.github.adminfaces</groupId> <groupId>com.github.adminfaces</groupId>
<artifactId>admin-template</artifactId> <artifactId>admin-template</artifactId>
<version>1.0.0-RC19</version> <version>1.0.0-RC19</version>
</dependency> </dependency>
<!-- Omnifaces, faces utils --> <!-- Omnifaces, faces utils -->
<dependency> <dependency>
<groupId>org.omnifaces</groupId> <groupId>org.omnifaces</groupId>
<artifactId>omnifaces</artifactId> <artifactId>omnifaces</artifactId>
<version>2.7</version> <version>2.7</version>
</dependency> </dependency>
<!-- Apache Shiro, Security API --> <!-- Apache Shiro, Security API -->
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId> <artifactId>shiro-core</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId> <artifactId>shiro-web</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>de.muehlencord.shared</groupId> <groupId>de.muehlencord.shared</groupId>
<artifactId>shared-shiro-faces</artifactId> <artifactId>shared-shiro-faces</artifactId>
<version>1.1-SNAPSHOT</version> <version>1.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>de.muehlencord.shared</groupId> <groupId>de.muehlencord.shared</groupId>
<artifactId>shared-account</artifactId> <artifactId>shared-account</artifactId>
<version>1.1-SNAPSHOT</version> <version>1.1-SNAPSHOT</version>
<type>jar</type> </dependency>
</dependency> <dependency>
<dependency> <groupId>de.muehlencord.shared</groupId>
<groupId>de.muehlencord.sf</groupId> <artifactId>shared-util</artifactId>
<artifactId>filter</artifactId> <version>1.1-SNAPSHOT</version>
<version>1.0</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>de.muehlencord.sf</groupId>
<groupId>javax</groupId> <artifactId>filter</artifactId>
<artifactId>javaee-web-api</artifactId> <version>1.0</version>
<version>7.0</version> </dependency>
<scope>provided</scope> <dependency>
</dependency> <groupId>javax</groupId>
</dependencies> <artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<build> <scope>provided</scope>
<filters> </dependency>
<filter>${basedir}/src/main/filters/${filter.name}.properties</filter> </dependencies>
</filters>
<build>
<resources> <filters>
<!-- fill buildinformation file --> <filter>${basedir}/src/main/filters/${filter.name}.properties</filter>
<resource> </filters>
<directory>src/main/resources</directory>
<filtering>true</filtering> <resources>
<includes> <!-- fill buildinformation file -->
<include>**/*.properties</include> <resource>
</includes> <directory>src/main/resources</directory>
</resource> <filtering>true</filtering>
</resources> <includes>
<include>**/*.properties</include>
<finalName>account</finalName> <include>**/*.xml</include>
<plugins> </includes>
<plugin> </resource>
<groupId>org.apache.maven.plugins</groupId> </resources>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version> <finalName>account</finalName>
<configuration> <plugins>
<source>10</source> <plugin>
<target>10</target> <groupId>org.apache.maven.plugins</groupId>
</configuration> <artifactId>maven-compiler-plugin</artifactId>
</plugin> <version>3.8.0</version>
<plugin> <configuration>
<groupId>org.apache.maven.plugins</groupId> <source>10</source>
<artifactId>maven-war-plugin</artifactId> <target>10</target>
<version>3.2.2</version> </configuration>
<configuration> </plugin>
<failOnMissingWebXml>false</failOnMissingWebXml> <plugin>
<webResources> <groupId>org.apache.maven.plugins</groupId>
<resource> <artifactId>maven-war-plugin</artifactId>
<directory>${basedir}/src/main/webapp</directory> <version>3.2.2</version>
<filtering>true</filtering> <configuration>
<includes> <failOnMissingWebXml>false</failOnMissingWebXml>
<include>WEB-INF/web.xml</include> <webResources>
<include>WEB-INF/shiro.ini</include> <resource>
</includes> <directory>${basedir}/src/main/webapp</directory>
</resource> <filtering>true</filtering>
</webResources> <includes>
</configuration> <include>WEB-INF/web.xml</include>
</plugin> <include>WEB-INF/shiro.ini</include>
</plugins> </includes>
</build> </resource>
</webResources>
<profiles> </configuration>
<profile> </plugin>
<id>development</id> </plugins>
<properties> </build>
<filter.name>development</filter.name>
</properties> <profiles>
</profile> <profile>
<id>development</id>
<profile> <properties>
<id>production</id> <filter.name>development</filter.name>
<properties> </properties>
<filter.name>production</filter.name> </profile>
</properties>
</profile> <profile>
</profiles> <id>production</id>
</project> <properties>
<filter.name>production</filter.name>
</properties>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,67 @@
/*
* Copyright 2018 Joern Muehlencord <joern at muehlencord.de>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.muehlencord.shared.account.web;
import de.muehlencord.shared.account.business.application.boundary.ApplicationService;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Joern Muehlencord <joern at muehlencord.de>
*/
@Named("applicationProdiucer")
@ApplicationScoped
public class ApplicationProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationProducer.class);
@EJB
ApplicationService applicationService;
private ApplicationEntity application = null;
@PostConstruct
public void init() {
String id = "143a2bd3-7e0b-4162-a76e-3031331c7dfe"; // TODO load from properties file
this.application = applicationService.findById(UUID.fromString(id));
if (application == null) {
LOGGER.error("Could not find application with id ");
} else {
LOGGER.info("Found application {} for id{}", application.getApplicationName(), id);
}
}
/**
* needs to return link to "Account UI" and not to current selected
* application TODO: ensure only Account UI can call functions where
* appliction can be handed in all other applications need to call the
* function which use the injected application
*/
@Produces
public ApplicationEntity getApplication() {
return application;
}
}

View File

@ -1,186 +1,300 @@
package de.muehlencord.shared.account.web.presentation; package de.muehlencord.shared.account.web.presentation;
import de.muehlencord.shared.account.business.account.boundary.AccountControl; import de.muehlencord.shared.account.business.account.boundary.AccountControl;
import de.muehlencord.shared.account.business.account.boundary.ApplicationRoleControl; import de.muehlencord.shared.account.business.account.boundary.ApplicationRoleControl;
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.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.AccountLoginEntity;
import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity; import de.muehlencord.shared.account.business.account.entity.AccountStatus;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity;
import de.muehlencord.shared.jeeutil.FacesUtil; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.io.Serializable; import de.muehlencord.shared.jeeutil.FacesUtil;
import java.util.ArrayList; import java.io.Serializable;
import java.util.List; import java.util.ArrayList;
import javax.ejb.EJB; import java.util.List;
import javax.faces.view.ViewScoped; import java.util.Locale;
import javax.inject.Named; import javax.ejb.EJB;
import javax.inject.Inject; import javax.faces.component.UIInput;
import org.primefaces.event.SelectEvent; import javax.faces.context.FacesContext;
import org.slf4j.Logger; import javax.faces.view.ViewScoped;
import org.slf4j.LoggerFactory; import javax.inject.Named;
import javax.inject.Inject;
/** import org.apache.shiro.SecurityUtils;
* import org.apache.shiro.subject.Subject;
* @author jomu import org.primefaces.event.SelectEvent;
*/ import org.primefaces.event.UnselectEvent;
@ViewScoped import org.slf4j.Logger;
@Named("accountView") import org.slf4j.LoggerFactory;
public class AccountView implements Serializable {
/**
private static final long serialVersionUID = -8050582392249849438L; *
private static final Logger LOGGER = LoggerFactory.getLogger(AccountView.class); * @author jomu
*/
@Inject @ViewScoped
private ApplicationView applicationView; @Named("accountView")
@EJB public class AccountView implements Serializable {
private AccountControl accountService;
@EJB private static final long serialVersionUID = -8050582392249849438L;
private ApplicationRoleControl appliationRoleService; private static final Logger LOGGER = LoggerFactory.getLogger(AccountView.class);
/** @Inject
* boolean flag to determine wether disabled accounts should be shown private ApplicationView applicationView;
* accounts are not deleted but disabled and can be activated in case @EJB
*/ private AccountControl accountService;
private boolean showDisabledAccounts = false; @EJB
private ApplicationRoleControl appliationRoleService;
// cached accounts
private List<AccountEntity> accountList = null; /**
// cached application roles * boolean flag to determine wether disabled accounts should be shown
private List<ApplicationRoleEntity> applicationRoles = null; * accounts are not deleted but disabled and can be activated in case
*/
// account currently on edit private boolean showDisabledAccounts = false;
private AccountEntity currentAccount;
private List<ApplicationRoleEntity> currentAccountRoles = null; // cached accounts
private List<AccountEntity> accountList = null;
public List<AccountEntity> getAccounts() { // cached application roles
if (accountList == null) { private List<ApplicationRoleEntity> applicationRoles = null;
accountList = accountService.getAccounts(showDisabledAccounts);
} // account currently on edit
return accountList; private AccountEntity currentAccount;
} private List<ApplicationRoleEntity> currentAccountRoles = null;
private AccountLoginEntity currentAccountLogin;
public List<ApplicationRoleEntity> getAllApplicationRoles() { private String password = null;
if (applicationRoles == null) { private String repeatPassword = null;
ApplicationEntity application = applicationView.getCurrentApplication();
applicationRoles = appliationRoleService.getAllRoles(application); public List<AccountEntity> getAccounts() {
} if (accountList == null) {
return applicationRoles; accountList = accountService.getAccounts(showDisabledAccounts);
} }
return accountList;
public void selectAccount(SelectEvent event) { }
if (currentAccount == null) {
applicationRoles = null; public List<ApplicationRoleEntity> getAllApplicationRoles() {
currentAccountRoles = null; if (applicationRoles == null) {
} ApplicationEntity application = applicationView.getCurrentApplication();
} applicationRoles = appliationRoleService.getAllRoles(application);
}
public boolean getAccountSelected() { return applicationRoles;
return currentAccount != null; }
}
public void selectAccount(SelectEvent event) {
public void newAccount() { // nothing to do, currentAccountRoles are loaded before dialog is shown
currentAccount = new AccountEntity(); }
currentAccount.setUsername(null);
currentAccount.setStatus("NEW"); // TODO add status enum public void unselectAccount(UnselectEvent event) {
currentAccountRoles = new ArrayList<>(); applicationRoles = null;
} currentAccountRoles = null;
}
public void editAccount() {
// function called by webpage public boolean getAccountSelected() {
if (currentAccount == null) { return currentAccount != null;
currentAccountRoles = null; }
} else {
currentAccount = accountService.getAccountEntity(currentAccount.getUsername(), true); public void newAccount() {
this.currentAccountRoles = new ArrayList<>(); currentAccount = new AccountEntity();
if (currentAccount.getApplicationRoleList() != null) { currentAccount.setStatus("NEW"); // TODO add status enum
currentAccountRoles.addAll(currentAccount.getApplicationRoleList()); currentAccountRoles = new ArrayList<>();
} }
}
} public void editAccount() {
// function called by webpage
public void cancelEditAccount() { if (currentAccount == null) {
currentAccount = null; currentAccountRoles = null;
currentAccountRoles = null; } else {
} currentAccount = accountService.getAccountEntity(currentAccount.getUsername(), true);
this.currentAccountRoles = new ArrayList<>();
public void saveEditAccount() { if (currentAccount.getApplicationRoleList() != null) {
String username = currentAccount.getUsername(); currentAccountRoles.addAll(currentAccount.getApplicationRoleList());
AccountEntity existingEntity = accountService.getAccountEntity(username, true); }
// check if it is a new user (createdBy == null) but a user with same name already exists }
if ((currentAccount.getCreatedBy() == null) && (existingEntity != null)) { }
currentAccount.setUsername(null);
FacesUtil.addErrorMessage("editDialogMessaegs", "Create new account failed", "Account with username " + username + " already exists"); public void cancelEditAccount() {
} else { currentAccount = null;
accountService.saveAccount(applicationView.getCurrentApplication(), currentAccount, currentAccountRoles); currentAccountRoles = null;
if (currentAccount.getId() == null) { }
// this was a new account
// force accounts to be loaded from database again public void saveEditAccount() {
accountList = null; String username = currentAccount.getUsername();
} AccountEntity existingEntity = accountService.getAccountEntity(username, true);
} // check if it is a new user (createdBy == null) but a user with same name already exists
} if ((currentAccount.getCreatedBy() == null) && (existingEntity != null)) {
FacesUtil.addErrorMessage("editDialogMessaegs", "Create new account failed", "Account with username " + username + " already exists");
public void deleteAccount() { } else {
try { accountService.saveAccount(currentAccount, currentAccountRoles);
accountService.deleteAccount(currentAccount); // force accounts to be loaded from database again
accountList.remove(currentAccount); accountList = null;
FacesUtil.addGlobalInfoMessage("Info", "Account " + currentAccount.getUsername() + " deleted");
currentAccount = null; }
currentAccountRoles = null; }
} catch (AccountException ex) {
if (LOGGER.isDebugEnabled()) { public void deleteAccount() {
LOGGER.debug(ex.toString(), ex); try {
} else { accountService.deleteAccount(currentAccount);
LOGGER.error(ex.toString()); accountList.remove(currentAccount);
} FacesUtil.addGlobalInfoMessage("Info", "Account " + currentAccount.getUsername() + " deleted");
currentAccount = null;
FacesUtil.addGlobalErrorMessage("Error deleting account", ex.getMessage()); currentAccountRoles = null;
} } catch (AccountException ex) {
} if (LOGGER.isDebugEnabled()) {
LOGGER.debug(ex.toString(), ex);
public void showDisabledAccountsChange() { } else {
if (LOGGER.isDebugEnabled()) { LOGGER.error(ex.toString());
LOGGER.debug("show diabled accounts changed to {}", showDisabledAccounts); }
}
this.accountList = null; FacesUtil.addGlobalErrorMessage("Error deleting account", ex.getMessage());
} }
}
public List<String> getStatusList() {
return AccountStatus.getAllStatusNames(); public void showDisabledAccountsChange() {
} if (LOGGER.isDebugEnabled()) {
LOGGER.debug("show diabled accounts changed to {}", showDisabledAccounts);
/* **** getter / setter **** */ }
/** this.accountList = null;
* setter for managed property applicationView }
*
* @param applicationView the applicaton view to inject public List<String> getStatusList() {
*/ return AccountStatus.getAllStatusNames();
public void setApplicationView(ApplicationView applicationView) { }
this.applicationView = applicationView;
} /* **** account login methods **** */
public boolean validatePasswords(FacesContext context, List<UIInput> components, List<Object> values) {
public AccountEntity getCurrentAccount() { String password = components.get(0).getSubmittedValue().toString();
return currentAccount; String passwordRepeat = components.get(1).getSubmittedValue().toString();
}
if ((password == null) || (passwordRepeat == null)) {
public void setCurrentAccount(AccountEntity currentAccount) { return false;
this.currentAccount = currentAccount; }
} boolean returnValue = password.equals(passwordRepeat);
return returnValue;
public boolean isShowDisabledAccounts() { }
return showDisabledAccounts;
} public void addAccountLogin() {
if (currentAccount == null) {
public void setShowDisabledAccounts(boolean showDisabledAccounts) { // TODO add error handling
this.showDisabledAccounts = showDisabledAccounts; } else {
} this.currentAccountLogin = accountService.createLoginWithRandomPassword();
}
public List<ApplicationRoleEntity> getCurrentAccountRoles() { }
return currentAccountRoles;
} public void editAccountLogin() {
if (currentAccount == null) {
public void setCurrentAccountRoles(List<ApplicationRoleEntity> currentAccountRoles) { // TODO add error handling
this.currentAccountRoles = currentAccountRoles; } else {
} this.currentAccountLogin = currentAccount.getAccountLogin();
}
} }
public void deleteAccountLogin() {
if (currentAccount == null) {
// TODO add error handling
} else {
accountService.deleteLogin(currentAccount);
currentAccount.setAccountLogin(null);
currentAccountLogin = null;
accountList = null; // force reload
FacesUtil.addGlobalInfoMessage("Account saved", "Login removed");
}
}
public void saveEditAccountLogin() {
// TODO move to account control - to much logic for the view
if ((currentAccountLogin == null) || (currentAccount == null)) {
// TODO add error handling
} else {
// overwrite password if provided
if ((password != null) && (!password.trim().equals(""))) {
// password has been specified
if (password.equals(repeatPassword)) {
currentAccount.getAccountLogin().setAccountPassword(accountService.getHashedPassword(password));
FacesUtil.addGlobalInfoMessage("Info", "Password updated");
} else {
// TODO connect to IPRS
// frontend does validate passwords do match
// someone is trying to cheat
}
}
if (currentAccountLogin.getId() == null) {
accountService.addLogin(currentAccount, currentAccountLogin);
currentAccount.setAccountLogin(currentAccountLogin);
accountList = null; // force reload of accounts
} else {
accountService.updateLogin(currentAccountLogin);
}
currentAccountLogin = null;
FacesUtil.addGlobalInfoMessage("Account saved", "Login data updated");
}
}
public void cancelEditAccountLogin() {
this.currentAccountLogin = null;
}
public boolean getCurrentLoggedInUser() {
if (currentAccount == null) {
return false;
}
Subject currentUser = SecurityUtils.getSubject();
if (currentUser == null) {
// TODO - connect to IPRS - how can this method be called if no user is logged in
return false;
}
String currentUserName = currentUser.getPrincipal().toString();
return currentUserName.equals(currentAccount.getUsername());
}
/* **** getter / setter **** */
/**
* setter for managed property applicationView
*
* @param applicationView the applicaton view to inject
*/
public void setApplicationView(ApplicationView applicationView) {
this.applicationView = applicationView;
}
public AccountEntity getCurrentAccount() {
return currentAccount;
}
public void setCurrentAccount(AccountEntity currentAccount) {
this.currentAccount = currentAccount;
}
public boolean isShowDisabledAccounts() {
return showDisabledAccounts;
}
public void setShowDisabledAccounts(boolean showDisabledAccounts) {
this.showDisabledAccounts = showDisabledAccounts;
}
public List<ApplicationRoleEntity> getCurrentAccountRoles() {
return currentAccountRoles;
}
public void setCurrentAccountRoles(List<ApplicationRoleEntity> currentAccountRoles) {
this.currentAccountRoles = currentAccountRoles;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepeatPassword() {
return repeatPassword;
}
public void setRepeatPassword(String repeatPassword) {
this.repeatPassword = repeatPassword;
}
}

View File

@ -1,149 +1,145 @@
/* /*
* Copyright 2017 Joern Muehlencord <joern at muehlencord.de>. * Copyright 2017 Joern Muehlencord <joern at muehlencord.de>.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package de.muehlencord.shared.account.web.presentation; package de.muehlencord.shared.account.web.presentation;
import de.muehlencord.shared.account.business.account.boundary.ApplicationPermissionControl; import de.muehlencord.shared.account.business.account.boundary.ApplicationPermissionControl;
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.ApplicationPermissionEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import de.muehlencord.shared.jeeutil.FacesUtil; import de.muehlencord.shared.jeeutil.FacesUtil;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.inject.Named; import javax.inject.Named;
import javax.faces.view.ViewScoped; import javax.faces.view.ViewScoped;
import javax.inject.Inject; import javax.inject.Inject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* *
* @author Joern Muehlencord <joern at muehlencord.de> * @author Joern Muehlencord <joern at muehlencord.de>
*/ */
@ViewScoped @ViewScoped
@Named("permissionView") @Named("permissionView")
public class PermissionView implements Serializable { public class PermissionView implements Serializable {
private static final long serialVersionUID = -1469453490360990772L; private static final long serialVersionUID = -1469453490360990772L;
private static final Logger LOGGER = LoggerFactory.getLogger(PermissionView.class); private static final Logger LOGGER = LoggerFactory.getLogger(PermissionView.class);
@Inject @Inject
private ApplicationView applicationView; private ApplicationView applicationView;
@EJB @EJB
ApplicationPermissionControl applicationPermissionService; ApplicationPermissionControl applicationPermissionService;
private ApplicationPermissionEntity currentPermission; private ApplicationPermissionEntity currentPermission;
public List<ApplicationPermissionEntity> getAppPermissions() { public List<ApplicationPermissionEntity> getAppPermissions() {
return applicationPermissionService.getApplicationPermissions(applicationView.getCurrentApplication()); return applicationPermissionService.getApplicationPermissions(applicationView.getCurrentApplication());
} }
public void saveEditPermission() throws AccountException { public void saveEditPermission() throws AccountException {
if (currentPermission != null) { if (currentPermission != null) {
ApplicationEntity currentApplication = applicationView.getCurrentApplication(); String newPermissionName = currentPermission.getPermissionName();
String currentApplicationName = currentApplication.getApplicationName(); String newPermissionDescription = currentPermission.getPermissionDescription();
String newPermissionName = currentPermission.getPermissionName(); if ((newPermissionName == null) || (newPermissionName.trim().length() == 0)) {
String newPermissionDescription = currentPermission.getPermissionDescription(); FacesUtil.addErrorMessage("editDialogMessages", "Error", "Permission name must not be null");
if ((newPermissionName == null) || (newPermissionName.trim().length() == 0)) { } else if ((newPermissionDescription == null) || (newPermissionDescription.trim().length() == 0)) {
FacesUtil.addErrorMessage("editDialogMessages", "Error", "Permission name must not be null"); FacesUtil.addErrorMessage("editDialogMessages", "Error", "Permission name must not be null");
} else if ((newPermissionDescription == null) || (newPermissionDescription.trim().length() == 0)) { } else {
FacesUtil.addErrorMessage("editDialogMessages", "Error", "Permission name must not be null"); if (currentPermission.getId() == null) {
} else { applicationPermissionService.create(applicationView.getCurrentApplication(), newPermissionName, newPermissionName);
if (currentPermission.getId() == null) { FacesUtil.addGlobalInfoMessage("Info", "Permission " + newPermissionName + " created");
applicationPermissionService.create(currentApplicationName, newPermissionName, newPermissionName); } else {
FacesUtil.addGlobalInfoMessage("Info", "Permission " + newPermissionName + " created"); applicationPermissionService.update(currentPermission);
// deselectPermission(); FacesUtil.addGlobalInfoMessage("Info", "Permission " + newPermissionName + " updated");
} else { }
applicationPermissionService.update(currentPermission); }
FacesUtil.addGlobalInfoMessage("Info", "Permission " + newPermissionName + " updated"); }
// deselectPermission(); }
}
} public ApplicationEntity getCurrentApplication() {
} if (applicationView.getCurrentApplication() == null) {
} return null;
} else {
public ApplicationEntity getCurrentApplication() { return applicationView.getCurrentApplication();
if (applicationView.getCurrentApplication() == null) { }
return null; }
} else {
return applicationView.getCurrentApplication(); public void cancelEditPermission() {
} this.currentPermission = null;
} }
public void cancelEditPermission() { public void newPermission() {
this.currentPermission = null; this.currentPermission = new ApplicationPermissionEntity();
} }
public void newPermission() { public void editPermission() {
this.currentPermission = new ApplicationPermissionEntity(); if (currentPermission == null) {
} FacesUtil.addGlobalErrorMessage("Error", "Please select a permission to edit");
}
public void editPermission() { }
if (currentPermission == null) {
FacesUtil.addGlobalErrorMessage("Error", "Please select a permission to edit"); public void deletePermission() {
} if (currentPermission == null) {
} FacesUtil.addGlobalErrorMessage("Error", "Please select a permission to edit");
} else {
public void deletePermission() { try {
if (currentPermission == null) { applicationPermissionService.delete(currentPermission);
FacesUtil.addGlobalErrorMessage("Error", "Please select a permission to edit"); currentPermission = null;
} else { } catch (AccountException ex) {
try { if (LOGGER.isDebugEnabled()) {
applicationPermissionService.delete(currentPermission); LOGGER.debug(ex.toString(), ex);
currentPermission = null; } else {
} catch (AccountException ex) { LOGGER.debug(ex.toString());
if (LOGGER.isDebugEnabled()) { }
LOGGER.debug(ex.toString(), ex); FacesUtil.addGlobalErrorMessage("Error while deleting permission.", ex.toString());
} else { }
LOGGER.debug(ex.toString()); }
} }
FacesUtil.addGlobalErrorMessage("Error while deleting permission.", ex.toString());
} public boolean getCanEdit() {
} return isPermissionSelected();
} }
public boolean getCanEdit() { public boolean getCanDelete() {
return isPermissionSelected(); return isPermissionSelected();
} }
public boolean getCanDelete() { /* *** getter / setter *** */
return isPermissionSelected(); /**
} * required setter for managedProperty
*
/* *** getter / setter *** */ *
/** * @param applicationView the injected applicationView
* required setter for managedProperty */
* public void setApplicationView(ApplicationView applicationView) {
* this.applicationView = applicationView;
* @param applicationView the injected applicationView }
*/
public void setApplicationView(ApplicationView applicationView) { public ApplicationPermissionEntity getCurrentPermission() {
this.applicationView = applicationView; return currentPermission;
} }
public ApplicationPermissionEntity getCurrentPermission() { public void setCurrentPermission(ApplicationPermissionEntity newCurrentPermission) {
return currentPermission; this.currentPermission = newCurrentPermission;
}
}
public void setCurrentPermission(ApplicationPermissionEntity newCurrentPermission) {
this.currentPermission = newCurrentPermission; public boolean isPermissionSelected() {
return currentPermission != null;
} }
}
public boolean isPermissionSelected() {
return currentPermission != null;
}
}

View File

@ -1,60 +1,56 @@
package de.muehlencord.shared.account.web.presentation; package de.muehlencord.shared.account.web.presentation;
import de.muehlencord.shared.account.business.account.boundary.ApplicationPermissionControl; import de.muehlencord.shared.account.business.account.boundary.ApplicationRoleControl;
import de.muehlencord.shared.account.business.account.boundary.ApplicationRoleControl; import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity;
import de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity; import de.muehlencord.shared.account.business.application.boundary.ApplicationService;
import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import java.io.Serializable;
import java.io.Serializable; import javax.ejb.EJB;
import javax.ejb.EJB; import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent;
import javax.faces.component.UIComponent; import javax.faces.context.FacesContext;
import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator;
import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator;
import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException;
import javax.faces.validator.ValidatorException; import javax.inject.Inject;
import javax.inject.Inject; import javax.persistence.EntityManager;
import javax.persistence.EntityManager;
import org.slf4j.Logger; /**
import org.slf4j.LoggerFactory; *
* @author Joern Muehlencord <joern at muehlencord.de>
/** */
* @FacesValidator("uniqueApplicationRoleNameValidator")
* @author Joern Muehlencord <joern at muehlencord.de> public class UniqueApplicationRoleNameValidator implements Validator, Serializable {
*/
@FacesValidator("uniqueApplicationRoleNameValidator") private static final long serialVersionUID = 8165013107453616719L;
public class UniqueApplicationRoleNameValidator implements Validator, Serializable {
@Inject
private static final long serialVersionUID = 8165013107453616719L; EntityManager em;
@Inject @EJB
EntityManager em; ApplicationRoleControl applicationRoleControl;
@EJB @Override
ApplicationRoleControl applicationRoleControl; public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object applicationObj = component.getAttributes().get("application");
@Override if ((applicationObj != null) && (applicationObj instanceof ApplicationEntity)) {
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { ApplicationEntity application = (ApplicationEntity) applicationObj;
Object applicationObj = component.getAttributes().get("application"); if (value == null) {
if ((applicationObj != null) && (applicationObj instanceof ApplicationEntity)) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Role name invalid", "Role name must not be empty"));
ApplicationEntity application = (ApplicationEntity) applicationObj; }
if (value == null) { if (value instanceof String) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Role name invalid", "Role name must not be empty")); String roleName = (String) value;
} ApplicationRoleEntity existingRole = applicationRoleControl.findByName(application, roleName);
if (value instanceof String) { if (existingRole != null) {
String roleName = (String) value; throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Role name invalid", "Role already exists"));
ApplicationRoleEntity existingRole = applicationRoleControl.findByName(application, roleName); }
if (existingRole != null) { } else {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Role name invalid", "Role already exists")); throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Role name invalid", "Role name must be a string value"));
} // TODO add IPRS logger - someone is trying to cheat
} else { }
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Role name invalid", "Role name must be a string value")); } else {
// TODO add IPRS logger - someone is trying to cheat throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Application not set", "Permission name cannot be set if application is unknown"));
} }
} else { }
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Application not set", "Permission name cannot be set if application is unknown"));
} }
}
}

View File

@ -1,59 +1,59 @@
package de.muehlencord.shared.account.web.presentation; package de.muehlencord.shared.account.web.presentation;
import de.muehlencord.shared.account.business.account.boundary.ApplicationPermissionControl; import de.muehlencord.shared.account.business.account.boundary.ApplicationPermissionControl;
import de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.io.Serializable; import java.io.Serializable;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent; import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext; import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator; import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator; import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException; import javax.faces.validator.ValidatorException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* *
* @author Joern Muehlencord <joern at muehlencord.de> * @author Joern Muehlencord <joern at muehlencord.de>
*/ */
@FacesValidator("uniquePermissionNameValidator") @FacesValidator("uniquePermissionNameValidator")
public class UniquePermissionNameValidator implements Validator, Serializable { public class UniquePermissionNameValidator implements Validator, Serializable {
private static final long serialVersionUID = 2526409681909574670L; private static final long serialVersionUID = 2526409681909574670L;
private static final Logger LOGGER = LoggerFactory.getLogger(UniquePermissionNameValidator.class); private static final Logger LOGGER = LoggerFactory.getLogger(UniquePermissionNameValidator.class);
@Inject @Inject
EntityManager em; EntityManager em;
@EJB @EJB
ApplicationPermissionControl applicationPermissionControl; ApplicationPermissionControl applicationPermissionControl;
@Override @Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object applicationObj = component.getAttributes().get("application"); Object applicationObj = component.getAttributes().get("application");
if ((applicationObj != null) && (applicationObj instanceof ApplicationEntity)) { if ((applicationObj != null) && (applicationObj instanceof ApplicationEntity)) {
ApplicationEntity application = (ApplicationEntity) applicationObj; ApplicationEntity application = (ApplicationEntity) applicationObj;
if (value == null) { if (value == null) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Permission name invalid", "Permission name must not be empty")); throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Permission name invalid", "Permission name must not be empty"));
} }
if (value instanceof String) { if (value instanceof String) {
String permissionName = (String) value; String permissionName = (String) value;
ApplicationPermissionEntity existingPermission = applicationPermissionControl.findPermissionByName(application, permissionName); ApplicationPermissionEntity existingPermission = applicationPermissionControl.findPermissionByName(application, permissionName);
if (existingPermission != null) { if (existingPermission != null) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Permission name invalid", "Permission already exists")); throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Permission name invalid", "Permission already exists"));
} }
} else { } else {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Permission name invalid", "Permission name must be a string value")); throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Permission name invalid", "Permission name must be a string value"));
// TODO add IPRS logger - someone is trying to cheat // TODO add IPRS logger - someone is trying to cheat
} }
} else { } else {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Application not set", "Permission name cannot be set if application is unknown")); throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Application not set", "Permission name cannot be set if application is unknown"));
} }
} }
} }

View File

@ -1,14 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="com.wincornixdorf.pcd_pu" transaction-type="JTA"> <persistence-unit name="de.muehlencord.shared.accountUiPu" transaction-type="JTA">
<jta-data-source>java:/jboss/accountTestDs</jta-data-source> <jta-data-source>java:/jboss/accountTestDs</jta-data-source>
<class>de.muehlencord.shared.account.business.account.entity.AccountEntity</class> <class>de.muehlencord.shared.account.business.account.entity.AccountEntity</class>
<class>de.muehlencord.shared.account.business.account.entity.AccountHistoryEntity</class> <class>de.muehlencord.shared.account.business.account.entity.AccountHistoryEntity</class>
<class>de.muehlencord.shared.account.business.account.entity.AccountLoginEntity</class>
<class>de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity</class> <class>de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity</class>
<class>de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity</class> <class>de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity</class>
<class>de.muehlencord.shared.account.business.application.entity.ApplicationEntity</class>
<class>de.muehlencord.shared.account.business.config.entity.ConfigEntity</class> <class>de.muehlencord.shared.account.business.config.entity.ConfigEntity</class>
<class>de.muehlencord.shared.account.business.mail.entity.MailTemplateEntity</class> <class>de.muehlencord.shared.account.business.mail.entity.MailTemplateEntity</class>
<class>de.muehlencord.shared.account.business.application.entity.ApplicationEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes> <exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>NONE</validation-mode> <validation-mode>NONE</validation-mode>

View File

@ -1,132 +1,133 @@
header_login=Login header_login=Login
header_reset_password=Reset password header_reset_password=Reset password
message_username_password=Please enter your user name and a new password message_username_password=Please enter your user name and a new password
button_login=Login button_login=Login
button_cancel=Cancel button_cancel=Cancel
button_password_lost=Password lost? button_password_lost=Password lost?
label_username=Username label_username=Username
label_password=Password label_password=Password
label_new_password=New Password label_new_password=New Password
button_password_reset=Reset password button_password_reset=Reset password
header_passwort_lost=Lost password header_passwort_lost=Lost password
message_start_password_reset=Please enter your username to start the password recovery procedure message_start_password_reset=Please enter your username to start the password recovery procedure
menu_dashboard=Dashboard menu_dashboard=Dashboard
menu_events=Events menu_events=Events
menu_administration=Administration menu_administration=Administration
menu_overview=Overview menu_overview=Overview
menu_emails=Emails menu_emails=Emails
menu_account=Account menu_account=Account
menu_config=Config menu_config=Config
menu_logout=Logout menu_logout=Logout
button_new=New button_new=New
button_delete=Delete button_delete=Delete
button_edit=Edit button_edit=Edit
button_reload=Reload button_reload=Reload
label_name=Name label_name=Name
label_description=Description label_description=Description
label_event_date=Event Date label_event_date=Event Date
label_reservation=Reservation label_reservation=Reservation
label_reservation_from_to=Reservation from/to label_reservation_from_to=Reservation from/to
label_actions=Actions label_actions=Actions
message_confirm=Are you sure? message_confirm=Are you sure?
button_setup=Setup button_setup=Setup
button_reservations=Reservations button_reservations=Reservations
label_event_name=Event Name label_event_name=Event Name
label_event_item_desc=Event Item Description label_event_item_desc=Event Item Description
label_timezone=Timezone label_timezone=Timezone
label_event_start=Event Start label_event_start=Event Start
label_event_end=Event End label_event_end=Event End
label_reservation_autostart=Reservation start label_reservation_autostart=Reservation start
label_reservation_autoend=Reservation end label_reservation_autoend=Reservation end
label_reservation_active=Reservation active label_reservation_active=Reservation active
label_reservation_max_items=Max Items label_reservation_max_items=Max Items
label_booking_deadline=Booking deadline label_booking_deadline=Booking deadline
label_template_validation=Email validation mail template label_template_validation=Email validation mail template
label_template_confirmation=Event confirmation mail template label_template_confirmation=Event confirmation mail template
label_template_waitlist=Event waitlist mail template label_template_waitlist=Event waitlist mail template
message_event_not_found=Event not found message_event_not_found=Event not found
label_items=Items label_items=Items
label_costs=Costs label_costs=Costs
label_all=All label_all=All
label_yes=Yes label_yes=Yes
label_no=No label_no=No
label_status=Status label_status=Status
label_firstname=Firstname label_firstname=Firstname
label_lastname=Lastname label_lastname=Lastname
label_emailaddress=Emailaddress label_emailaddress=Emailaddress
label_comment=Comment label_comment=Comment
label_email_confirmed=Email confirmed label_email_confirmed=Email confirmed
label_booking_number=Booking Number label_booking_number=Booking Number
label_booking_executed=booking executed label_booking_executed=booking executed
tt_log_entries=Show log entries tt_log_entries=Show log entries
tt_cancel_reservation=Cancel the current reservation tt_cancel_reservation=Cancel the current reservation
tt_send_email_again=Send email again tt_send_email_again=Send email again
tt_move_from_wl=Move from waitlist tt_move_from_wl=Move from waitlist
tt_fix_reservation=Try to fix the current reservation tt_fix_reservation=Try to fix the current reservation
tt_edit_reservation=Edit the reservation tt_edit_reservation=Edit the reservation
button_refresh_free=Refresh free button_refresh_free=Refresh free
button_manual_reserve=Reserve button_manual_reserve=Reserve
button_export=Export button_export=Export
label_amount=Amount label_amount=Amount
label_select=Select label_select=Select
label_created_by=Created by label_created_by=Created by
label_ip=IP label_ip=IP
label_ip_forwarded=IP (forwarded) label_ip_forwarded=IP (forwarded)
label_value=Value label_value=Value
label_useragent=Useragent label_useragent=Useragent
button_ok=Ok button_ok=Ok
message_comment=Please add a comment message_comment=Please add a comment
menu_help=Help menu_help=Help
label_event=Event label_event=Event
label_active=Active label_active=Active
label_waitlist=Waitlist label_waitlist=Waitlist
label_is_waitlist=Is waitlist label_is_waitlist=Is waitlist
label_order=Order label_order=Order
message_dynamic_numbering=dynamic numbering (put %n as placeholder) message_dynamic_numbering=dynamic numbering (put %n as placeholder)
label_start_number=Start Number label_start_number=Start Number
label_end_number=End Number label_end_number=End Number
header_item_def=Define items for event header_item_def=Define items for event
message_no_event_items=No event item defined message_no_event_items=No event item defined
button_overview=Overview button_overview=Overview
label_reservation_auto_start=Automatically switch on/off label_reservation_auto_start=Automatically switch on/off
label_item_public=Item public? label_item_public=Item public?
label_is_publicitem=Is public label_is_publicitem=Is public
label_customer_comment=Customer comment label_customer_comment=Customer comment
label_change_comment=Change comment label_change_comment=Change comment
label_existing_items=current items label_existing_items=current items
label_new_items=new items label_new_items=new items
label_available_items=available items label_available_items=available items
label_no_records=No records found. label_no_records=No records found.
button_mail=Mail button_mail=Mail
header_email_distribution=Email distribution header_email_distribution=Email distribution
label_template=Template label_template=Template
label_demomode=Demo mode label_demomode=Demo mode
message_invalid_email=Please provide a valid email address message_invalid_email=Please provide a valid email address
menu_permissions=Permissions menu_permissions=Permissions
button_save=Save button_save=Save
menu_groups=Groups menu_groups=Groups
message_email_sent=email sent message_email_sent=email sent
message_email_with_error=emails with error message_email_with_error=emails with error
message_no_email=no email address defined message_no_email=no email address defined
message_email_not_sent=Error while sending emails message_email_not_sent=Error while sending emails
label_seating=Seating label_seating=Seating
label_attachments=Attachments label_attachments=Attachments
label_language=Language label_language=Language
label_subject=Subject label_subject=Subject
label_bytes=Bytes label_bytes=Bytes
label_upload=Upload label_upload=Upload
header_export=Export header_export=Export
label_export_type=Export Type label_export_type=Export Type
label_filtered=Filtered label_filtered=Filtered
label_include_deleted=Include deleted label_include_deleted=Include deleted
label_include_log=Include Logs label_include_log=Include Logs
label_template_booking_executed=Booking executed template label_template_booking_executed=Booking executed template
label_street=Street label_street=Street
label_zipCode=ZIP Code label_zipCode=ZIP Code
label_city=City label_city=City
label_groupName=Groupname label_groupName=Groupname
label_phoneNumber=Phone Number label_phoneNumber=Phone Number
label_template_waitlist_cancelled=Waitlist cancelled mail template label_template_waitlist_cancelled=Waitlist cancelled mail template
msgs_menu_status=Status msgs_menu_status=Status
menu_status=Status menu_status=Status
button_add=Add button_add=Add
passwords_different=Passwords do not match, please check input

View File

@ -1,133 +1,134 @@
header_login=Anmeldung header_login=Anmeldung
header_reset_password=Passwort zur\u00fccksetzten header_reset_password=Passwort zur\u00fccksetzten
message_username_password=Bitte geben Deinen Benutzernamen und dein Passwort ein message_username_password=Bitte geben Deinen Benutzernamen und dein Passwort ein
button_login=Anmelden button_login=Anmelden
button_cancel=Abbruch button_cancel=Abbruch
button_password_lost=Passwort vergessen? button_password_lost=Passwort vergessen?
label_username=Benutzername label_username=Benutzername
label_password=Passwort label_password=Passwort
label_new_password=Neues Passwort label_new_password=Neues Passwort
button_password_reset=Passwort zur\u00fccksetzten button_password_reset=Passwort zur\u00fccksetzten
header_passwort_lost=Passwort vergessen header_passwort_lost=Passwort vergessen
message_start_password_reset=Bitte gib deinen Benutzernamen ein um das Zur\u00fccksetzten des Passworts zu starten. message_start_password_reset=Bitte gib deinen Benutzernamen ein um das Zur\u00fccksetzten des Passworts zu starten.
menu_dashboard=Dashbaord menu_dashboard=Dashbaord
menu_events=Veranstaltungen menu_events=Veranstaltungen
menu_administration=Administration menu_administration=Administration
menu_overview=\u00dcbersicht menu_overview=\u00dcbersicht
menu_emails=E-Mails menu_emails=E-Mails
menu_account=Benutzer menu_account=Benutzer
menu_config=Konfiguration menu_config=Konfiguration
menu_logout=Abmelden menu_logout=Abmelden
button_new=Neu button_new=Neu
button_delete=L\u00f6schen button_delete=L\u00f6schen
button_edit=Bearbeiten button_edit=Bearbeiten
button_reload=Aktualisieren button_reload=Aktualisieren
label_name=Name label_name=Name
label_description=Beschreibung label_description=Beschreibung
label_event_date=Veranstaltungsdatum label_event_date=Veranstaltungsdatum
label_reservation=Reservierung label_reservation=Reservierung
label_reservation_from_to=Reservierung von/bis label_reservation_from_to=Reservierung von/bis
label_actions=Aktionen label_actions=Aktionen
message_confirm=Bist du sicher? message_confirm=Bist du sicher?
button_setup=Setup button_setup=Setup
button_reservations=Reservierungen button_reservations=Reservierungen
label_event_name=Veranstaltungsname label_event_name=Veranstaltungsname
label_event_item_desc=Veranstaltungsobjekte label_event_item_desc=Veranstaltungsobjekte
label_timezone=Zeitzone label_timezone=Zeitzone
label_event_start=Veranstaltungsbeginn label_event_start=Veranstaltungsbeginn
label_event_end=Veranstaltungsende label_event_end=Veranstaltungsende
label_reservation_autostart=Reservierung von label_reservation_autostart=Reservierung von
label_reservation_autoend=Reservierung bis label_reservation_autoend=Reservierung bis
label_reservation_active=Reservierung aktiv label_reservation_active=Reservierung aktiv
label_reservation_max_items=Maximale Objekte label_reservation_max_items=Maximale Objekte
label_booking_deadline=Buchungsfrist label_booking_deadline=Buchungsfrist
label_template_validation=Vorlage Emailvalidierung label_template_validation=Vorlage Emailvalidierung
label_template_confirmation=Vorlage Reservierungsbest\u00e4tigung label_template_confirmation=Vorlage Reservierungsbest\u00e4tigung
label_template_waitlist=Vorlage Wartelist label_template_waitlist=Vorlage Wartelist
message_event_not_found=Veranstaltung nicht gefunden message_event_not_found=Veranstaltung nicht gefunden
label_items=Objekte label_items=Objekte
label_costs=Kosten label_costs=Kosten
label_all=Alle label_all=Alle
label_yes=Ja label_yes=Ja
label_no=Nein label_no=Nein
label_status=Status label_status=Status
label_firstname=Vorname label_firstname=Vorname
label_lastname=Nachname label_lastname=Nachname
label_emailaddress=E-Mail-Adresse label_emailaddress=E-Mail-Adresse
label_comment=Kommentar label_comment=Kommentar
label_email_confirmed=E-Mail best\u00e4tigt label_email_confirmed=E-Mail best\u00e4tigt
label_booking_number=Buchungsnummer label_booking_number=Buchungsnummer
label_booking_executed=Buchungs ausgef\u00fchrt label_booking_executed=Buchungs ausgef\u00fchrt
tt_log_entries=Logbucheintr\u00e4ge tt_log_entries=Logbucheintr\u00e4ge
tt_cancel_reservation=Storniere die Reservierung tt_cancel_reservation=Storniere die Reservierung
tt_send_email_again=Sende E-Mail erneut tt_send_email_again=Sende E-Mail erneut
tt_move_from_wl=Schiebe von Warteliste tt_move_from_wl=Schiebe von Warteliste
tt_fix_reservation=Versuche den Fehler zu beheben tt_fix_reservation=Versuche den Fehler zu beheben
tt_edit_reservation=Bearbeite die Reservierung tt_edit_reservation=Bearbeite die Reservierung
button_refresh_free=Frei aktualisieren button_refresh_free=Frei aktualisieren
button_manual_reserve=Reservieren button_manual_reserve=Reservieren
button_export=Exportieren button_export=Exportieren
label_amount=Anzahl label_amount=Anzahl
label_select=W\u00e4hlen label_select=W\u00e4hlen
label_created_by=Erzeugt durch label_created_by=Erzeugt durch
label_ip=IP label_ip=IP
label_ip_forwarded=IP (forwarded) label_ip_forwarded=IP (forwarded)
label_value=Wert label_value=Wert
label_useragent=Useragent label_useragent=Useragent
button_ok=Ok button_ok=Ok
message_comment=Bitte geben Sie einen Kommentar an message_comment=Bitte geben Sie einen Kommentar an
menu_help=Hilfe menu_help=Hilfe
label_event=Veranstaltung label_event=Veranstaltung
label_active=Aktiv label_active=Aktiv
label_waitlist=Warteliste label_waitlist=Warteliste
label_is_waitlist=Ist Warteliste label_is_waitlist=Ist Warteliste
label_order=Reihenfolge label_order=Reihenfolge
message_dynamic_numbering=Dynamische Nummerierung (%n als Platzhalter) message_dynamic_numbering=Dynamische Nummerierung (%n als Platzhalter)
label_start_number=Startnummer label_start_number=Startnummer
label_end_number=Endnummer label_end_number=Endnummer
header_item_def=Objekte f\u00fcr Veranstaltung header_item_def=Objekte f\u00fcr Veranstaltung
message_no_event_items=Keine Objekte definiert message_no_event_items=Keine Objekte definiert
button_overview=\u00dcbersicht button_overview=\u00dcbersicht
label_reservation_auto_start=Automatisch ein/ausschalten label_reservation_auto_start=Automatisch ein/ausschalten
label_item_public=\u00d6ffentlich verf\u00fcgar? label_item_public=\u00d6ffentlich verf\u00fcgar?
label_is_publicitem=\u00d6ffentlich label_is_publicitem=\u00d6ffentlich
label_customer_comment=Kundenkommentar label_customer_comment=Kundenkommentar
label_change_comment=\u00c4nderungskommentar label_change_comment=\u00c4nderungskommentar
label_existing_items=aktuelle Objekte label_existing_items=aktuelle Objekte
label_new_items=neue Objekte label_new_items=neue Objekte
label_available_items=verf\u00fcgbare Objekte label_available_items=verf\u00fcgbare Objekte
label_no_records=Keine Daten gefunden. label_no_records=Keine Daten gefunden.
button_mail=E-Mail button_mail=E-Mail
header_email_distribution=Emailversand header_email_distribution=Emailversand
label_template=Vorlage label_template=Vorlage
label_demomode=Demomodus label_demomode=Demomodus
message_invalid_email=Bitte geben Sie eine g\u00fcltige Emailadresse an message_invalid_email=Bitte geben Sie eine g\u00fcltige Emailadresse an
menu_permissions=Berechtigungen menu_permissions=Berechtigungen
button_save=Speichern button_save=Speichern
menu_groups=Gruppen menu_groups=Gruppen
message_email_sent=Email gesendet message_email_sent=Email gesendet
message_email_with_error=Emails mit Fehler message_email_with_error=Emails mit Fehler
message_no_email=keine Emailadresse verf\u00fcgbar message_no_email=keine Emailadresse verf\u00fcgbar
message_email_not_sent=Fehler beim Versenden der Email message_email_not_sent=Fehler beim Versenden der Email
label_seating=Saalplan Platz label_seating=Saalplan Platz
label_attachments=Attachments label_attachments=Attachments
label_language=Sprache label_language=Sprache
label_subject=Betreff label_subject=Betreff
label_bytes=Bytes label_bytes=Bytes
label_upload=Upload label_upload=Upload
header_export=Exportieren header_export=Exportieren
label_export_type=Export Art label_export_type=Export Art
label_filtered=Gefiltert label_filtered=Gefiltert
label_include_deleted=Einschlie\u00dflich gel\u00f6scht label_include_deleted=Einschlie\u00dflich gel\u00f6scht
label_include_log=mit Logbuch label_include_log=mit Logbuch
label_template_booking_executed=Vorlage Buchung durchgef\u00fchrt label_template_booking_executed=Vorlage Buchung durchgef\u00fchrt
label_street=Stra\u00dfe label_street=Stra\u00dfe
label_zipCode=PLZ label_zipCode=PLZ
label_city=Ort label_city=Ort
label_groupName=Gruppenname label_groupName=Gruppenname
label_phoneNumber=Telefonnummer label_phoneNumber=Telefonnummer
label_template_waitlist_cancelled=Vorlage Warteliste Abbruch label_template_waitlist_cancelled=Vorlage Warteliste Abbruch
msgs_menu_status=Status msgs_menu_status=Status
menu_status=Status menu_status=Status
button_add=Hinzuf\u00fcgen button_add=Hinzuf\u00fcgen
passwords_different=Passw\u00f6rter stimmen \u00fcberein, bitte \u00fcberpr\u00fcfen Sie ihre Eingabe

View File

@ -1,133 +1,134 @@
header_login=Login header_login=Login
header_reset_password=Reset password header_reset_password=Reset password
message_username_password=Please enter your user name and a new password message_username_password=Please enter your user name and a new password
button_login=Login button_login=Login
button_cancel=Cancel button_cancel=Cancel
button_password_lost=Password lost? button_password_lost=Password lost?
label_username=Username label_username=Username
label_password=Password label_password=Password
label_new_password=New Password label_new_password=New Password
button_password_reset=Reset password button_password_reset=Reset password
header_passwort_lost=Lost password header_passwort_lost=Lost password
message_start_password_reset=Please enter your username to start the password recovery procedure message_start_password_reset=Please enter your username to start the password recovery procedure
menu_dashboard=Dashboard menu_dashboard=Dashboard
menu_events=Events menu_events=Events
menu_administration=Administration menu_administration=Administration
menu_overview=Overview menu_overview=Overview
menu_emails=Emails menu_emails=Emails
menu_account=Account menu_account=Account
menu_config=Config menu_config=Config
menu_logout=Logout menu_logout=Logout
button_new=New button_new=New
button_delete=Delete button_delete=Delete
button_edit=Edit button_edit=Edit
button_reload=Reload button_reload=Reload
label_name=Name label_name=Name
label_description=Description label_description=Description
label_event_date=Event Date label_event_date=Event Date
label_reservation=Reservation label_reservation=Reservation
label_reservation_from_to=Reservation from/to label_reservation_from_to=Reservation from/to
label_actions=Actions label_actions=Actions
message_confirm=Are you sure? message_confirm=Are you sure?
button_setup=Setup button_setup=Setup
button_reservations=Reservations button_reservations=Reservations
label_event_name=Event Name label_event_name=Event Name
label_event_item_desc=Event Item Description label_event_item_desc=Event Item Description
label_timezone=Timezone label_timezone=Timezone
label_event_start=Event Start label_event_start=Event Start
label_event_end=Event End label_event_end=Event End
label_reservation_autostart=Reservation Start label_reservation_autostart=Reservation Start
label_reservation_autoend=Reservation End label_reservation_autoend=Reservation End
label_reservation_active=Reservation active label_reservation_active=Reservation active
label_reservation_max_items=Max Items label_reservation_max_items=Max Items
label_booking_deadline=Booking deadline label_booking_deadline=Booking deadline
label_template_validation=Email validation mail template label_template_validation=Email validation mail template
label_template_confirmation=Event confirmation mail template label_template_confirmation=Event confirmation mail template
label_template_waitlist=Event waitlist mail template label_template_waitlist=Event waitlist mail template
message_event_not_found=Event not found message_event_not_found=Event not found
label_items=Items label_items=Items
label_costs=Costs label_costs=Costs
label_all=All label_all=All
label_yes=Yes label_yes=Yes
label_no=No label_no=No
label_status=Status label_status=Status
label_firstname=Firstname label_firstname=Firstname
label_lastname=Lastname label_lastname=Lastname
label_emailaddress=Emailaddress label_emailaddress=Emailaddress
label_comment=Comment label_comment=Comment
label_email_confirmed=Email confirmed label_email_confirmed=Email confirmed
label_booking_number=Booking Number label_booking_number=Booking Number
label_booking_executed=booking executed label_booking_executed=booking executed
tt_log_entries=Show log entries tt_log_entries=Show log entries
tt_cancel_reservation=Cancel the current reservation tt_cancel_reservation=Cancel the current reservation
tt_send_email_again=Send email again tt_send_email_again=Send email again
tt_move_from_wl=Move from waitlist tt_move_from_wl=Move from waitlist
tt_fix_reservation=Try to fix the current reservation tt_fix_reservation=Try to fix the current reservation
tt_edit_reservation=Edit the reservation tt_edit_reservation=Edit the reservation
button_refresh_free=Refresh free button_refresh_free=Refresh free
button_manual_reserve=Reserve button_manual_reserve=Reserve
button_export=Export button_export=Export
label_amount=Amount label_amount=Amount
label_select=Select label_select=Select
label_created_by=Created by label_created_by=Created by
label_ip=IP label_ip=IP
label_ip_forwarded=IP (forwarded) label_ip_forwarded=IP (forwarded)
label_value=Value label_value=Value
label_useragent=Useragent label_useragent=Useragent
button_ok=Ok button_ok=Ok
message_comment=Please add a comment message_comment=Please add a comment
menu_help=Help menu_help=Help
label_event=Event label_event=Event
label_active=Active label_active=Active
label_waitlist=Waitlist label_waitlist=Waitlist
label_is_waitlist=Is waitlist label_is_waitlist=Is waitlist
label_order=Reservation Order label_order=Reservation Order
message_dynamic_numbering=dynamic numbering (put %n as placeholder) message_dynamic_numbering=dynamic numbering (put %n as placeholder)
label_start_number=Start Number label_start_number=Start Number
label_end_number=End Number label_end_number=End Number
header_item_def=Define items for event header_item_def=Define items for event
message_no_event_items=No event item defined message_no_event_items=No event item defined
button_overview=Overview button_overview=Overview
label_reservation_auto_start=Automatically switch on/off label_reservation_auto_start=Automatically switch on/off
label_item_public=Item public? label_item_public=Item public?
label_is_publicitem=Is public label_is_publicitem=Is public
label_customer_comment=Customer comment label_customer_comment=Customer comment
label_change_comment=Change comment label_change_comment=Change comment
label_existing_items=current items label_existing_items=current items
label_new_items=new items label_new_items=new items
label_available_items=available items label_available_items=available items
label_no_records=No records found. label_no_records=No records found.
button_mail=Mail button_mail=Mail
header_email_distribution=Email distribution header_email_distribution=Email distribution
label_template=Template label_template=Template
label_demomode=Demo mode label_demomode=Demo mode
message_invalid_email=Please provide a valid email address message_invalid_email=Please provide a valid email address
menu_permissions=Permissions menu_permissions=Permissions
button_save=Save button_save=Save
menu_groups=Groups menu_groups=Groups
message_email_sent=email sent message_email_sent=email sent
message_email_with_error=emails with error message_email_with_error=emails with error
message_no_email=no email address defined message_no_email=no email address defined
message_email_not_sent=Error while sending emails message_email_not_sent=Error while sending emails
label_seating=Seating label_seating=Seating
label_attachments=Anh\u00e4nge label_attachments=Anh\u00e4nge
label_language=Language label_language=Language
label_subject=Subject label_subject=Subject
label_bytes=Bytes label_bytes=Bytes
label_upload=Hochladen label_upload=Hochladen
header_export=Export header_export=Export
label_export_type=Export Type label_export_type=Export Type
label_filtered=Filtered label_filtered=Filtered
label_include_deleted=Include deleted label_include_deleted=Include deleted
label_include_log=Include Logs label_include_log=Include Logs
label_template_booking_executed=Booking executed template label_template_booking_executed=Booking executed template
label_street=Street label_street=Street
label_zipCode=ZIP Code label_zipCode=ZIP Code
label_city=City label_city=City
label_groupName=Groupname label_groupName=Groupname
label_phoneNumber=Phone Number label_phoneNumber=Phone Number
label_template_waitlist_cancelled=Waitlist cancelled mail template label_template_waitlist_cancelled=Waitlist cancelled mail template
msgs_menu_status=Status msgs_menu_status=Status
menu_status=Status menu_status=Status
button_add=Add button_add=Add
passwords_different=Passwords do not match, please check input

View File

@ -1,56 +1,56 @@
[main] [main]
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager securityManager.cacheManager = $cacheManager
# DataSource Setup # DataSource Setup
datasource = org.apache.shiro.jndi.JndiObjectFactory datasource = org.apache.shiro.jndi.JndiObjectFactory
datasource.resourceName = java:/jboss/accountTestDs datasource.resourceName = java:/jboss/accountTestDs
# TODO - change to accountDs # TODO - change to accountDs
datasource.resourceRef = true datasource.resourceRef = true
# HashService # HashService
hashService = org.apache.shiro.crypto.hash.DefaultHashService hashService = org.apache.shiro.crypto.hash.DefaultHashService
hashService.hashIterations = 500000 hashService.hashIterations = 500000
hashService.hashAlgorithmName = SHA-512 hashService.hashAlgorithmName = SHA-512
hashService.generatePublicSalt = true hashService.generatePublicSalt = true
# Password service # Password service
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordService.hashService = $hashService passwordService.hashService = $hashService
# Required password matcher # Required password matcher
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordMatcher.passwordService = $passwordService passwordMatcher.passwordService = $passwordService
# JDBC Realm setup # JDBC Realm setup
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled=false jdbcRealm.permissionsLookupEnabled=false
jdbcRealm.authenticationQuery = select account_password from account where username = ? and status not in ('LOCKED','DELETED') jdbcRealm.authenticationQuery = select al.account_password from account a, account_login al where al.account = a.id and a.username = ? and status not in ('LOCKED','DELETED')
jdbcRealm.userRolesQuery = select r.role_name from application_role r, account_role ar, account a WHERE a.username = ? AND a.id = ar.account AND ar.account_role = r.id jdbcRealm.userRolesQuery = select r.role_name from application_role r, account_role ar, account a WHERE a.username = ? AND a.id = ar.account AND ar.account_role = r.id
jdbcRealm.credentialsMatcher = $passwordMatcher jdbcRealm.credentialsMatcher = $passwordMatcher
jdbcRealm.dataSource = $datasource jdbcRealm.dataSource = $datasource
# Activate realms # Activate realms
authcStrategy = org.apache.shiro.authc.pam.AllSuccessfulStrategy authcStrategy = org.apache.shiro.authc.pam.AllSuccessfulStrategy
securityManager.realms = $jdbcRealm securityManager.realms = $jdbcRealm
securityManager.authenticator.authenticationStrategy = $authcStrategy securityManager.authenticator.authenticationStrategy = $authcStrategy
# Setup authentication filter # Setup authentication filter
authc = de.muehlencord.shirofaces.filter.FacesAjaxAwarePassThruAuthenticationFilter authc = de.muehlencord.shirofaces.filter.FacesAjaxAwarePassThruAuthenticationFilter
authc.loginUrl = /login.xhtml authc.loginUrl = /login.xhtml
authc.successUrl = /web/account.xhtml authc.successUrl = /web/account.xhtml
roles.unauthorizedUrl = /error/accessDenied.xhtml roles.unauthorizedUrl = /error/accessDenied.xhtml
# #
# filter setup # filter setup
# #
[urls] [urls]
/public/**=anon /public/**=anon
/resources/**=anon /resources/**=anon
/fonts/**=anon /fonts/**=anon
/javax.faces.resource/**=anon /javax.faces.resource/**=anon
/login.xhtml=authc /login.xhtml=authc
/logout.xhtml=logout /logout.xhtml=logout
/**=authc /**=authc
# /web/**=authc # /web/**=authc

View File

@ -1,251 +1,314 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml" <ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" xmlns:p="http://primefaces.org/ui"
template="/resources/template/template.xhtml" template="/resources/template/template.xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:co="http://java.sun.com/jsf/composite/composite" xmlns:co="http://java.sun.com/jsf/composite/composite"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:composite="http://xmlns.jcp.org/jsf/composite/composite"> xmlns:o="http://omnifaces.org/ui"
xmlns:composite="http://xmlns.jcp.org/jsf/composite/composite">
<ui:define name="title">
Account Overview <ui:define name="title">
</ui:define> Account Overview
</ui:define>
<ui:define name="description">
for #{applicationView.currentApplication.applicationName} <ui:define name="description">
</ui:define> for #{applicationView.currentApplication.applicationName}
</ui:define>
<ui:define name="body">
<h:form id="accountForm"> <ui:define name="body">
<p:dataTable id="accountTable" value="#{accountView.accounts}" var="account" rowKey="#{account.username}" selectionMode="single" selection="#{accountView.currentAccount}" <h:form id="accountForm" prependId="false">
styleClass="box-primary"> <p:dataTable id="accountTable" value="#{accountView.accounts}" var="account" rowKey="#{account.username}" selectionMode="single" selection="#{accountView.currentAccount}"
<p:ajax event="rowSelect" update="deleteButton,editButton" listener="#{accountView.selectAccount}" /> styleClass="box-primary">
<p:ajax event="rowUnselect" update="deleteButton,editButton" listener="#{accountView.selectAccount}" /> <p:ajax event="rowSelect" update="buttonPanel" listener="#{accountView.selectAccount}" />
<p:column headerText="Username"> <p:ajax event="rowUnselect" update="buttonPanel" listener="#{accountView.unselectAccount}" />
<h:outputText value="#{account.username}" /> <p:column headerText="Username">
</p:column> <h:outputText value="#{account.username}" />
<p:column headerText="Lastname"> </p:column>
<h:outputText value="#{account.lastname}" /> <p:column headerText="Lastname">
</p:column> <h:outputText value="#{account.lastname}" />
<p:column headerText="Firstname"> </p:column>
<h:outputText value="#{account.firstname}" /> <p:column headerText="Firstname">
</p:column> <h:outputText value="#{account.firstname}" />
<p:column headerText="Email"> </p:column>
<h:outputText value="#{account.emailaddress}" /> <p:column headerText="Email">
</p:column> <h:outputText value="#{account.emailaddress}" />
<p:column headerText="Last login"> </p:column>
<h:outputText value="#{account.lastLogin}" /> <p:column headerText="Status">
</p:column> <h:outputText value="#{account.status}" />
<p:column headerText="Status"> </p:column>
<h:outputText value="#{account.status}" /> <p:column headerText="Can login" >
</p:column> <p:selectBooleanCheckbox id="canLogin" disabled="true" value="#{!empty account.accountLogin}" />
<p:column headerText="CreatedOn"> </p:column>
<h:outputText value="#{account.createdOn}" > <p:column headerText="CreatedOn">
<f:convertDateTime type="both" dateStyle="full" timeStyle="short" timeZone="Europe/Berlin"/> <h:outputText value="#{account.createdOn}" >
</h:outputText> <f:convertDateTime type="both" dateStyle="full" timeStyle="short" timeZone="Europe/Berlin"/>
</p:column> </h:outputText>
<p:column headerText="CreatedBy"> </p:column>
<h:outputText value="#{account.createdBy}" /> <p:column headerText="CreatedBy">
</p:column> <h:outputText value="#{account.createdBy}" />
<p:column headerText="LastUpdatedOn"> </p:column>
<h:outputText value="#{account.lastUpdatedOn}"> <p:column headerText="LastUpdatedOn">
<f:convertDateTime type="both" dateStyle="full" timeStyle="short" timeZone="Europe/Berlin"/> <h:outputText value="#{account.lastUpdatedOn}">
</h:outputText> <f:convertDateTime type="both" dateStyle="full" timeStyle="short" timeZone="Europe/Berlin"/>
</p:column> </h:outputText>
<p:column headerText="LastUpdatedBy"> </p:column>
<h:outputText value="#{account.lastUpdatedBy}" /> <p:column headerText="LastUpdatedBy">
</p:column> <h:outputText value="#{account.lastUpdatedBy}" />
<f:facet name="footer" > </p:column>
</p:dataTable>
<div class="col-sm-12 col-md-3" style="margin-top:10px">
<p:spacer height="10px" /> <p:spacer height="10px" />
<div class="ui-inputgroup" > <p:panel id="buttonPanel" styleClass="box-primary" style="margin-bottom:20px">
<h:outputLabel for="includeDisabledCheckbox" value="Include disabled accounts?" /> <div class="ui-g ui-fluid">
<p:inputSwitch id="includeDisabledCheckbox" value="#{accountView.showDisabledAccounts}" styleClass="btn-teal btn-block" > <div class="col-sm-12 col-md-4" style="margin-top:10px">
<p:ajax listener="#{accountView.showDisabledAccountsChange}" update="accountTable" /> <div class="ui-inputgroup" >
</p:inputSwitch> <h:outputLabel for="includeDisabledCheckbox" value="Include disabled accounts?" />
</div> <p:inputSwitch id="includeDisabledCheckbox" value="#{accountView.showDisabledAccounts}" styleClass="btn-teal btn-block" >
</div> <p:ajax listener="#{accountView.showDisabledAccountsChange}" update="accountTable" />
</p:inputSwitch>
<div class="col-sm-12 col-md-3"> </div>
<p:spacer height="10px" /> </div>
<p:commandButton value="New" id="newButton" icon="fa fa-plus"
update="editDialog" oncomplete="PF('editDialogVar').show();" <div class="col-sm-12 col-md-2">
actionListener="#{accountView.newAccount}" styleClass="btn-primary btn-block" /> <p:commandButton value="New" id="newButton" icon="fa fa-plus"
</div> update="editDialog" oncomplete="PF('editDialogVar').show();"
<div class="col-sm-12 col-md-3"> actionListener="#{accountView.newAccount}" styleClass="btn-primary btn-block" />
<p:spacer height="10px" /> </div>
<p:commandButton value="Edit" id="editButton" icon="fa fa-pencil" <div class="col-sm-12 col-md-2">
update="editDialog" oncomplete="PF('editDialogVar').show();" <p:commandButton value="Edit" id="editButton" icon="fa fa-pencil"
actionListener="#{accountView.editAccount}" disabled="#{!accountView.accountSelected}" styleClass="btn-teal btn-block" /> update="editDialog" oncomplete="PF('editDialogVar').show();"
</div> actionListener="#{accountView.editAccount}" disabled="#{!accountView.accountSelected}" styleClass="btn-teal btn-block" />
<div class="col-sm-12 col-md-3"> </div>
<p:spacer height="10px" /> <div class="col-sm-12 col-md-2">
<p:commandButton value="Delete" id="deleteButton" icon="fa fa-trash-o" <p:commandButton value="Delete" id="deleteButton" icon="fa fa-trash-o"
update=":accountForm:accountTable" action="#{accountView.deleteAccount}" disabled="#{!accountView.accountSelected}" styleClass="btn-danger btn-block"> update=":accountForm:accountTable" action="#{accountView.deleteAccount}" disabled="#{accountView.accountSelected eq false or accountView.currentLoggedInUser eq true}" styleClass="btn-danger btn-block">
<p:confirm header="Confirmation" message="Are you sure?" icon="fa fa-exclamation-triangle" /> <p:confirm header="Confirmation" message="Are you sure?" icon="fa fa-exclamation-triangle" />
</p:commandButton> </p:commandButton>
</div> </div>
</f:facet>
</p:dataTable> <div class="col-sm-12 col-md-2">
<c:if test="#{empty accountView.currentAccount.accountLogin}">
<composite:confirmationDialog /> <p:commandButton value="Add login" id="addLoginButton" icon="fa fa-plus" disabled="#{!accountView.accountSelected}"
</h:form> update="editLoginDialog" oncomplete="PF('editLoginDialogVar').show();"
action="#{accountView.addAccountLogin}" styleClass="btn-teal btn-block">
</p:commandButton>
<p:dialog id="editDialog" widgetVar="editDialogVar" header="Edit account" width="600" </c:if>
modal="true" appendTo="@(body)" showEffect="fade" hideEffect="fade" styleClass="box-solid box-primary" > <c:if test="#{!empty accountView.currentAccount.accountLogin}">
<h:form id="editDialogForm"> <p:splitButton value="Edit login" id="editLoginButton" icon="fa fa-pencil" disabled="#{!accountView.accountSelected}"
<p:messages id="editDialogMessages" showDetail="true" showIcon="true" showSummary="true"> update="editLoginDialog" oncomplete="PF('editLoginDialogVar').show();"
<p:autoUpdate /> action="#{accountView.editAccountLogin}" styleClass="btn-success btn-block">
</p:messages>
<p:menuitem value="Delete login" icon="fa fa-trash-o" disabled="#{accountView.currentLoggedInUser}"
<div class="ui-g ui-fluid"> update="accountTable,buttonPanel" styleClass="btn-danger btn-block"
<div class="col-sm-12 col-md-3"> action="#{accountView.deleteAccountLogin}" >
<p:outputLabel for="username" value="Username" />
</div> <p:confirm header="Confirmation" message="Are you sure?" icon="fa fa-exclamation-triangle" />
<div class="col-sm-12 col-md-6"> </p:menuitem>
<c:if test="#{accountView.currentAccount.createdBy != null}"> </p:splitButton>
<h:outputText id="username" value="#{accountView.currentAccount.username}" /> </c:if>
</c:if> </div>
<c:if test="#{accountView.currentAccount.createdBy == null}"> </div>
<p:inputText id="username" value="#{accountView.currentAccount.username}" /> </p:panel>
</c:if>
</div>
<div class="col-sm-12 col-md-3">
<p:message for="username"><p:autoUpdate /></p:message> <composite:confirmationDialog />
</div> </h:form>
<div class="col-sm-12 col-md-3">
<p:outputLabel for="lastname" value="Lastname" /> <p:dialog id="editDialog" widgetVar="editDialogVar" header="Edit account" width="600"
</div> modal="true" appendTo="@(body)" showEffect="fade" hideEffect="fade" styleClass="box-solid box-primary" >
<div class="col-sm-12 col-md-6"> <h:form id="editDialogForm">
<p:inputText id="lastname" value="#{accountView.currentAccount.lastname}" size="40" maxlength="100"/> <p:messages id="editDialogMessages" showDetail="true" showIcon="true" showSummary="true">
</div> <p:autoUpdate />
<div class="col-sm-12 col-md-3 "> </p:messages>
<p:message for="lastname"> <p:autoUpdate /></p:message>
</div> <div class="ui-g ui-fluid">
<div class="col-sm-12 col-md-3">
<div class="col-sm-12 col-md-3"> <p:outputLabel for="username" value="Username" />
<p:outputLabel for="firstname" value="Firstname" /> </div>
</div> <div class="col-sm-12 col-md-6">
<div class="col-sm-12 col-md-6"> <c:if test="#{accountView.currentAccount.createdBy != null}">
<p:inputText id="firstname" value="#{accountView.currentAccount.firstname}" size="40" maxlength="100" /> <h:outputText id="username" value="#{accountView.currentAccount.username}" />
</div> </c:if>
<div class="col-sm-12 col-md-3"> <c:if test="#{accountView.currentAccount.createdBy == null}">
<p:message for="firstname"> <p:autoUpdate /></p:message> <p:inputText id="username" value="#{accountView.currentAccount.username}" />
</div> </c:if>
</div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:outputLabel for="emailaddress" value="emailaddress" /> <p:message for="username"><p:autoUpdate /></p:message>
</div> </div>
<div class="col-sm-12 col-md-6">
<p:inputText id="emailaddress" value="#{accountView.currentAccount.emailaddress}" size="40" maxlength="200"> <div class="col-sm-12 col-md-3">
<f:validator validatorId="de.muehlencord.shared.jeeutil.validator.EmailValidator" /> <p:outputLabel for="lastname" value="Lastname" />
</p:inputText> </div>
</div> <div class="col-sm-12 col-md-6">
<div class="col-sm-12 col-md-3"> <p:inputText id="lastname" value="#{accountView.currentAccount.lastname}" size="40" maxlength="100"/>
<p:message for="emailaddress"> <p:autoUpdate /></p:message> </div>
</div> <div class="col-sm-12 col-md-3 ">
<p:message for="lastname"> <p:autoUpdate /></p:message>
<c:if test="#{accountView.currentAccount.username != null}"> </div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:outputLabel for="status" value="Status" /> <p:outputLabel for="firstname" value="Firstname" />
</div> </div>
<div class="col-sm-12 col-md-6"> <div class="col-sm-12 col-md-6">
<p:selectOneMenu id="status" value="#{accountView.currentAccount.status}" > <p:inputText id="firstname" value="#{accountView.currentAccount.firstname}" size="40" maxlength="100" />
<f:selectItems value="#{accountView.statusList}" /> </div>
</p:selectOneMenu> <div class="col-sm-12 col-md-3">
</div> <p:message for="firstname"> <p:autoUpdate /></p:message>
<div class="col-sm-12 col-md-3"> </div>
<p:message for="status" />
</div> <div class="col-sm-12 col-md-3">
<p:outputLabel for="emailaddress" value="emailaddress" />
<div class="col-sm-12 col-md-3"> </div>
<p:outputLabel for="lastlogin" value="Lastlogin" /> <div class="col-sm-12 col-md-6">
</div> <p:inputText id="emailaddress" value="#{accountView.currentAccount.emailaddress}" size="40" maxlength="200">
<div class="col-sm-12 col-md-3"> <f:validator validatorId="de.muehlencord.shared.jeeutil.validator.EmailValidator" />
<h:outputText id="lastlogin" value="#{accountView.currentAccount.lastLogin}" /> </p:inputText>
</div> </div>
<div class="col-sm-12 col-md-6"> <div class="col-sm-12 col-md-3">
<p:message for="lastlogin" /> <p:message for="emailaddress"> <p:autoUpdate /></p:message>
</div> </div>
<div class="col-sm-12 col-md-3"> <c:if test="#{accountView.currentAccount.username != null}">
<p:outputLabel for="createdon" value="Created on" />
</div> <div class="col-sm-12 col-md-3">
<div class="col-sm-12 col-md-6"> <p:outputLabel for="status" value="Status" />
<h:outputText id="createdon" value="#{accountView.currentAccount.createdOn}" /> </div>
</div> <div class="col-sm-12 col-md-6">
<div class="col-sm-12 col-md-3"> <p:selectOneMenu id="status" value="#{accountView.currentAccount.status}" >
<p:message for="createdon" /> <f:selectItems value="#{accountView.statusList}" />
</div> </p:selectOneMenu>
</div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:outputLabel for="createdby" value="Created by" /> <p:message for="status" />
</div> </div>
<div class="col-sm-12 col-md-6">
<h:outputText id="createdby" value="#{accountView.currentAccount.createdBy}" /> <div class="col-sm-12 col-md-3">
</div> <p:outputLabel for="createdon" value="Created on" />
<div class="col-sm-12 col-md-3"> </div>
<p:message for="createdby" /> <div class="col-sm-12 col-md-6">
</div> <h:outputText id="createdon" value="#{accountView.currentAccount.createdOn}" />
</div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:outputLabel for="lastupdatedon" value="Last updated on" /> <p:message for="createdon" />
</div> </div>
<div class="col-sm-12 col-md-6">
<h:outputText id="lastupdatedon" value="#{accountView.currentAccount.lastUpdatedOn}" /> <div class="col-sm-12 col-md-3">
</div> <p:outputLabel for="createdby" value="Created by" />
<div class="col-sm-12 col-md-3"> </div>
<p:message for="lastupdatedon" /> <div class="col-sm-12 col-md-6">
</div> <h:outputText id="createdby" value="#{accountView.currentAccount.createdBy}" />
</div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:outputLabel for="lastupdatedby" value="Last updated by" /> <p:message for="createdby" />
</div> </div>
<div class="col-sm-12 col-md-6">
<h:outputText id="lastupdatedby" value="#{accountView.currentAccount.lastUpdatedBy}" /> <div class="col-sm-12 col-md-3">
</div> <p:outputLabel for="lastupdatedon" value="Last updated on" />
<div class="col-sm-12 col-md-3"> </div>
<p:message for="lastupdatedby" /> <div class="col-sm-12 col-md-6">
</div> <h:outputText id="lastupdatedon" value="#{accountView.currentAccount.lastUpdatedOn}" />
</c:if> </div>
<div class="col-sm-12 col-md-3">
<p:message for="lastupdatedon" />
<div class="col-sm-12 col-md-3"> </div>
<p:outputLabel for="roles" value="Roles" />
</div> <div class="col-sm-12 col-md-3">
<div class="col-sm-12 col-md-6"> <p:outputLabel for="lastupdatedby" value="Last updated by" />
<p:selectManyMenu id="roles" var="role" label="#{role.roleName}" value="#{accountView.currentAccountRoles}" converter="omnifaces.SelectItemsConverter" required="false" > </div>
<f:selectItems value="#{accountView.allApplicationRoles}" var="roleItem" itemValue="#{roleItem}" /> <div class="col-sm-12 col-md-6">
<p:column> <h:outputText id="lastupdatedby" value="#{accountView.currentAccount.lastUpdatedBy}" />
<h:outputText value="#{role.application.applicationName}-#{role.roleName}"/> </div>
</p:column> <div class="col-sm-12 col-md-3">
</p:selectManyMenu> <p:message for="lastupdatedby" />
</div> </div>
<div class="col-sm-12 col-md-3"> </c:if>
<p:message for="roles" />
</div>
<div class="col-sm-12 col-md-3">
<p:outputLabel for="roles" value="Roles" />
<div class="col-sm-12 col-md-6"> </div>
<p:spacer height="10px" /> <div class="col-sm-12 col-md-6">
<p:commandButton value="Save" action="#{accountView.saveEditAccount}" styleClass="btn-primary btn-block" <p:selectManyMenu id="roles" var="role" label="#{role.roleName}" value="#{accountView.currentAccountRoles}" converter="omnifaces.SelectItemsConverter" required="false" >
oncomplete="if (args &amp;&amp; !args.validationFailed) PF('editDialogVar').hide();" update=":accountForm:accountTable" /> <f:selectItems value="#{accountView.allApplicationRoles}" var="roleItem" itemValue="#{roleItem}" />
</div> <p:column>
<div class="col-sm-12 col-md-6"> <h:outputText value="#{role.application.applicationName}-#{role.roleName}"/>
<p:spacer height="10px" /> </p:column>
<p:commandButton value="Cancel" action="#{accountView.cancelEditAccount}" immediate="true" styleClass="btn-teal btn-block" </p:selectManyMenu>
oncomplete="PF('editDialogVar').hide();" /> </div>
</div> <div class="col-sm-12 col-md-3">
</div> <p:message for="roles" />
</h:form> </div>
</p:dialog>
</ui:define> <div class="col-sm-12 col-md-6">
<p:spacer height="10px" />
<p:commandButton value="Save" action="#{accountView.saveEditAccount}" styleClass="btn-primary btn-block"
oncomplete="if (args &amp;&amp; !args.validationFailed) PF('editDialogVar').hide();" update=":accountForm:accountTable" />
</div>
<div class="col-sm-12 col-md-6">
<p:spacer height="10px" />
<p:commandButton value="Cancel" action="#{accountView.cancelEditAccount}" immediate="true" styleClass="btn-teal btn-block"
oncomplete="PF('editDialogVar').hide();" />
</div>
</div>
</h:form>
</p:dialog>
<p:dialog id="editLoginDialog" widgetVar="editLoginDialogVar" header="Edit account login" width="600"
modal="true" appendTo="@(body)" showEffect="fade" hideEffect="fade" styleClass="box-solid box-primary" >
<h:form id="editLoginDialogForm">
<p:messages id="editLoginDialogMessages" showDetail="true" showIcon="true" showSummary="true">
<p:autoUpdate />
</p:messages>
<div class="ui-g ui-fluid">
<o:validateMultiple id="myId" components="password repeatPassword"
validator="#{accountView.validatePasswords}" message="#{msgs.passwords_different}" />
<div class="col-sm-12">
<p:outputLabel value="Enter a new password or keep values empty to keep existing / autogenrated value" />
</div>
<div class="col-sm-12 col-md-3">
<p:outputLabel for="password" value="Password" />
</div>
<div class="col-sm-12 col-md-6">
<p:password id="password" value="#{accountView.password}" maxlength="32" size="32" required="false"/>
</div>
<div class="col-sm-12 col-md-3">
<p:message for="password" />
</div>
<div class="col-sm-12 col-md-3">
<p:outputLabel for="repeatPassword" value="repeat Password" />
</div>
<div class="col-sm-12 col-md-6">
<p:password id="repeatPassword" value="#{accountView.repeatPassword}" maxlength="32" size="32" required="false"/>
</div>
<div class="col-sm-12 col-md-3">
<p:message for="repeatPassword" />
</div>
<div class="col-sm-12 col-md-6">
<p:spacer height="10px" />
<p:commandButton value="Save" action="#{accountView.saveEditAccountLogin}" styleClass="btn-primary btn-block"
oncomplete="if (args &amp;&amp; !args.validationFailed) PF('editLoginDialogVar').hide();" update=":accountForm:accountTable,:accountForm:buttonPanel" />
</div>
<div class="col-sm-12 col-md-6">
<p:spacer height="10px" />
<p:commandButton value="Cancel" action="#{accountView.cancelEditAccountLogin}" immediate="true" styleClass="btn-teal btn-block"
oncomplete="PF('editLoginDialogVar').hide();" />
</div>
</div>
</h:form>
</p:dialog>
</ui:define>
</ui:composition> </ui:composition>

View File

@ -1,84 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml" <ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" xmlns:p="http://primefaces.org/ui"
template="/resources/template/template.xhtml" template="/resources/template/template.xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:co="http://java.sun.com/jsf/composite/composite" xmlns:co="http://java.sun.com/jsf/composite/composite"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:composite="http://xmlns.jcp.org/jsf/composite/composite"> xmlns:composite="http://xmlns.jcp.org/jsf/composite/composite">
<ui:define name="title"> <ui:define name="title">
Applications Applications
</ui:define> </ui:define>
<ui:define name="body" > <ui:define name="body" >
<h:form id="applicationForm"> <h:form id="applicationForm" prependId="false">
<p:panel styleClass="box-solid"> <p:panel styleClass="box-solid">
<div class="ui-g ui-fluid"> <div class="ui-g ui-fluid">
<div class="col-sm-12 col-md-6"> <div class="col-sm-12 col-md-6">
<p:selectOneMenu id="applicationSelect" value="#{applicationView.currentApplication}" converter="omnifaces.SelectItemsConverter" required="true"> <p:selectOneMenu id="applicationSelect" value="#{applicationView.currentApplication}" converter="omnifaces.SelectItemsConverter" required="true">
<f:selectItems value="#{applicationView.allApplications}" var="app" itemLabel="#{app.applicationName}" itemValue="#{app}" /> <f:selectItems value="#{applicationView.allApplications}" var="app" itemLabel="#{app.applicationName}" itemValue="#{app}" />
</p:selectOneMenu> </p:selectOneMenu>
</div> </div>
<div class="col-sm-12 col-md-2"> <div class="col-sm-12 col-md-2">
<p:commandButton value="Select" styleClass="btn-primary btn-solid}" actionListener="#{applicationView.selectApplication}" /> <p:commandButton value="Select" styleClass="btn-primary btn-solid}" actionListener="#{applicationView.selectApplication}" />
</div> </div>
<div class="col-sm-12 col-md-2"> <div class="col-sm-12 col-md-2">
<p:commandButton value="New" id="newButton" icon="fa fa-plus" <p:commandButton value="New" id="newButton" icon="fa fa-plus"
update="editDialog" oncomplete="PF('editDialogVar').show();" update="editDialog" oncomplete="PF('editDialogVar').show();"
actionListener="#{applicationView.newApplication}" styleClass="btn-teal btn-block" /> actionListener="#{applicationView.newApplication}" styleClass="btn-teal btn-block" />
</div> </div>
<div class="col-sm-12 col-md-2"> <div class="col-sm-12 col-md-2">
<p:commandButton id="deletePermissionButton" icon="fa fa-trash-o" value="#{msgs.button_delete}" actionListener="#{applicationView.deleteApplication}" <p:commandButton id="deletePermissionButton" icon="fa fa-trash-o" value="#{msgs.button_delete}" actionListener="#{applicationView.deleteApplication}"
update="applicationSelect" styleClass="btn-danger btn-block" > update="applicationSelect" styleClass="btn-danger btn-block" >
<p:confirm header="Confirmation" message="Are you sure?" icon="fa fa-exclamation-triangle" /> <p:confirm header="Confirmation" message="Are you sure?" icon="fa fa-exclamation-triangle" />
</p:commandButton> </p:commandButton>
</div> </div>
</div> </div>
</p:panel> </p:panel>
<composite:confirmationDialog /> <composite:confirmationDialog />
</h:form> </h:form>
<p:dialog id="editDialog" widgetVar="editDialogVar" header="Edit account" width="600" <p:dialog id="editDialog" widgetVar="editDialogVar" header="Edit account" width="600"
modal="true" appendTo="@(body)" showEffect="fade" hideEffect="fade" styleClass="box-solid box-primary" > modal="true" appendTo="@(body)" showEffect="fade" hideEffect="fade" styleClass="box-solid box-primary" >
<h:form id="editDialogForm"> <h:form id="editDialogForm">
<p:messages id="editDialogMessages" showDetail="true" showIcon="true" showSummary="true"> <p:messages id="editDialogMessages" showDetail="true" showIcon="true" showSummary="true">
<p:autoUpdate /> <p:autoUpdate />
</p:messages> </p:messages>
<div class="ui-g ui-fluid"> <div class="ui-g ui-fluid">
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:outputLabel for="applicationName" value="Application name" /> <p:outputLabel for="applicationName" value="Application name" />
</div> </div>
<div class="col-sm-12 col-md-6"> <div class="col-sm-12 col-md-6">
<p:inputText id="applicationName" value="#{applicationView.editApplication.applicationName}"> <p:inputText id="applicationName" value="#{applicationView.editApplication.applicationName}">
<f:validator validatorId="uniqueApplicationValidator"/> <f:validator validatorId="uniqueApplicationValidator"/>
</p:inputText> </p:inputText>
</div> </div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:message for="applicationName"><p:autoUpdate /></p:message> <p:message for="applicationName"><p:autoUpdate /></p:message>
</div> </div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:spacer height="10px" /> <p:spacer height="10px" />
<p:commandButton value="Save" action="#{applicationView.saveEditApplication}" styleClass="btn-primary btn-block" <p:commandButton value="Save" action="#{applicationView.saveEditApplication}" styleClass="btn-primary btn-block"
oncomplete="if (args &amp;&amp; !args.validationFailed) PF('editDialogVar').hide();" update=":applicationForm" /> oncomplete="if (args &amp;&amp; !args.validationFailed) PF('editDialogVar').hide();" update=":applicationForm" />
</div> </div>
<div class="col-sm-12 col-md-3"> <div class="col-sm-12 col-md-3">
<p:spacer height="10px" /> <p:spacer height="10px" />
<p:commandButton value="Cancel" action="#{applicationView.cancelEditApplication}" immediate="true" styleClass="btn-teal btn-block" <p:commandButton value="Cancel" action="#{applicationView.cancelEditApplication}" immediate="true" styleClass="btn-teal btn-block"
oncomplete="PF('editDialogVar').hide();" /> oncomplete="PF('editDialogVar').hide();" />
</div> </div>
</div> </div>
</h:form> </h:form>
</p:dialog> </p:dialog>
</ui:define> </ui:define>
</ui:composition> </ui:composition>

View File

@ -65,7 +65,13 @@
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId> <artifactId>jcl-over-slf4j</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>de.muehlencord.shared</groupId>
<artifactId>shared-util</artifactId>
<version>1.1-SNAPSHOT</version>
<type>jar</type>
</dependency>
<dependency> <dependency>
<groupId>javax</groupId> <groupId>javax</groupId>
<artifactId>javaee-api</artifactId> <artifactId>javaee-api</artifactId>

View File

@ -1,18 +1,32 @@
DELETE FROM config;
DELETE FROM account_role;
DELETE FROM account_login;
DELETE FROM account;
DELETE FROM role_permission;
DELETE FROM application_role;
DELETE FROM application_permission;
DELETE FROM application;
-- application configuration INSERT INTO application (id, application_name) values ('143a2bd3-7e0b-4162-a76e-3031331c7dfe', 'Account UI');
INSERT INTO application_permission (id, permission_name, permission_description) values ('dfd0f8f1-4a51-4fdc-9a1c-a942bee9b649', 'test:view', 'Display test view');
INSERT INTO application_role (id, role_name, role_description) values ('5cd0aca0-5466-483d-8f3e-c369f8061131','Admin', 'Admin role');
INSERT INTO application_role (id, role_name, role_description) values ('da30060e-fd23-4016-a506-4e12e9322148', 'User', 'Standard user role');
-- account -- permissions not used in Account UI
INSERT INTO account (id, username, firstname, lastname, emailaddress, account_password, created_by, last_updated_by) values ('2a712ed4-30f8-47b4-a002-7d87441b7013', 'system', 'system', 'system', 'n/a', 'n/a', 'system', 'system'); -- INSERT INTO application_permission (id, permission_name, permission_description) values ('dfd0f8f1-4a51-4fdc-9a1c-a942bee9b649', 'test:view', 'Display test view');
INSERT INTO account (id, username, emailaddress, firstname, lastname, account_password, created_by, last_updated_by) values('ab5c8337-6872-4aea-a9b9-78ea63706b8f','admin', 'joern@muehlencord.de', 'Joern', 'Muehlencord','$shiro1$SHA-256$500000$4bHPNH9k539UjdFLgm/HOA==$T/n8skgoGSOtNw/c9ScDlXCiGrx2cZF0Esrvf6WPq6g=', 'admin','admin'); --admin/secret
-- add roles to Account UI application
INSERT INTO application_role (id, application, role_name, role_description) values ('5cd0aca0-5466-483d-8f3e-c369f8061131','143a2bd3-7e0b-4162-a76e-3031331c7dfe', 'Admin', 'Admin role');
INSERT INTO application_role (id, application, role_name, role_description) values ('da30060e-fd23-4016-a506-4e12e9322148','143a2bd3-7e0b-4162-a76e-3031331c7dfe', 'User', 'Standard user role');
-- create accounts
INSERT INTO account (id, username, firstname, lastname, emailaddress, created_by, last_updated_by) values ('2a712ed4-30f8-47b4-a002-7d87441b7013', 'system', 'system', 'system', 'n/a', 'system', 'system');
INSERT INTO account (id, username, emailaddress, firstname, lastname, created_by, last_updated_by) values('ab5c8337-6872-4aea-a9b9-78ea63706b8f','admin', 'joern@muehlencord.de', 'Joern', 'Muehlencord','system','system'); --admin/secret
-- assign AccountUI.Admin role to admin user
INSERT INTO account_role (account, account_role) values ('ab5c8337-6872-4aea-a9b9-78ea63706b8f', '5cd0aca0-5466-483d-8f3e-c369f8061131'); INSERT INTO account_role (account, account_role) values ('ab5c8337-6872-4aea-a9b9-78ea63706b8f', '5cd0aca0-5466-483d-8f3e-c369f8061131');
-- create login for user admin (login admin, password secret)
INSERT INTO account_login (account, account_password, created_by, last_updated_by) VALUES ('ab5c8337-6872-4aea-a9b9-78ea63706b8f', '$shiro1$SHA-256$500000$4bHPNH9k539UjdFLgm/HOA==$T/n8skgoGSOtNw/c9ScDlXCiGrx2cZF0Esrvf6WPq6g=', 'system', 'system');
-- config -- config
INSERT INTO config (config_key, config_key_account, config_value) VALUES ('account.maxFailedLogins', '2a712ed4-30f8-47b4-a002-7d87441b7013', '5'); INSERT INTO config (application, config_key, config_key_account, config_value) VALUES ('143a2bd3-7e0b-4162-a76e-3031331c7dfe', 'account.maxFailedLogins', '2a712ed4-30f8-47b4-a002-7d87441b7013', '5');

View File

@ -1,314 +1,376 @@
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.AccountLoginEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity;
import de.muehlencord.shared.account.business.config.entity.ConfigException; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import de.muehlencord.shared.account.util.SecurityUtil; import de.muehlencord.shared.account.util.SecurityUtil;
import java.io.Serializable; import de.muehlencord.shared.util.DateUtil;
import java.util.ArrayList; import java.io.Serializable;
import java.util.Date; import java.util.ArrayList;
import java.util.List; import java.util.Date;
import javax.ejb.EJB; import java.util.List;
import javax.ejb.Stateless; import javax.ejb.EJB;
import javax.inject.Inject; import javax.ejb.Stateless;
import javax.persistence.EntityManager; import javax.inject.Inject;
import javax.persistence.NoResultException; import javax.persistence.EntityManager;
import javax.persistence.Query; import javax.persistence.NoResultException;
import javax.transaction.Transactional; import javax.persistence.Query;
import org.apache.commons.lang3.RandomStringUtils; import javax.transaction.Transactional;
import org.slf4j.Logger; import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.apache.shiro.SecurityUtils; import org.slf4j.LoggerFactory;
import org.apache.shiro.subject.Subject; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
/**
* /**
* @author joern.muehlencord *
*/ * @author joern.muehlencord
@Stateless */
public class AccountControl implements Serializable { @Stateless
public class AccountControl implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountControl.class.getName());
private static final long serialVersionUID = 3424816272598108101L; private static final Logger LOGGER = LoggerFactory.getLogger(AccountControl.class.getName());
private static final long serialVersionUID = 3424816272598108101L;
@EJB
private ConfigService configService; @EJB
private ConfigService configService;
@EJB
private MailService mailService; @EJB
private MailService mailService;
@Inject
EntityManager em; @Inject
private ApplicationEntity application;
/**
* returns a list of active accounts @Inject
* EntityManager em;
* @return a list of active accounts
*/ /**
public List<AccountEntity> getActiveAccounts() { * returns a list of active accounts
Query query = em.createQuery("SELECT a FROM AccountEntity a WHERE a.status <> :status", AccountEntity.class); *
query.setParameter("status", AccountStatus.DISABLED.name()); * @return a list of active accounts
return query.getResultList(); */
} public List<AccountEntity> getActiveAccounts() {
Query query = em.createQuery("SELECT a FROM AccountEntity a WHERE a.status <> :status", AccountEntity.class);
/** query.setParameter("status", AccountStatus.DISABLED.name());
* returns a list of active accounts return query.getResultList();
* }
* @return a list of active accounts
*/ /**
public List<AccountEntity> getAllAccounts() { * returns a list of active accounts
Query query = em.createNamedQuery("AccountEntity.findAll"); *
return query.getResultList(); * @return a list of active accounts
} */
public List<AccountEntity> getAllAccounts() {
public List<AccountEntity> getAccounts(boolean includeDisabled) { Query query = em.createNamedQuery("AccountEntity.findAll");
if (includeDisabled) { return query.getResultList();
return getAllAccounts(); }
} else {
return getActiveAccounts(); public List<AccountEntity> getAccounts(boolean includeDisabled) {
} if (includeDisabled) {
} return getAllAccounts();
} else {
public AccountEntity getAccountEntity(String userName, boolean loadRoles) { return getActiveAccounts();
StringBuilder queryBuilder = new StringBuilder(); }
queryBuilder.append("SELECT a FROM AccountEntity a "); }
if (loadRoles) {
queryBuilder.append("LEFT JOIN FETCH a.applicationRoleList "); public AccountEntity getAccountEntity(String userName, boolean loadRoles) {
} StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("WHERE a.username = :username"); queryBuilder.append("SELECT a FROM AccountEntity a ");
Query query = em.createQuery(queryBuilder.toString()); if (loadRoles) {
query.setParameter("username", userName); queryBuilder.append("LEFT JOIN FETCH a.applicationRoleList ");
try { }
return (AccountEntity) query.getSingleResult(); queryBuilder.append("WHERE a.username = :username");
} catch (NoResultException ex) { Query query = em.createQuery(queryBuilder.toString());
return null; query.setParameter("username", userName);
} try {
} return (AccountEntity) query.getSingleResult();
} catch (NoResultException ex) {
@Transactional return null;
public AccountEntity saveAccount(ApplicationEntity application, AccountEntity account, List<ApplicationRoleEntity> applicationRoles) { }
Date now = new Date(); // Todo now in UTC }
Subject currentUser = SecurityUtils.getSubject();
String currentLoggedInUser = currentUser.getPrincipal().toString(); @Transactional
public AccountEntity saveAccount(AccountEntity account, List<ApplicationRoleEntity> applicationRoles) {
account.setLastUpdatedBy(currentLoggedInUser); Date now = DateUtil.getCurrentTimeInUTC();
account.setLastUpdatedOn(now); Subject currentUser = SecurityUtils.getSubject();
String currentLoggedInUser = currentUser.getPrincipal().toString();
boolean newAccount = (account.getCreatedOn() == null);
account.setLastUpdatedBy(currentLoggedInUser);
// new account account.setLastUpdatedOn(now);
if (newAccount) {
account.setCreatedOn(now); boolean newAccount = (account.getCreatedOn() == null);
account.setCreatedBy(currentLoggedInUser);
// new account
// set default random password, user has to get password via lost passwort option afterwards if (newAccount) {
String randomPassword = RandomStringUtils.random(20, true, true); account.setCreatedOn(now);
String hashedPassword = SecurityUtil.createPassword(randomPassword); account.setCreatedBy(currentLoggedInUser);
account.setAccountPassword(hashedPassword); em.persist(account);
em.persist(account); } else {
} else { em.merge(account);
em.merge(account);
// reload account from db and join roles
// reload account from db and join roles account = getAccountEntity(account.getUsername(), true);
account = getAccountEntity(account.getUsername(), true); }
}
// assign roles to account
// assign roles to account if (account.getApplicationRoleList() == null) {
if (account.getApplicationRoleList() == null) { account.setApplicationRoleList(new ArrayList<>());
account.setApplicationRoleList(new ArrayList<>()); }
}
boolean roleSetupChanged = false;
boolean roleSetupChanged = false; // remove roles which are no longer listed
// remove roles which are no longer listed // ensure this is only done for the given application - keep the other applications untouched
// ensure this is only done for the given application - keep the other applications untouched List<ApplicationRoleEntity> assignedRoles = new ArrayList<>();
List<ApplicationRoleEntity> assignedRoles = new ArrayList<>(); assignedRoles.addAll(account.getApplicationRoleList());
assignedRoles.addAll(account.getApplicationRoleList()); for (ApplicationRoleEntity currentlyAssignedRole : assignedRoles) {
for (ApplicationRoleEntity currentlyAssignedRole : assignedRoles) { if ((currentlyAssignedRole.getApplication().equals(application) && (!applicationRoles.contains(currentlyAssignedRole)))) {
if ((currentlyAssignedRole.getApplication().equals(application) && (!applicationRoles.contains(currentlyAssignedRole)))) { account.getApplicationRoleList().remove(currentlyAssignedRole);
account.getApplicationRoleList().remove(currentlyAssignedRole); roleSetupChanged = true;
roleSetupChanged = true; if (LOGGER.isDebugEnabled()) {
if (LOGGER.isDebugEnabled()) { LOGGER.debug("Removed role {} ({}) from user {}", currentlyAssignedRole.getRoleName(), application.getApplicationName(), account.getUsername());
LOGGER.debug("Removed role {} ({}) from user {}", currentlyAssignedRole.getRoleName(), application.getApplicationName(), account.getUsername()); }
} }
} }
}
// add newly added roles to role list
// add newly added roles to role list for (ApplicationRoleEntity applicationRole : applicationRoles) {
for (ApplicationRoleEntity applicationRole : applicationRoles) { if (!account.getApplicationRoleList().contains(applicationRole)) {
if (!account.getApplicationRoleList().contains(applicationRole)) { account.addApplicationRole(applicationRole);
account.addApplicationRole(applicationRole); roleSetupChanged = true;
roleSetupChanged = true; if (LOGGER.isDebugEnabled()) {
if (LOGGER.isDebugEnabled()) { LOGGER.debug("Added role {} ({}) to account {}", applicationRole.getRoleName(), application.getApplicationName(), account.getUsername());
LOGGER.debug("Added role {} ({}) to account {}", applicationRole.getRoleName(), application.getApplicationName(), account.getUsername()); }
} }
} }
}
// update account in database if roles changed
// update account in database if roles changed if (roleSetupChanged) {
if (roleSetupChanged) { em.merge(account);
em.merge(account); }
} return account;
return account; }
}
@Transactional
@Transactional public void deleteAccount(AccountEntity account) throws AccountException {
public void deleteAccount(AccountEntity account) throws AccountException { Date now = new Date(); // Todo now in UTC
Date now = new Date(); // Todo now in UTC Subject currentUser = SecurityUtils.getSubject();
Subject currentUser = SecurityUtils.getSubject(); String currentUserName = currentUser.getPrincipal().toString();
String currentUserName = currentUser.getPrincipal().toString();
if (account.getUsername().equals(currentUserName)) {
if (account.getUsername().equals(currentUserName)) { throw new AccountException("Cannot delete own account");
throw new AccountException("Cannot delete own account"); } else {
} else { account.setStatus(AccountStatus.DISABLED.name());
account.setStatus(AccountStatus.DISABLED.name()); account.setLastUpdatedBy(currentUserName);
account.setLastUpdatedBy(currentUserName); account.setLastUpdatedOn(now);
account.setLastUpdatedOn(now); em.merge(account);
em.merge(account); }
}
}
}
public boolean initPasswordReset(String userName) {
public boolean initPasswordReset(String userName) { try {
try { AccountEntity account = getAccountEntity(userName, false);
AccountEntity account = getAccountEntity(userName, false); if (account == null) {
if (account == null) { LOGGER.warn("Account with name " + userName + " not found");
LOGGER.warn("Account with name " + userName + " not found"); return false;
return false; }
}
if (account.getStatus().equals(AccountStatus.BLOCKED.name())) {
if (account.getStatus().equals(AccountStatus.BLOCKED.name())) { LOGGER.warn("Account " + userName + " is locked, cannot initialize password reset");
LOGGER.warn("Account " + userName + " is locked, cannot initialize password reset"); return false;
return false; }
}
String randomString = RandomStringUtils.random(40, true, true);
String randomString = RandomStringUtils.random(40, true, true);
Date validTo = new Date(); // TODO now in UTC
Date validTo = new Date(); // TODO now in UTC validTo = new Date(validTo.getTime() + 1000 * 600); // 10 minutes to react
validTo = new Date(validTo.getTime() + 1000 * 600); // 10 minutes to react
// TODO rework password reset
account.setPasswordResetHash(randomString); // account.setPasswordResetHash(randomString);
account.setPasswordResetOngoing(true); // account.setPasswordResetOngoing(true);
account.setPasswordResetValidTo(validTo); // account.setPasswordResetValidTo(validTo);
mailService.sendPasswortResetStartEmail(account, randomString);
mailService.sendPasswortResetStartEmail(account, randomString);
em.merge(account);
em.merge(account); return true;
return true; } catch (MailException ex) {
} catch (MailException ex) { LOGGER.error("Error while sending password reset mail. " + ex.toString());
LOGGER.error("Error while sending password reset mail. " + ex.toString()); if (LOGGER.isDebugEnabled()) {
if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error while sending password reset mail.", ex);
LOGGER.debug("Error while sending password reset mail.", ex); }
} return false;
return false; }
} }
}
public boolean resetPassword(String userName, String newPassword, String resetPasswordToken) {
public boolean resetPassword(String userName, String newPassword, String resetPasswordToken) { AccountEntity account = getAccountEntity(userName, false);
AccountEntity account = getAccountEntity(userName, false);
if (account == null) {
if (account == null) { LOGGER.warn("Error while resetting password, no account with username " + userName + " found");
LOGGER.warn("Error while resetting password, no account with username " + userName + " found"); // TODO add extra logging for intrusion protection system like fail2ban
// TODO add extra logging for intrusion protection system like fail2ban return false;
return false; }
}
/*
if (account.getPasswordResetOngoing() && (account.getPasswordResetHash() != null) && (account.getPasswordResetValidTo() != null)) { if (account.getPasswordResetOngoing() && (account.getPasswordResetHash() != null) && (account.getPasswordResetValidTo() != null)) {
Date now = new Date(); // TODO now in UTC Date now = new Date(); // TODO now in UTC
String storedHash = account.getPasswordResetHash().trim(); String storedHash = account.getPasswordResetHash().trim();
if (account.getPasswordResetValidTo().after(now)) { if (account.getPasswordResetValidTo().after(now)) {
if (storedHash.equals(resetPasswordToken)) { if (storedHash.equals(resetPasswordToken)) {
// everything ok, reset password // everything ok, reset password
executePasswordReset(account, newPassword); executePasswordReset(account, newPassword);
LOGGER.info("Updated password for user " + userName); LOGGER.info("Updated password for user " + userName);
return true; return true;
} else { } else {
// token is not valid, refuse to change password // token is not valid, refuse to change password
LOGGER.warn("Trying to reset password for user " + userName + " but wrong token " + resetPasswordToken + " provided"); LOGGER.warn("Trying to reset password for user " + userName + " but wrong token " + resetPasswordToken + " provided");
addLoginError(account); addLoginError(account);
return false; return false;
} }
} else { } else {
// password reset token no longer valid // password reset token no longer valid
LOGGER.warn("Trying to reset password for user " + userName + " but token is no longer valid"); LOGGER.warn("Trying to reset password for user " + userName + " but token is no longer valid");
addLoginError(account); addLoginError(account);
return false; return false;
} }
} else { } else {
// user is not is password reset mode // user is not is password reset mode
LOGGER.warn("Trying to reset password for user " + userName + " but password reset was not requested"); LOGGER.warn("Trying to reset password for user " + userName + " but password reset was not requested");
addLoginError(account); addLoginError(account);
return false; return false;
} }
} */
return false; // FIMXE re-implement password reset
private void executePasswordReset(AccountEntity account, String newPassword) { }
Date now = new Date(); // TODO now in UTC
private void executePasswordReset(AccountEntity account, String newPassword) {
String hashedPassword = SecurityUtil.createPassword(newPassword); Date now = new Date(); // TODO now in UTC
account.setAccountPassword(hashedPassword);
String hashedPassword = SecurityUtil.createPassword(newPassword);
account.setPasswordResetOngoing(false); // account.setAccountPassword(hashedPassword);
account.setPasswordResetHash(null); //
account.setPasswordResetValidTo(null); // account.setPasswordResetOngoing(false);
// account.setPasswordResetHash(null);
account.setLastUpdatedBy(account.getUsername()); // account.setPasswordResetValidTo(null);
account.setLastUpdatedOn(now);
em.merge(account); account.setLastUpdatedBy(account.getUsername());
account.setLastUpdatedOn(now);
} em.merge(account);
public void updateLogin(AccountEntity account) { }
Date now = new Date(); // TODO now in UTC
// a scucessful login ends a password reset procedure public AccountLoginEntity updateSuccessFullLogin(AccountLoginEntity login, String byUser) {
if (account.getPasswordResetOngoing()) { Date now = DateUtil.getCurrentTimeInUTC();
account.setPasswordResetOngoing(false); // a scucessful login ends a password reset procedure
account.setPasswordResetHash(null); if (login.getPasswordResetOngoing()) {
account.setPasswordResetValidTo(null); login.setPasswordResetOngoing(false);
account.setLastUpdatedOn(now); login.setPasswordResetHash(null);
account.setLastUpdatedBy(account.getUsername()); login.setPasswordResetValidTo(null);
} login.setLastUpdatedOn(now);
login.setLastUpdatedBy(byUser);
account.setLastLogin(now); }
account.setFailureCount(0);
account.setStatus(AccountStatus.NORMAL.name()); login.setLastLogin(now);
login.setFailureCount(0);
em.merge(account); return updateLogin(login);
} }
public void addLoginError(ApplicationEntity application, AccountEntity account) {
try { public AccountLoginEntity updateLogin(AccountLoginEntity login) {
Date now = new Date(); // TODO now in UTC return em.merge (login);
account.setLastFailedLogin(now); }
account.setFailureCount(account.getFailureCount() + 1);
public void updateLogin (AccountEntity account) {
int maxFailedLogins = Integer.parseInt(configService.getConfigValue("account.maxFailedLogins")); if (account.getAccountLogin() == null) {
if ((account.getFailureCount() >= maxFailedLogins) && (!account.getStatus().equals("LOCKED"))) { // TOD add status enum // TODO connect to IPRS - how can an account ask for an updated login if the user cannot login
// max failed logins reached, disabling user } else {
LOGGER.info("Locking account " + account.getUsername() + " due to " + account.getFailureCount() + " failed logins"); updateSuccessFullLogin (account.getAccountLogin(), account.getUsername());
account.setStatus(AccountStatus.BLOCKED.name()); }
} }
// on a failed login request, disable password reset
account.setPasswordResetOngoing(false);
account.setPasswordResetHash(null); public void addLoginError(AccountEntity account) {
account.setPasswordResetValidTo(null); // TODO reimplement
// try {
account.setLastUpdatedBy("system"); // Date now = new Date(); // TODO now in UTC
account.setLastUpdatedOn(now); // account.setLastFailedLogin(now);
em.merge(account); // account.setFailureCount(account.getFailureCount() + 1);
} catch (ConfigException ex) { //
if (LOGGER.isDebugEnabled()) { // int maxFailedLogins = Integer.parseInt(configService.getConfigValue( "account.maxFailedLogins"));
LOGGER.debug(ex.toString(), ex); // if ((account.getFailureCount() >= maxFailedLogins) && (!account.getStatus().equals("LOCKED"))) { // TOD add status enum
} else { // // max failed logins reached, disabling user
LOGGER.error(ex.toString()); // 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());
// }
// }
}
public AccountLoginEntity createLoginWithRandomPassword() {
AccountLoginEntity login = new AccountLoginEntity();
String randomPassword = RandomStringUtils.random(20, true, true);
String hashedPassword = SecurityUtil.createPassword(randomPassword);
login.setAccountPassword(hashedPassword);
login.setLastLogin(null);
login.setLastFailedLogin(null);
login.setFailureCount(0);
return login;
}
public String getHashedPassword (String password) {
String hashedPassword = SecurityUtil.createPassword(password);
return hashedPassword;
}
@Transactional
public void addLogin(AccountEntity accountToAdd, AccountLoginEntity accountLogin) {
Date now = DateUtil.getCurrentTimeInUTC();
Subject currentUser = SecurityUtils.getSubject();
String currentLoggedInUser = currentUser.getPrincipal().toString();
AccountEntity account = em.merge(accountToAdd);
accountLogin.setAccount(account);
accountLogin.setCreatedBy(currentLoggedInUser);
accountLogin.setCreatedOn(now);
accountLogin.setLastUpdatedBy(currentLoggedInUser);
accountLogin.setLastUpdatedOn(now);
em.persist(accountLogin);
account.setAccountLogin(accountLogin);
em.merge(account);
}
@Transactional
public void deleteLogin(AccountEntity accountToDelete) {
AccountEntity account = em.merge(accountToDelete);
AccountLoginEntity login = account.getAccountLogin();
login.setAccount(null);
account.setAccountLogin(null);
em.remove(login);
em.merge(account);
}
}

View File

@ -1,105 +1,99 @@
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.ApplicationPermissionEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity;
import de.muehlencord.shared.account.business.application.boundary.ApplicationService; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import java.io.Serializable;
import java.io.Serializable; import javax.ejb.Stateless;
import javax.ejb.Stateless; import javax.persistence.EntityManager;
import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContext; import java.util.List;
import java.util.List; import java.util.ArrayList;
import java.util.ArrayList; import javax.persistence.OptimisticLockException;
import javax.ejb.EJB; import javax.persistence.Query;
import javax.persistence.OptimisticLockException; import javax.transaction.Transactional;
import javax.persistence.Query;
import javax.transaction.Transactional; /**
*
/** * @author Joern Muehlencord <joern at muehlencord.de>
* */
* @author Joern Muehlencord <joern at muehlencord.de> @Stateless
*/ public class ApplicationPermissionControl implements Serializable {
@Stateless
public class ApplicationPermissionControl implements Serializable { private static final long serialVersionUID = -3761100587901739481L;
private static final long serialVersionUID = -3761100587901739481L; @PersistenceContext
EntityManager em;
@EJB
ApplicationService applicationService; public List<ApplicationPermissionEntity> getApplicationPermissions(ApplicationEntity app) {
Query query = em.createNamedQuery("ApplicationPermissionEntity.findAll");
@PersistenceContext query.setParameter("application", app);
EntityManager em; List<ApplicationPermissionEntity> permissionList = query.getResultList();
if (permissionList == null) {
public List<ApplicationPermissionEntity> getApplicationPermissions(ApplicationEntity application) { return new ArrayList<>();
Query query = em.createNamedQuery("ApplicationPermissionEntity.findAll"); } else {
query.setParameter("application", application); return permissionList;
List<ApplicationPermissionEntity> permissionList = query.getResultList(); }
if (permissionList == null) { }
return new ArrayList<>();
} else { public ApplicationPermissionEntity findPermissionByName(ApplicationEntity application, String permissionName) {
return permissionList; Query query = em.createNamedQuery("ApplicationPermissionEntity.findByPermissionName");
} query.setParameter("application", application);
} query.setParameter("permissionName", permissionName);
List<ApplicationPermissionEntity> resultList = query.getResultList();
public ApplicationPermissionEntity findPermissionByName(ApplicationEntity application, String permissionName) { if ((resultList == null) || (resultList.isEmpty())) {
Query query = em.createNamedQuery("ApplicationPermissionEntity.findByPermissionName"); return null;
query.setParameter("application", application); } else {
query.setParameter("permissionName", permissionName); return resultList.get(0);
List<ApplicationPermissionEntity> resultList = query.getResultList(); }
if ((resultList == null) || (resultList.isEmpty())) { }
return null;
} else { @Transactional
return resultList.get(0); public void create(ApplicationEntity application,String name, String description) {
} ApplicationPermissionEntity permission = new ApplicationPermissionEntity(application, name, description);
} em.persist(permission);
}
@Transactional
public void create(String applicationName, String name, String description) { @Transactional
ApplicationEntity application = applicationService.findByApplicationName(applicationName); public void update(ApplicationPermissionEntity permission) throws AccountException {
// TODO add error handling if not found ApplicationPermissionEntity existing = attach(permission);
ApplicationPermissionEntity permission = new ApplicationPermissionEntity(application, name, description); em.merge(existing);
em.persist(permission); }
}
@Transactional
@Transactional public void createOrUpdate(ApplicationEntity application, String name, String description) {
public void update(ApplicationPermissionEntity permission) throws AccountException { ApplicationPermissionEntity permission = findByName(application, name);
ApplicationPermissionEntity existing = attach(permission); if (permission == null) {
em.merge(existing); permission = new ApplicationPermissionEntity(name, description);
} em.persist(permission);
} else {
@Transactional permission.setPermissionDescription(description);
public void createOrUpdate(String name, String description) { em.merge(permission);
ApplicationPermissionEntity permission = findByName(name); }
if (permission == null) { }
permission = new ApplicationPermissionEntity(name, description);
em.persist(permission); public void delete(ApplicationPermissionEntity permission) throws AccountException {
} else { ApplicationPermissionEntity existingPermission = attach(permission);
permission.setPermissionDescription(description); em.remove(existingPermission);
em.merge(permission); }
}
} public ApplicationPermissionEntity attach(ApplicationPermissionEntity permission) throws AccountException {
try {
public void delete(ApplicationPermissionEntity permission) throws AccountException { return em.merge(permission);
ApplicationPermissionEntity existingPermission = attach(permission); } catch (OptimisticLockException ex) {
em.remove(existingPermission); throw new AccountException("Entity updated / deleted, please reload", true);
} }
}
public ApplicationPermissionEntity attach(ApplicationPermissionEntity permission) throws AccountException {
try { private ApplicationPermissionEntity findByName(ApplicationEntity application, String name) {
return em.merge(permission); Query query = em.createNamedQuery("ApplicationPermissionEntity.findByPermissionName");
} catch (OptimisticLockException ex) { query.setParameter("application", application);
throw new AccountException("Entity updated / deleted, please reload", true); query.setParameter("permissionName", name);
} List<ApplicationPermissionEntity> permissions = query.getResultList();
} if ((permissions == null) || (permissions.isEmpty())) {
return null;
private ApplicationPermissionEntity findByName(String name) { } else {
Query query = em.createNamedQuery("ApplicationPermissionEntity.findByPermissionName"); return permissions.get(0);
query.setParameter("permissionName", name); }
List<ApplicationPermissionEntity> permissions = query.getResultList(); }
if ((permissions == null) || (permissions.isEmpty())) { }
return null;
} else {
return permissions.get(0);
}
}
}

View File

@ -1,149 +1,147 @@
/* /*
* To change this license header, choose License Headers in Project Properties. * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
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.ApplicationPermissionEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationPermissionEntity;
import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity; import de.muehlencord.shared.account.business.account.entity.ApplicationRoleEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
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.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.OptimisticLockException; import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import javax.persistence.Query; import javax.persistence.Query;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* *
* @author Joern Muehlencord <joern at muehlencord.de> * @author Joern Muehlencord <joern at muehlencord.de>
*/ */
@Stateless @Stateless
public class ApplicationRoleControl implements Serializable { public class ApplicationRoleControl implements Serializable {
private static final long serialVersionUID = 5962478269550134748L; private static final long serialVersionUID = 5962478269550134748L;
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRoleControl.class); private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRoleControl.class);
@EJB @EJB
ApplicationPermissionControl applicationPermissionControl; ApplicationPermissionControl applicationPermissionControl;
@PersistenceContext @PersistenceContext
EntityManager em; EntityManager em;
public List<ApplicationRoleEntity> getAllRoles(ApplicationEntity application) { public List<ApplicationRoleEntity> getAllRoles(ApplicationEntity app) {
Query query = em.createNamedQuery("ApplicationRoleEntity.findAll"); Query query = em.createNamedQuery("ApplicationRoleEntity.findAll");
query.setParameter ("application", application); query.setParameter("application", app);
List<ApplicationRoleEntity> roles = query.getResultList(); List<ApplicationRoleEntity> roles = query.getResultList();
if (roles == null) { if (roles == null) {
return new ArrayList<>(); return new ArrayList<>();
} else { } else {
return roles; return roles;
} }
} }
@Transactional @Transactional
public void createOrUpdate(ApplicationEntity application, String name, String description) { public void createOrUpdate(ApplicationEntity application, String name, String description) {
ApplicationRoleEntity role = findByName(application, name); ApplicationRoleEntity role = findByName(application, name);
if (role == null) { if (role == null) {
role = new ApplicationRoleEntity(application, name, description); role = new ApplicationRoleEntity(application, name, description);
em.persist(role); em.persist(role);
} else { } else {
role.setRoleDescription(description); role.setRoleDescription(description);
em.merge(role); em.merge(role);
} }
} }
@Transactional @Transactional
public void create(ApplicationRoleEntity role) { public void create(ApplicationRoleEntity role) {
em.persist(role); em.persist(role);
} }
@Transactional @Transactional
public void update (ApplicationRoleEntity role) { public void update(ApplicationRoleEntity role) {
em.merge(role); em.merge(role);
} }
public void delete(ApplicationRoleEntity role) throws AccountException { public void delete(ApplicationRoleEntity role) throws AccountException {
ApplicationRoleEntity existingRole = attach(role); ApplicationRoleEntity existingRole = attach(role);
em.remove(existingRole); em.remove(existingRole);
} }
public ApplicationRoleEntity attach(ApplicationRoleEntity role) throws AccountException { public ApplicationRoleEntity attach(ApplicationRoleEntity role) throws AccountException {
try { try {
return em.merge(role); return em.merge(role);
} catch (OptimisticLockException ex) { } catch (OptimisticLockException ex) {
throw new AccountException("Entity updated / deleted, please reload", true); throw new AccountException("Entity updated / deleted, please reload", true);
} }
} }
public ApplicationRoleEntity findByName(ApplicationEntity application, String name) { public ApplicationRoleEntity findByName(ApplicationEntity application, String name) {
Query query = em.createNamedQuery("ApplicationRoleEntity.findByRoleName"); Query query = em.createNamedQuery("ApplicationRoleEntity.findByRoleName");
query.setParameter("application", application); query.setParameter("application", application);
query.setParameter("roleName", name); query.setParameter("roleName", name);
List<ApplicationRoleEntity> permissions = query.getResultList(); List<ApplicationRoleEntity> permissions = query.getResultList();
if ((permissions == null) || (permissions.isEmpty())) { if ((permissions == null) || (permissions.isEmpty())) {
return null; return null;
} else { } else {
return permissions.get(0); return permissions.get(0);
} }
} }
public List<ApplicationPermissionEntity> getRolePermissions(ApplicationRoleEntity role) throws AccountException { public List<ApplicationPermissionEntity> getRolePermissions(ApplicationRoleEntity role) throws AccountException {
ApplicationRoleEntity existingRole = em.find(ApplicationRoleEntity.class, role.getId()); ApplicationRoleEntity existingRole = em.find(ApplicationRoleEntity.class, role.getId());
List<ApplicationPermissionEntity> permissions = existingRole.getApplicationPermissionList(); List<ApplicationPermissionEntity> permissions = existingRole.getApplicationPermissionList();
permissions.size(); // force list to load permissions.size(); // force list to load
return permissions; return permissions;
} }
public List<ApplicationPermissionEntity> getNotAssignedApplicationPermissions(ApplicationRoleEntity role) { public List<ApplicationPermissionEntity> getNotAssignedApplicationPermissions(ApplicationRoleEntity role) {
try { try {
List<ApplicationPermissionEntity> rolePermissions = getRolePermissions(role); List<ApplicationPermissionEntity> rolePermissions = getRolePermissions(role);
List<ApplicationPermissionEntity> allPermssions = applicationPermissionControl.getApplicationPermissions(role.getApplication()); List<ApplicationPermissionEntity> allPermssions = applicationPermissionControl.getApplicationPermissions(role.getApplication());
List<ApplicationPermissionEntity> missingPermissions = new ArrayList<>(); List<ApplicationPermissionEntity> missingPermissions = new ArrayList<>();
allPermssions.stream().filter((perm) -> (!rolePermissions.contains(perm))).forEachOrdered((perm) -> { allPermssions.stream().filter((perm) -> (!rolePermissions.contains(perm))).forEachOrdered((perm) -> {
missingPermissions.add(perm); missingPermissions.add(perm);
}); });
return missingPermissions; return missingPermissions;
} catch (AccountException ex) { } catch (AccountException ex) {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug(ex.toString(), ex); LOGGER.debug(ex.toString(), ex);
} else { } else {
LOGGER.debug(ex.toString()); LOGGER.debug(ex.toString());
} }
return null; return null;
} }
} }
@Transactional @Transactional
public void addPermission(ApplicationRoleEntity role, ApplicationPermissionEntity permission) throws AccountException { public void addPermission(ApplicationRoleEntity role, ApplicationPermissionEntity permission) throws AccountException {
ApplicationRoleEntity existingRole = attach(role); ApplicationRoleEntity existingRole = attach(role);
if (existingRole.getApplicationPermissionList() == null) { if (existingRole.getApplicationPermissionList() == null) {
existingRole.setApplicationPermissionList(new ArrayList<>()); existingRole.setApplicationPermissionList(new ArrayList<>());
} }
existingRole.getApplicationPermissionList().add(permission); existingRole.getApplicationPermissionList().add(permission);
em.merge(role); em.merge(role);
} }
@Transactional @Transactional
public void removePermission(ApplicationRoleEntity role, ApplicationPermissionEntity permission) throws AccountException { public void removePermission(ApplicationRoleEntity role, ApplicationPermissionEntity permission) throws AccountException {
ApplicationRoleEntity existingRole = attach(role); ApplicationRoleEntity existingRole = attach(role);
if ((existingRole.getApplicationPermissionList() != null) && (existingRole.getApplicationPermissionList().contains(permission))) { if ((existingRole.getApplicationPermissionList() != null) && (existingRole.getApplicationPermissionList().contains(permission))) {
existingRole.getApplicationPermissionList().remove(permission); existingRole.getApplicationPermissionList().remove(permission);
} }
em.merge(role); em.merge(role);
} }
}
}

View File

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

View File

@ -1,270 +1,243 @@
/* /*
* To change this license header, choose License Headers in Project Properties. * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
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.Date;
import java.util.UUID; import java.util.UUID;
import javax.persistence.Basic; import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.Lob; import javax.persistence.NamedQueries;
import javax.persistence.NamedQueries; import javax.persistence.NamedQuery;
import javax.persistence.NamedQuery; import javax.persistence.OneToOne;
import javax.persistence.OneToOne; import javax.persistence.Table;
import javax.persistence.Table; import javax.persistence.Temporal;
import javax.persistence.Temporal; import javax.persistence.TemporalType;
import javax.persistence.TemporalType; import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;
import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlRootElement; import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type;
import org.hibernate.annotations.Type;
/**
/** *
* * @author jomu
* @author jomu */
*/ @Entity
@Entity @Table(name = "account_login")
@Table(name = "account_login") @XmlRootElement
@XmlRootElement @NamedQueries({
@NamedQueries({ @NamedQuery(name = "AccountLoginEntity.findAll", query = "SELECT a FROM AccountLoginEntity a"),
@NamedQuery(name = "AccountLoginEntity.findAll", query = "SELECT a FROM AccountLoginEntity a"), @NamedQuery(name = "AccountLoginEntity.findByAccountPassword", query = "SELECT a FROM AccountLoginEntity a WHERE a.accountPassword = :accountPassword"),
@NamedQuery(name = "AccountLoginEntity.findByAccountPassword", query = "SELECT a FROM AccountLoginEntity a WHERE a.accountPassword = :accountPassword"), @NamedQuery(name = "AccountLoginEntity.findByLastLogin", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastLogin = :lastLogin"),
@NamedQuery(name = "AccountLoginEntity.findByLastLogin", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastLogin = :lastLogin"), @NamedQuery(name = "AccountLoginEntity.findByLastFailedLogin", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastFailedLogin = :lastFailedLogin"),
@NamedQuery(name = "AccountLoginEntity.findByLastFailedLogin", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastFailedLogin = :lastFailedLogin"), @NamedQuery(name = "AccountLoginEntity.findByFailureCount", query = "SELECT a FROM AccountLoginEntity a WHERE a.failureCount = :failureCount"),
@NamedQuery(name = "AccountLoginEntity.findByFailureCount", query = "SELECT a FROM AccountLoginEntity a WHERE a.failureCount = :failureCount"), @NamedQuery(name = "AccountLoginEntity.findByPasswordResetOngoing", query = "SELECT a FROM AccountLoginEntity a WHERE a.passwordResetOngoing = :passwordResetOngoing"),
@NamedQuery(name = "AccountLoginEntity.findByPasswordResetOngoing", query = "SELECT a FROM AccountLoginEntity a WHERE a.passwordResetOngoing = :passwordResetOngoing"), @NamedQuery(name = "AccountLoginEntity.findByPasswordResetValidTo", query = "SELECT a FROM AccountLoginEntity a WHERE a.passwordResetValidTo = :passwordResetValidTo"),
@NamedQuery(name = "AccountLoginEntity.findByPasswordResetValidTo", query = "SELECT a FROM AccountLoginEntity a WHERE a.passwordResetValidTo = :passwordResetValidTo"), @NamedQuery(name = "AccountLoginEntity.findByPasswordResetHash", query = "SELECT a FROM AccountLoginEntity a WHERE a.passwordResetHash = :passwordResetHash"),
@NamedQuery(name = "AccountLoginEntity.findByPasswordResetHash", query = "SELECT a FROM AccountLoginEntity a WHERE a.passwordResetHash = :passwordResetHash"), @NamedQuery(name = "AccountLoginEntity.findByCreatedOn", query = "SELECT a FROM AccountLoginEntity a WHERE a.createdOn = :createdOn"),
@NamedQuery(name = "AccountLoginEntity.findByCreatedOn", query = "SELECT a FROM AccountLoginEntity a WHERE a.createdOn = :createdOn"), @NamedQuery(name = "AccountLoginEntity.findByCreatedBy", query = "SELECT a FROM AccountLoginEntity a WHERE a.createdBy = :createdBy"),
@NamedQuery(name = "AccountLoginEntity.findByCreatedBy", query = "SELECT a FROM AccountLoginEntity a WHERE a.createdBy = :createdBy"), @NamedQuery(name = "AccountLoginEntity.findByLastUpdatedOn", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastUpdatedOn = :lastUpdatedOn"),
@NamedQuery(name = "AccountLoginEntity.findByLastUpdatedOn", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastUpdatedOn = :lastUpdatedOn"), @NamedQuery(name = "AccountLoginEntity.findByLastUpdatedBy", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastUpdatedBy = :lastUpdatedBy")})
@NamedQuery(name = "AccountLoginEntity.findByLastUpdatedBy", query = "SELECT a FROM AccountLoginEntity a WHERE a.lastUpdatedBy = :lastUpdatedBy")}) public class AccountLoginEntity implements Serializable {
public class AccountLoginEntity implements Serializable {
private static final long serialVersionUID = -799045989045040077L;
private static final long serialVersionUID = -799045989045040077L;
@Id
@Id @Basic(optional = false)
@Basic(optional = false) @NotNull
@NotNull @Column(name = "id")
@Column(name = "id") @GeneratedValue(generator = "uuid2")
@GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2") @Type(type = "pg-uuid")
@Type(type = "pg-uuid") private UUID id;
private UUID id; @Basic(optional = false)
@Basic(optional = false) @NotNull
@NotNull @Size(min = 1, max = 200)
@Size(min = 1, max = 32) @Column(name = "account_password")
@Column(name = "username") private String accountPassword;
private String username; @Column(name = "last_login")
@Basic(optional = false) @Temporal(TemporalType.TIMESTAMP)
@NotNull private Date lastLogin;
@Size(min = 1, max = 200) @Column(name = "last_failed_login")
@Column(name = "emailaddress") @Temporal(TemporalType.TIMESTAMP)
private String emailaddress; private Date lastFailedLogin;
@Basic(optional = false) @Basic(optional = false)
@NotNull @NotNull
@Size(min = 1, max = 200) @Column(name = "failure_count")
@Column(name = "account_password") private int failureCount;
private String accountPassword; @Basic(optional = false)
@Column(name = "last_login") @NotNull
@Temporal(TemporalType.TIMESTAMP) @Column(name = "password_reset_ongoing")
private Date lastLogin; private boolean passwordResetOngoing;
@Column(name = "last_failed_login") @Column(name = "password_reset_valid_to")
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date lastFailedLogin; private Date passwordResetValidTo;
@Basic(optional = false) @Size(max = 200)
@NotNull @Column(name = "password_reset_hash")
@Column(name = "failure_count") private String passwordResetHash;
private int failureCount; @Basic(optional = false)
@Basic(optional = false) @NotNull
@NotNull @Column(name = "created_on")
@Column(name = "password_reset_ongoing") @Temporal(TemporalType.TIMESTAMP)
private boolean passwordResetOngoing; private Date createdOn;
@Column(name = "password_reset_valid_to") @Basic(optional = false)
@Temporal(TemporalType.TIMESTAMP) @NotNull
private Date passwordResetValidTo; @Size(min = 1, max = 32)
@Size(max = 200) @Column(name = "created_by")
@Column(name = "password_reset_hash") private String createdBy;
private String passwordResetHash; @Basic(optional = false)
@Basic(optional = false) @NotNull
@NotNull @Column(name = "last_updated_on")
@Column(name = "created_on") @Temporal(TemporalType.TIMESTAMP)
@Temporal(TemporalType.TIMESTAMP) private Date lastUpdatedOn;
private Date createdOn; @Basic(optional = false)
@Basic(optional = false) @NotNull
@NotNull @Size(min = 1, max = 32)
@Size(min = 1, max = 32) @Column(name = "last_updated_by")
@Column(name = "created_by") private String lastUpdatedBy;
private String createdBy; @JoinColumn(name = "account", referencedColumnName = "id")
@Basic(optional = false) @OneToOne(optional = false)
@NotNull private AccountEntity account;
@Column(name = "last_updated_on")
@Temporal(TemporalType.TIMESTAMP) public AccountLoginEntity() {
private Date lastUpdatedOn; }
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 32) public UUID getId() {
@Column(name = "last_updated_by") return id;
private String lastUpdatedBy; }
@JoinColumn(name = "account", referencedColumnName = "id")
@OneToOne(optional = false) public void setId(UUID id) {
private AccountEntity account; this.id = id;
}
public AccountLoginEntity() {
} public String getAccountPassword() {
return accountPassword;
}
public UUID getId() {
return id; public void setAccountPassword(String accountPassword) {
} this.accountPassword = accountPassword;
}
public void setId(UUID id) {
this.id = id; 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 boolean getPasswordResetOngoing() {
} return passwordResetOngoing;
}
public int getFailureCount() {
return failureCount; public void setPasswordResetOngoing(boolean passwordResetOngoing) {
} this.passwordResetOngoing = passwordResetOngoing;
}
public void setFailureCount(int failureCount) {
this.failureCount = failureCount; 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; public AccountEntity getAccount() {
} return account;
}
public String getLastUpdatedBy() {
return lastUpdatedBy; public void setAccount(AccountEntity account) {
} this.account = account;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy; @Override
} public int hashCode() {
int hash = 0;
public AccountEntity getAccount() { hash += (id != null ? id.hashCode() : 0);
return account; return hash;
} }
public void setAccount(AccountEntity account) { @Override
this.account = account; public boolean equals(Object object) {
} // TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AccountLoginEntity)) {
public String getUsername() { return false;
return username; }
} AccountLoginEntity other = (AccountLoginEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
public void setUsername(String username) { return false;
this.username = username; }
} return true;
}
public String getEmailaddress() {
return emailaddress; @Override
} public String toString() {
return "de.muehlencord.shared.account.business.account.entity.AccountLoginEntity[ id=" + id + " ]";
public void setEmailaddress(String emailaddress) { }
this.emailaddress = emailaddress;
} }
@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 AccountLoginEntity)) {
return false;
}
AccountLoginEntity other = (AccountLoginEntity) 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.account.entity.AccountLoginEntity[ id=" + id + " ]";
}
}

View File

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

View File

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

View File

@ -1,237 +1,204 @@
package de.muehlencord.shared.account.business.config.boundary; package de.muehlencord.shared.account.business.config.boundary;
import de.muehlencord.shared.account.business.account.entity.Account; import de.muehlencord.shared.account.business.account.entity.Account;
import de.muehlencord.shared.account.business.account.entity.AccountEntity; import de.muehlencord.shared.account.business.account.entity.AccountEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import de.muehlencord.shared.account.business.config.entity.ConfigEntity; import de.muehlencord.shared.account.business.config.entity.ConfigEntity;
import de.muehlencord.shared.account.business.config.entity.ConfigEntityPK; import de.muehlencord.shared.account.business.config.entity.ConfigEntityPK;
import de.muehlencord.shared.account.business.config.entity.ConfigException; import de.muehlencord.shared.account.business.config.entity.ConfigException;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.ejb.Lock; import javax.ejb.Lock;
import javax.ejb.LockType; import javax.ejb.LockType;
import javax.ejb.Singleton; import javax.ejb.Singleton;
import javax.ejb.Startup; import javax.ejb.Startup;
import javax.inject.Inject; import javax.inject.Inject;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.Query; import javax.persistence.Query;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* *
* @author joern.muehlencord * @author joern.muehlencord
*/ */
@Singleton @Singleton
@Startup @Startup
public class ConfigService implements Serializable { public class ConfigService implements Serializable {
private static final long serialVersionUID = -3195224653632853003L; private static final long serialVersionUID = -3195224653632853003L;
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigService.class); private static final Logger LOGGER = LoggerFactory.getLogger(ConfigService.class);
@Inject @Inject
EntityManager em; EntityManager em;
// private String storagePath = null; @Inject
// private int maxFailedLogins = 5; ApplicationEntity application;
@PostConstruct
public void init() { /**
// ConfigEntity configEntity = em.find(ConfigEntity.class, "storage.path"); * returns global config key which is not assigned to any. If more than one
// if (configEntity != null) { * value is defined for the given key, the key assigned to system is
// this.storagePath = configEntity.getConfigValue(); * returned. If more than one key is defined but system key is not defined,
// } * an exception is thrown.
// configEntity = em.find(ConfigEntity.class, "account.maxFailedLogins"); *
// if (configEntity != null) { * @param configKey the key to return
// this.maxFailedLogins = Integer.parseInt(configEntity.getConfigValue()); * @return the configValue belonging to the given configKey
// } * @throws
} * de.muehlencord.shared.account.business.config.entity.ConfigException if
* more than one value is defined for the given key but none of the values
/** * is defined for the system user
* returns global config key which is not assigned to any. If more than one */
* value is defined for the given key, the key assigned to system is public String getConfigValue(String configKey) throws ConfigException {
* returned. If more than one key is defined but system key is not defined, Query query = em.createNamedQuery("ConfigEntity.findByConfigKey");
* an exception is thrown. query.setParameter("application", application);
* query.setParameter("configKey", configKey);
* @param configKey the key to return List<ConfigEntity> configList = query.getResultList();
* @return the configValue belonging to the given configKey if ((configList == null) || (configList.isEmpty())) {
* @throws // key is not found in the database at all
* de.muehlencord.shared.account.business.config.entity.ConfigException if return null;
* more than one value is defined for the given key but none of the values } else if (configList.size() == 1) {
* is defined for the system user // exact one element found, return this one
*/ return configList.get(0).getConfigValue();
public String getConfigValue(ApplicationEntity application, String configKey) throws ConfigException { } else {
Query query = em.createNamedQuery("ConfigEntity.findByConfigKey"); // if more than one result found, return the one which is assigned to system if present
query.setParameter ("application", application); // if not present, throw exception
query.setParameter("configKey", configKey); Optional<ConfigEntity> firstItem = configList.stream()
List<ConfigEntity> configList = query.getResultList(); .filter(config -> config.getConfigPK().getConfigKeyAccount().getUsername().equals("system"))
if ((configList == null) || (configList.isEmpty())) { .findFirst();
// key is not found in the database at all if (firstItem.isPresent()) {
return null; return firstItem.get().getConfigValue();
} else if (configList.size() == 1) { } else {
// exact one element found, return this one throw new ConfigException("ConfigKey " + configKey + " not unique and system value not defined");
return configList.get(0).getConfigValue(); }
} else { }
// if more than one result found, return the one which is assigned to system if present }
// if not present, throw exception
Optional<ConfigEntity> firstItem = configList.stream() public String getConfigValue(String configKey, String defaultValue) throws ConfigException {
.filter(config -> config.getConfigPK().getConfigKeyAccount().getUsername().equals("system")) return getConfigValue(configKey, defaultValue, false);
.findFirst(); }
if (firstItem.isPresent()) {
return firstItem.get().getConfigValue(); public String getConfigValue(String configKey, String defaultValue, boolean storeDefaultValue) throws ConfigException {
} else { // get configValue as usual
throw new ConfigException("ConfigKey " + configKey + " not unique and system value not defined"); String configValue = getConfigValue(configKey);
}
} // if config value is not found null has been returned
} // in this case the value to return is the defaultValue
if (configValue == null) {
public String getConfigValue(ApplicationEntity application, String configKey, String defaultValue) throws ConfigException { configValue = defaultValue;
return getConfigValue(application, configKey, defaultValue, false); }
}
// check if the default value should be stored in the database
public String getConfigValue(ApplicationEntity application, String configKey, String defaultValue, boolean storeDefaultValue) throws ConfigException { if (storeDefaultValue) {
// get configValue as usual AccountEntity account = getAccount("system");
String configValue = getConfigValue(application, configKey); updateConfigValue(configKey, account, configValue);
}
// if config value is not found null has been returned
// in this case the value to return is the defaultValue return defaultValue;
if (configValue == null) { }
configValue = defaultValue;
} public String getConfigValue(String configKey, Account account, boolean fallbackToSystem) throws ConfigException {
Query query = em.createNamedQuery("ConfigEntity.findByConfigKeyAndAccount");
// check if the default value should be stored in the database query.setParameter("configKey", configKey);
if (storeDefaultValue) { query.setParameter("account", account);
AccountEntity account = getAccount("system"); List<ConfigEntity> configList = query.getResultList();
updateConfigValue(application, configKey, account, configValue); if ((configList == null) || (configList.isEmpty())) {
} // fallback to default / system value
if (fallbackToSystem) {
return defaultValue; return getConfigValue(configKey);
} } else {
return null;
public String getConfigValue(ApplicationEntity application, String configKey, Account account, boolean fallbackToSystem) throws ConfigException { }
Query query = em.createNamedQuery("ConfigEntity.findByConfigKeyAndAccount"); } else if (configList.size() == 1) {
query.setParameter("configKey", configKey); // exact one element found, return this one
query.setParameter("account", account); return configList.get(0).getConfigValue();
List<ConfigEntity> configList = query.getResultList(); } else {
if ((configList == null) || (configList.isEmpty())) { // more than one value must not happen - this is not possible per the defintion of the datamodel
// fallback to default / system value throw new ConfigException("Cannot have more than one value for the the given key " + configKey + " and the given account " + account.getUsername());
if (fallbackToSystem) { }
return getConfigValue(application, configKey); }
} else {
return null; public String getConfigValue(String configKey, String defaultValue, boolean storeDefaultValue, Account account, boolean fallbackToSystem) throws ConfigException {
} String configValue = getConfigValue(configKey, account, fallbackToSystem);
} else if (configList.size() == 1) {
// exact one element found, return this one if (configValue == null) {
return configList.get(0).getConfigValue(); // value not found for given account and if allowed also not found for system user
} else { configValue = defaultValue;
// more than one value must not happen - this is not possible per the defintion of the datamodel }
throw new ConfigException("Cannot have more than one value for the the given key " + configKey + " and the given account " + account.getUsername());
} // check if the default value should be stored in the database
} if (storeDefaultValue) {
updateConfigValue(configKey, account, configValue);
public String getConfigValue(ApplicationEntity application, String configKey, String defaultValue, boolean storeDefaultValue, Account account, boolean fallbackToSystem) throws ConfigException { }
String configValue = getConfigValue(application, configKey, account, fallbackToSystem);
return configValue;
if (configValue == null) { }
// value not found for given account and if allowed also not found for system user
configValue = defaultValue; @Transactional
} @Lock(LockType.WRITE)
public boolean updateConfigValue(String configKey, String configValue) throws ConfigException {
// check if the default value should be stored in the database Account account = getAccount("system");
if (storeDefaultValue) { return updateConfigValue(configKey, account, configValue);
updateConfigValue(application, configKey, account, configValue); }
}
@Transactional
return configValue; @Lock(LockType.WRITE)
} public boolean updateConfigValue(String configKey, String accountName, String configValue) {
Account account = getAccount(accountName);
@Transactional if (accountName == null) {
@Lock(LockType.WRITE) return false;
public boolean updateConfigValue(ApplicationEntity application,String configKey, String configValue) throws ConfigException { }
Account account = getAccount("system"); if (account == null) {
return updateConfigValue(application, configKey, account, configValue); LOGGER.error("Account for usreName {} not found", accountName);
} return false;
}
@Transactional return updateConfigValue(configKey, account, configValue);
@Lock(LockType.WRITE) }
public boolean updateConfigValue(ApplicationEntity application,String configKey, String accountName, String configValue) {
Account account = getAccount(accountName); @Transactional
if (accountName == null) { @Lock(LockType.WRITE)
return false; public boolean updateConfigValue(String configKey, Account account, String configValue) {
} if ((configKey == null) || (configKey.equals("")) || (configValue == null) || (configValue.equals(""))) {
if (account == null) { // null or empty key / values are not possible
LOGGER.error("Account for usreName {} not found", accountName); return false;
return false; }
}
return updateConfigValue(application, configKey, account, configValue); if (account == null) {
} LOGGER.error("Account must not be null, not updating");
return false;
@Transactional }
@Lock(LockType.WRITE)
public boolean updateConfigValue(ApplicationEntity application, String configKey, Account account, String configValue) { AccountEntity accountEntity = getAccount(account.getUsername());
if ((configKey == null) || (configKey.equals("")) || (configValue == null) || (configValue.equals(""))) { ConfigEntityPK pk = new ConfigEntityPK(application, configKey, accountEntity);
// null or empty key / values are not possible ConfigEntity currentEntity = em.find(ConfigEntity.class, pk);
return false; if (currentEntity == null) {
} currentEntity = new ConfigEntity(pk);
currentEntity.setConfigValue(configValue);
if (account == null) { em.persist(currentEntity);
LOGGER.error("Account must not be null, not updating"); return true; // config item created - udpate performed
return false; } else {
} if ((currentEntity.getConfigValue() != null) && (currentEntity.getConfigValue().equals(configValue))) {
// value is the same - no update
AccountEntity accountEntity = getAccount (account.getUsername()); return false;
ConfigEntityPK pk = new ConfigEntityPK(application, configKey, accountEntity); } else {
ConfigEntity currentEntity = em.find(ConfigEntity.class, pk); currentEntity.setConfigValue(configValue);
if (currentEntity == null) { em.merge(currentEntity);
currentEntity = new ConfigEntity(pk); return true;
currentEntity.setConfigValue(configValue); }
em.persist(currentEntity); }
return true; // config item created - udpate performed }
} else {
if ((currentEntity.getConfigValue() != null) && (currentEntity.getConfigValue().equals(configValue))) { private AccountEntity getAccount(String accountName) {
// value is the same - no update Query query = em.createNamedQuery("AccountEntity.findByUsername");
return false; query.setParameter("username", accountName);
} else { List<AccountEntity> accountList = query.getResultList();
currentEntity.setConfigValue(configValue); if ((accountList == null) || (accountList.isEmpty())) {
em.merge(currentEntity); return null;
return true; } else {
} return accountList.get(0);
} }
} }
}
private AccountEntity getAccount(String accountName) {
Query query = em.createNamedQuery("AccountEntity.findByUsername");
query.setParameter("username", accountName);
List<AccountEntity> accountList = query.getResultList();
if ((accountList == null) || (accountList.isEmpty())) {
return null;
} else {
return accountList.get(0);
}
}
/* *** getter *** */
/**
* FIXME remove, this is application specific
*
* @return
* @deprecated replace by getConfigValue ("storage.path")
*/
// @Deprecated
// public String getStoragePath() {
// return storagePath;
// }
/**
* // TODO move to accountControl
*
* @return
* @deprecated replace by getConfigValue ("account.maxFailedLogins")
*/
// @Deprecated
// public int getMaxFailedLogins() {
// return maxFailedLogins;
// }
}

View File

@ -1,127 +1,149 @@
/* /*
* To change this license header, choose License Headers in Project Properties. * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package de.muehlencord.shared.account.business.config.entity; package de.muehlencord.shared.account.business.config.entity;
import de.muehlencord.shared.account.business.account.entity.AccountEntity; import de.muehlencord.shared.account.business.account.entity.AccountEntity;
import de.muehlencord.shared.account.business.application.entity.ApplicationEntity; import de.muehlencord.shared.account.business.application.entity.ApplicationEntity;
import java.io.Serializable; import java.io.Serializable;
import javax.persistence.Cacheable; import javax.persistence.Cacheable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.EmbeddedId; import javax.persistence.EmbeddedId;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.QueryHint; import javax.persistence.QueryHint;
import javax.persistence.Table; import javax.persistence.Table;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.annotations.Cache; import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
/** /**
* *
* @author Joern Muehlencord <joern at muehlencord.de> * @author Joern Muehlencord <joern at muehlencord.de>
*/ */
@Entity @Entity
@Table(name = "config") @Table(name = "config")
@XmlRootElement @XmlRootElement
@Cacheable(true) @Cacheable(true)
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = "Configuration") @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = "Configuration")
@NamedQueries({ @NamedQueries({
@NamedQuery(name = "ConfigEntity.findAll", query = "SELECT c FROM ConfigEntity c ORDER BY c.configPK.configKey", @NamedQuery(name = "ConfigEntity.findAll", query = "SELECT c FROM ConfigEntity c ORDER BY c.configPK.configKey",
hints = { hints = {
@QueryHint(name = "org.hibernate.cacheable", value = "true"), @QueryHint(name = "org.hibernate.cacheable", value = "true"),
@QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}), @QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}),
@NamedQuery(name = "ConfigEntity.findByConfigKey", query = "SELECT c FROM ConfigEntity c WHERE c.configPK.application = :application AND c.configPK.configKey = :configKey", @NamedQuery(name = "ConfigEntity.findByConfigKey", query = "SELECT c FROM ConfigEntity c WHERE c.configPK.application = :application AND c.configPK.configKey = :configKey",
hints = { hints = {
@QueryHint(name = "org.hibernate.cacheable", value = "true"), @QueryHint(name = "org.hibernate.cacheable", value = "true"),
@QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}), @QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}),
@NamedQuery(name = "ConfigEntity.findByConfigKeyAndAccount", query = "SELECT c FROM ConfigEntity c WHERE c.configPK.application = :application AND c.configPK.configKey = :configKey AND c.configPK.configKeyAccount = :account", @NamedQuery(name = "ConfigEntity.findByConfigKeyAndAccount", query = "SELECT c FROM ConfigEntity c WHERE c.configPK.application = :application AND c.configPK.configKey = :configKey AND c.configPK.configKeyAccount = :account",
hints = { hints = {
@QueryHint(name = "org.hibernate.cacheable", value = "true"), @QueryHint(name = "org.hibernate.cacheable", value = "true"),
@QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}), @QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}),
@NamedQuery(name = "ConfigEntity.findByConfigValue", query = "SELECT c FROM ConfigEntity c WHERE c.configPK.application = :application AND c.configValue = :configValue", @NamedQuery(name = "ConfigEntity.findByConfigValue", query = "SELECT c FROM ConfigEntity c WHERE c.configPK.application = :application AND c.configValue = :configValue",
hints = { hints = {
@QueryHint(name = "org.hibernate.cacheable", value = "true"), @QueryHint(name = "org.hibernate.cacheable", value = "true"),
@QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")}) @QueryHint(name = "org.hibernate.cacheRegion", value = "Queries")})
}) })
public class ConfigEntity implements Serializable { public class ConfigEntity implements Serializable {
private static final long serialVersionUID = -2013982316933782223L; private static final long serialVersionUID = -2013982316933782223L;
@EmbeddedId @EmbeddedId
protected ConfigEntityPK configPK; protected ConfigEntityPK configPK;
@Size(max = 200) @Size(max = 200)
@Column(name = "config_value") @Column(name = "config_value")
private String configValue; private String configValue;
@Size(max = 200) @Size(max = 200)
@Column(name = "config_key_group") @Column(name = "config_key_group")
private String configKeyGroup; private String configKeyGroup;
@JoinColumn(name = "config_key_account", referencedColumnName = "id", insertable = false, updatable = false)
public ConfigEntity() { @ManyToOne(optional = false)
} private AccountEntity account;
@JoinColumn(name = "application", referencedColumnName = "id", insertable = false, updatable = false)
public ConfigEntity(ApplicationEntity application, String configKey, AccountEntity account) { @ManyToOne(optional = false)
this.configPK = new ConfigEntityPK(application, configKey, account); private ApplicationEntity application;
}
public ConfigEntity() {
public ConfigEntity(ConfigEntityPK configPK) { }
this.configPK = configPK;
} public ConfigEntity(ApplicationEntity application, String configKey, AccountEntity account) {
this.configPK = new ConfigEntityPK(application, configKey, account);
public ConfigEntityPK getConfigPK() { }
return configPK;
} public ConfigEntity(ConfigEntityPK configPK) {
this.configPK = configPK;
public void setConfigPK(ConfigEntityPK configPK) { }
this.configPK = configPK;
} public ConfigEntityPK getConfigPK() {
return configPK;
public String getConfigValue() { }
return configValue;
} public void setConfigPK(ConfigEntityPK configPK) {
this.configPK = configPK;
public void setConfigValue(String configValue) { }
this.configValue = configValue;
} public String getConfigValue() {
return configValue;
public String getConfigKeyGroup() { }
return configKeyGroup;
} public void setConfigValue(String configValue) {
this.configValue = configValue;
public void setConfigKeyGroup(String configKeyGroup) { }
this.configKeyGroup = configKeyGroup;
} public String getConfigKeyGroup() {
return configKeyGroup;
@Override }
public int hashCode() {
int hash = 0; public void setConfigKeyGroup(String configKeyGroup) {
hash += (configPK != null ? configPK.hashCode() : 0); this.configKeyGroup = configKeyGroup;
return hash; }
}
@Override
@Override public int hashCode() {
public boolean equals(Object object) { int hash = 0;
// TODO: Warning - this method won't work in the case the id fields are not set hash += (configPK != null ? configPK.hashCode() : 0);
if (!(object instanceof ConfigEntity)) { return hash;
return false; }
}
ConfigEntity other = (ConfigEntity) object; @Override
if ((this.configPK == null && other.configPK != null) || (this.configPK != null && !this.configPK.equals(other.configPK))) { public boolean equals(Object object) {
return false; // TODO: Warning - this method won't work in the case the id fields are not set
} if (!(object instanceof ConfigEntity)) {
return true; return false;
} }
ConfigEntity other = (ConfigEntity) object;
@Override if ((this.configPK == null && other.configPK != null) || (this.configPK != null && !this.configPK.equals(other.configPK))) {
public String toString() { return false;
return "de.muehlencord.shared.account.business.config.entity.Config[ configPK=" + configPK + " ]"; }
} return true;
}
}
@Override
public String toString() {
return "de.muehlencord.shared.account.business.config.entity.Config[ configPK=" + configPK + " ]";
}
public AccountEntity getAccount() {
return account;
}
public void setAccount(AccountEntity account) {
this.account = account;
}
public ApplicationEntity getApplication() {
return application;
}
public void setApplication(ApplicationEntity application) {
this.application = application;
}
}

View File

@ -189,7 +189,7 @@ public class MailService implements Serializable {
String resetUrlWithToken = passwordResetUrl + "?token=" + token; String resetUrlWithToken = passwordResetUrl + "?token=" + token;
model.addParameter("url", baseUrl); model.addParameter("url", baseUrl);
model.addParameter("resetUrl", resetUrlWithToken); model.addParameter("resetUrl", resetUrlWithToken);
return sendHTMLMail(account.getAccountLogin().getEmailaddress(), "Reset your password", model, "password_reset_html"); return sendHTMLMail(account.getEmailaddress(), "Reset your password", model, "password_reset_html");
} }
private String transportMail(Message message) throws MessagingException { private String transportMail(Message message) throws MessagingException {

View File

@ -37,9 +37,9 @@ public class ConfigServiceTest {
application.setApplicationName("Test App"); application.setApplicationName("Test App");
AccountEntity account = new AccountEntity(); AccountEntity account = new AccountEntity();
account.setUsername("system");
AccountLoginEntity login = new AccountLoginEntity(); AccountLoginEntity login = new AccountLoginEntity();
login.setAccount (account); login.setAccount (account);
login.setUsername("system");
account.setAccountLogin(login); account.setAccountLogin(login);
ConfigEntityPK pk = new ConfigEntityPK(application, "account.maxFailedLogins", account); ConfigEntityPK pk = new ConfigEntityPK(application, "account.maxFailedLogins", account);
@ -52,7 +52,7 @@ public class ConfigServiceTest {
@Ignore @Ignore
// TODO move to account test // TODO move to account test
public void testGetMaxFailedLogins() { public void testGetMaxFailedLogins() {
configService.init(); // configService.init();
// assertEquals ("maxFailedLogins", 7, configService.getMaxFailedLogins()); // assertEquals ("maxFailedLogins", 7, configService.getMaxFailedLogins());
} }

View File

@ -0,0 +1,22 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.muehlencord.shared.account.util;
import org.junit.Test;
/**
*
* @author Joern Muehlencord <joern at muehlencord.de>
*/
public class SecurityUtilTest {
@Test
public void testCreatePassword() {
System.out.println (SecurityUtil.createPassword("secret"));
}
}