multitenant
František Přibyl 11 years ago
commit 3ad8cfbe3f

@ -70,6 +70,21 @@
<artifactId>spring-security-config</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- testing LDAP server
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-all</artifactId>
<version>1.5.5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>-->
<!-- <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
@ -91,6 +106,13 @@
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
@ -106,7 +128,7 @@
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
</dependency> -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
@ -204,6 +226,12 @@
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>${zk.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>

@ -12,8 +12,6 @@ import javax.servlet.ServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
@ -34,23 +32,16 @@ public class DbInitListener implements ServletContextListener {
Logger logger = LoggerFactory.getLogger(DbInitListener.class);
logger.info("Initializing database");
User tmpAdmin = new User();
Role tmpRole = new Role();
tmpRole.setAuthority(Constants.ROLE_ADMIN);
tmpAdmin.setUsername(Constants.DEF_ADMIN);
tmpAdmin.addAuthority(tmpRole);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(tmpAdmin, null, tmpAdmin.getAuthorities()));
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(evt.getServletContext());
roleService = ctx.getBean(RoleService.class);
userService = ctx.getBean(UserService.class);
permService = ctx.getBean(PermissionService.class);
userService.grantAdmin();
checkRoles();
checkUsers();
checkPermissions();
SecurityContextHolder.getContext().setAuthentication(null);
userService.removeAccess();
}
private void checkRoles() {

@ -49,12 +49,15 @@ public class User extends BaseSimpleData implements UserDetails, DataModel {
@Override
public List<Role> getAuthorities() {
List<Role> roles = new ArrayList<Role>();
int i = 10000000;
for (Role r : authorities) {
roles.add(r);
for (Permission p : r.getPermissions()) {
Role role = new Role();
boolean addRole = true;
role.setAuthority(p.getAuthority() + "_" + p.getModule());
role.setId(i);
++i;
for (Role chRole : roles) {
if (chRole.getAuthority().equals(role.getAuthority())) {

@ -0,0 +1,76 @@
package info.bukova.isspst.security;
import info.bukova.isspst.Constants;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User;
import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.services.users.UserService;
import java.util.Collection;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
public class AuthPopulator implements LdapAuthoritiesPopulator {
private UserService userService;
private RoleService roleService;
public AuthPopulator(UserService userService, RoleService roleService) {
this.userService = userService;
this.roleService = roleService;
}
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(
DirContextOperations userData, String login) {
User user = null;
try {
user = (User) userService.loadUserByUsername(login);
} catch (UsernameNotFoundException e) {
Logger logger = LoggerFactory.getLogger(AuthPopulator.class);
logger.info("Importing user from LDAP");
user = new User();
user.setUsername(login);
Role role = roleService.getRoleByAuthority(Constants.ROLE_USER);
user.addAuthority(role);
if (userData.attributeExists("givenName")) {
try {
user.setFirstName(userData.getAttributes().get("givenName").get().toString());
} catch (NamingException e1) {
logger.info("LDAP object has no 'givenName' attribute");
}
}
if (userData.attributeExists("sn")) {
try {
user.setLastName(userData.getAttributes().get("sn").get().toString());
} catch (NamingException e1) {
logger.info("LDAP object has no 'sn' attribute");
}
}
if (userData.attributeExists("mail")) {
try {
user.setEmail(userData.getAttributes().get("mail").get().toString());
} catch (NamingException e1) {
logger.info("LDAP object has no 'mail' attribute");
}
}
userService.grantAdmin();
userService.add(user);
userService.removeAccess();
}
return user != null ? user.getAuthorities() : null;
}
}

@ -1,5 +1,7 @@
package info.bukova.isspst;
package info.bukova.isspst.security;
import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.services.Service;

@ -1,4 +1,4 @@
package info.bukova.isspst;
package info.bukova.isspst.security;
import java.io.IOException;

@ -6,6 +6,7 @@ import org.hibernate.NonUniqueResultException;
import org.hibernate.Query;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import info.bukova.isspst.data.OwnedDataModel;
@ -36,7 +37,7 @@ public class AbstractOwnedService<T extends OwnedDataModel> extends AbstractServ
@Transactional
protected User getLoggedInUser() {
try {
String query = "from User where ID = " + ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
String query = "from User where USERNAME = '" + ((UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername() + "'";
Query q = dao.getQuery(query);
return (User) q.uniqueResult();
} catch (NonUniqueResultException e) {

@ -12,5 +12,7 @@ public interface UserService extends UserDetailsService, Service<User> {
public void saveWithPwd(User user, String password);
public User getCurrent();
public String encodePassword(User user, String plain);
public void grantAdmin();
public void removeAccess();
}

@ -1,6 +1,7 @@
package info.bukova.isspst.services.users;
import org.hibernate.Query;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@ -8,6 +9,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import info.bukova.isspst.Constants;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User;
import info.bukova.isspst.services.AbstractService;
@ -58,11 +60,16 @@ public class UserServiceImpl extends AbstractService<User> implements UserServic
}
@Override
@Transactional
public User getCurrent() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getPrincipal() != null) {
return (User)auth.getPrincipal();
try {
return (User)loadUserByUsername(((UserDetails)auth.getPrincipal()).getUsername());
} catch(UsernameNotFoundException e) {
return null;
}
}
return null;
@ -73,5 +80,20 @@ public class UserServiceImpl extends AbstractService<User> implements UserServic
return encoder.encodePassword(plain, user.getUsername());
}
@Override
public void grantAdmin() {
User tmpAdmin = new User();
Role tmpRole = new Role();
tmpRole.setAuthority(Constants.ROLE_ADMIN);
tmpAdmin.setUsername(Constants.DEF_ADMIN);
tmpAdmin.addAuthority(tmpRole);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(tmpAdmin, null, tmpAdmin.getAuthorities()));
}
@Override
public void removeAccess() {
SecurityContextHolder.getContext().setAuthentication(null);
}
}

@ -21,11 +21,15 @@ public class FormViewModel<T extends DataModel> {
private Map<String, String> errMessages;
private Service<T> service;
private boolean newRec;
private ServiceConstraint<T> constraint;
@Init
public void init(@ExecutionArgParam("selected") T selected, @ExecutionArgParam("service") Service<T> service) {
this.dataBean = selected;
this.service = service;
constraint = new ServiceConstraint<T>();
constraint.setDataBean(selected);
constraint.setService(service);
if (selected.getId() == 0 && selected.getCreated() == null) {
newRec = true;
} else {
@ -33,6 +37,10 @@ public class FormViewModel<T extends DataModel> {
}
}
public ServiceConstraint<T> getConstriant() {
return constraint;
}
public T getDataBean() {
return dataBean;
}

@ -131,7 +131,7 @@ public class ListViewModel<T extends DataModel> {
try {
newRecMode();
editBean = service.create();
if (dataBean == null) {
if (editBean == null) {
editBean = dataClass.newInstance();
}
showForm();

@ -0,0 +1,54 @@
package info.bukova.isspst.ui;
import info.bukova.isspst.data.DataModel;
import info.bukova.isspst.services.Service;
import info.bukova.isspst.services.ValidationException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Constraint;
public class ServiceConstraint<T extends DataModel> implements Constraint {
private Service<T> service;
private T dataBean;
@Override
public void validate(Component component, Object value)
throws WrongValueException {
String id = component.getId();
if (id == null || id.isEmpty()) {
return;
}
try {
BeanUtils.setProperty(dataBean, id, value);
service.validate(dataBean);
} catch (ValidationException e) {
Map<String, String> errMessages = e.getMessages();
if (errMessages != null && errMessages.get(id) != null && !errMessages.get(id).isEmpty()) {
WrongValueException ex = new WrongValueException(component, errMessages.get(id));
throw ex;
}
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
public void setService(Service<T> service) {
this.service = service;
}
public void setDataBean(T dataBean) {
this.dataBean = dataBean;
}
}

@ -0,0 +1,71 @@
dn: ou=groups,dc=bukova,dc=info
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=bukova,dc=info
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=kadel,ou=people,dc=bukova,dc=info
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Kadel Pohlavnik
sn: Pohlavnik
givenName: Kadel
uid: kadel
userPassword: pokus
dn: uid=admin,ou=people,dc=bukova,dc=info
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Administrator
sn: admin
uid: admin
userPassword: xsacfgd
dn: uid=dianne,ou=people,dc=bukova,dc=info
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Dianne Emu
sn: Emu
uid: dianne
userPassword: emu
dn: uid=scott,ou=people,dc=bukova,dc=info
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Scott
sn: Wombat
uid: scott
userPassword: wombat
dn: cn=user,ou=groups,dc=bukova,dc=info
objectclass: top
objectclass: groupOfNames
cn: user
member: uid=rod,ou=people,dc=bukova,dc=info
member: uid=dianne,ou=people,dc=bukova,dc=info
member: uid=scott,ou=people,dc=bukova,dc=info
dn: cn=teller,ou=groups,dc=bukova,dc=info
objectclass: top
objectclass: groupOfNames
cn: teller
member: uid=rod,ou=people,dc=bukova,dc=info
member: dianne=rod,ou=people,dc=bukova,dc=info
dn: cn=supervisor,ou=groups,dc=bukova,dc=info
objectclass: top
objectclass: groupOfNames
cn: supervisor
member: uid=rod,ou=people,dc=bukova,dc=info

@ -0,0 +1,2 @@
ldap.server=ldap://localhost:3089
ldap.userDNPattern=uid=\{0\},OU=people,DC=bukova,DC=info

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<security:password-encoder ref="passwordEncoder">
<security:salt-source user-property="username" />
</security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
</beans>

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- LDAP -->
<!-- embedded server only for testing -->
<security:ldap-server root="dc=bukova,dc=info" ldif="classpath:users.ldif" port="3089"/>
<security:authentication-manager>
<security:authentication-provider ref="ldapAuthProvider"/>
</security:authentication-manager>
<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="${ldap.server}"/>
</bean>
<bean id="authenticator" class="org.springframework.security.ldap.authentication.BindAuthenticator">
<constructor-arg ref="contextSource"/>
<property name="userDnPatterns">
<list>
<value>${ldap.userDNPattern}</value>
</list>
</property>
</bean>
<bean id="populator" class="info.bukova.isspst.security.AuthPopulator">
<constructor-arg>
<ref local="userService"/>
</constructor-arg>
<constructor-arg>
<ref local="roleService"/>
</constructor-arg>
</bean>
<bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<constructor-arg ref="authenticator"/>
<constructor-arg ref="populator"/>
</bean>
</beans>

@ -11,7 +11,14 @@
<context:annotation-config />
<context:component-scan base-package="info.bukova.isspst,org.zkoss.spring.beans.zkcomponents"></context:component-scan>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="propertyConfigurer" p:location="/WEB-INF/jdbc.properties" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="propertyConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
<value>/WEB-INF/ldap.properties</value>
</list>
</property>
</bean>
<!-- Database -->
<bean id="dataSource"
@ -52,7 +59,7 @@
<property name="permissionEvaluator" ref="permissionEvaluator" />
</bean>
<bean id="permissionEvaluator" class="info.bukova.isspst.IsspstPermissionEvaluator"/>
<bean id="permissionEvaluator" class="info.bukova.isspst.security.IsspstPermissionEvaluator"/>
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/app/**" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')"/>
@ -65,13 +72,8 @@
<security:logout invalidate-session="true"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<security:password-encoder ref="passwordEncoder">
<security:salt-source user-property="username" />
</security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
<import resource="database-auth.xml"/>
<!-- <import resource="ldap-auth.xml"/> -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.springframework.security.core.context.SecurityContextHolder" />
@ -81,7 +83,7 @@
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"/>
<bean id="loginFail" class="info.bukova.isspst.LoginFailHandler"/>
<bean id="loginFail" class="info.bukova.isspst.security.LoginFailHandler"/>
<!-- DAO -->
<bean id="userDao" class="info.bukova.isspst.dao.jpa.UserDaoJPA">

@ -12,12 +12,10 @@
<column label="" hflex="min"/>
<column label="" hflex="min"/>
<column label=""/>
<column label=""/>
</columns>
<rows>
<row>
<label value="Firma" /> <textbox value="@bind(vm.dataBean.company)" instant="true"/>
<label visible="true" value="@load(vm.errMessages['company'])" style="color:red"/>
<label value="Firma" /> <textbox id="company" constraint="@load(vm.constriant)" value="@bind(vm.dataBean.company)" instant="true" width="320px"/>
<button image="/img/search.png" label="Hledat v ARESu" onClick="@command('searchAres')" sclass="nicebutton" disabled="@load((vm.dataBean.ic == 0) &amp;&amp; (empty vm.dataBean.company))" />
</row>
<row>
@ -33,14 +31,13 @@
<label value="Kontaktní osoba" /> <textbox value="@bind(vm.dataBean.contactName)"/>
</row>
<row>
<label value="Ulice" /> <textbox value="@bind(vm.dataBean.street)"/>
<label value="Ulice" /> <textbox value="@bind(vm.dataBean.street)" width="320px"/>
</row>
<row>
<label value="Číslo domu" /> <textbox value="@bind(vm.dataBean.houseNumber)"/>
<label value="Číslo domu" /> <textbox value="@bind(vm.dataBean.houseNumber)" width="80px"/>
</row>
<row>
<label value="Město" /> <textbox value="@bind(vm.dataBean.city)"/>
<label visible="true" value="@load(vm.errMessages['city'])" style="color:red"/>
<label value="Město" /> <textbox id="city" constraint="@load(vm.constriant)" value="@bind(vm.dataBean.city)" width="320px"/>
</row>
<row>
<label value="PSČ" /> <textbox value="@bind(vm.dataBean.zipCode)"/>
@ -49,12 +46,10 @@
<label value="Telefon" /> <textbox value="@bind(vm.dataBean.phone)"/>
</row>
<row>
<label value="E-mail" /> <textbox value="@bind(vm.dataBean.email)"/>
<label visible="true" value="@load(vm.errMessages['email'])" style="color:red"/>
<label value="E-mail" /> <textbox id="email" constraint="@load(vm.constriant)" value="@bind(vm.dataBean.email)" width="320px"/>
</row>
<row>
<label value="Web" /> <textbox value="@bind(vm.dataBean.web)"/>
<label visible="true" value="@load(vm.errMessages['web'])" style="color:red"/>
<label value="Web" /> <textbox id="web" constraint="@load(vm.constriant)" value="@bind(vm.dataBean.web)" width="320px"/>
</row>
</rows>
</grid>

@ -2,9 +2,10 @@
<zk>
<?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?>
<window id="passwd" title="Změnit heslo" border="normal" closable="true" width="350px"
<window id="passwd" border="normal" closable="true" width="350px"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('info.bukova.isspst.ui.users.PasswdVM')">
<caption src="/img/passwd.png" zclass="form-caption" label="Změnit heslo" />
<style src="/app/form.css"/>
<grid>
<columns>

@ -8,16 +8,12 @@
<columns>
<column align="right" hflex="min" />
<column />
<column />
</columns>
<rows>
<row>
<cell sclass="row-title">${labels.BuildingsFormCode} :</cell>
<cell>
<textbox width="200px" value="@bind(vm.dataBean.code)" />
</cell>
<cell>
<label visible="true" value="@load(vm.errMessages['code'])" style="color:red" />
<textbox id="code" constraint="@load(vm.constriant)" width="200px" value="@bind(vm.dataBean.code)" />
</cell>
</row>
<row>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Loading…
Cancel
Save