Systém přístupových práv

multitenant
Josef Rokos 11 years ago
parent acfc0ce17e
commit bfd9371a35

@ -1,6 +1,11 @@
package info.bukova.isspst; package info.bukova.isspst;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.Role; import info.bukova.isspst.data.Role;
import info.bukova.isspst.services.BuildingService;
import info.bukova.isspst.services.addressbook.AdbService;
import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.services.users.UserService;
public class Constants { public class Constants {
@ -25,5 +30,27 @@ public class Constants {
new Role(ROLE_TECHNICIAN, "Technik"), new Role(ROLE_TECHNICIAN, "Technik"),
new Role(ROLE_LEADER, "Vedoucí"), new Role(ROLE_LEADER, "Vedoucí"),
new Role(ROLE_USER, "Uživatel") new Role(ROLE_USER, "Uživatel")
}; };
public final static String PERM_READ = "PERM_READ";
public final static String PERM_ADD = "PERM_ADD";
public final static String PERM_EDIT = "PERM_EDIT";
public final static String PERM_DELETE = "PERM_DELETE";
public final static Permission DEF_PERMISSIONS[] = {
new Permission(PERM_READ, "Číst"),
new Permission(PERM_ADD, "Přidávat"),
new Permission(PERM_EDIT, "Upravit"),
new Permission(PERM_DELETE, "Mazat")
};
public final static String MOD_USERS = "USERS";
public final static String MOD_PERMISSIONS = "PERMISSIONS";
public final static String MOD_ADDRESSBOOK = "ADDRESSBOOK";
public final static String MOD_BUILDINGS = "BUILDINGS";
public final static Module MODULES[] = {
new Module(MOD_USERS, "Uživatelé", UserService.class),
new Module(MOD_PERMISSIONS, "Práva", RoleService.class),
new Module(MOD_ADDRESSBOOK, "Dodavatelé", AdbService.class),
new Module(MOD_BUILDINGS, "Budovy", BuildingService.class)
};
} }

@ -1,7 +1,9 @@
package info.bukova.isspst; package info.bukova.isspst;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.Role; import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User; import info.bukova.isspst.data.User;
import info.bukova.isspst.services.users.PermissionService;
import info.bukova.isspst.services.users.RoleService; import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.services.users.UserService; import info.bukova.isspst.services.users.UserService;
@ -10,6 +12,8 @@ import javax.servlet.ServletContextListener;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.context.support.WebApplicationContextUtils;
@ -18,6 +22,7 @@ public class DbInitListener implements ServletContextListener {
private RoleService roleService; private RoleService roleService;
private UserService userService; private UserService userService;
private PermissionService permService;
@Override @Override
public void contextDestroyed(ServletContextEvent arg0) { public void contextDestroyed(ServletContextEvent arg0) {
@ -29,12 +34,23 @@ public class DbInitListener implements ServletContextListener {
Logger logger = LoggerFactory.getLogger(DbInitListener.class); Logger logger = LoggerFactory.getLogger(DbInitListener.class);
logger.info("Initializing database"); 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()); WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(evt.getServletContext());
roleService = ctx.getBean(RoleService.class); roleService = ctx.getBean(RoleService.class);
userService = ctx.getBean(UserService.class); userService = ctx.getBean(UserService.class);
permService = ctx.getBean(PermissionService.class);
checkRoles(); checkRoles();
checkUsers(); checkUsers();
checkPermissions();
SecurityContextHolder.getContext().setAuthentication(null);
} }
private void checkRoles() { private void checkRoles() {
@ -73,5 +89,16 @@ public class DbInitListener implements ServletContextListener {
} }
} }
} }
private void checkPermissions() {
for (Module m : Constants.MODULES) {
for (Permission p : Constants.DEF_PERMISSIONS) {
if (permService.getPermissionByModule(m.getId(), p.getAuthority()) == null) {
p.setModule(m.getId());
permService.add(p);
}
}
}
}
} }

@ -0,0 +1,55 @@
package info.bukova.isspst;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.services.Service;
import java.io.Serializable;
import java.util.List;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
public class IsspstPermissionEvaluator implements PermissionEvaluator {
@SuppressWarnings("unchecked")
@Override
public boolean hasPermission(Authentication authentication,
Object targetDomainObject, Object permission) {
List<Role> perms = (List<Role>) authentication.getAuthorities();
String moduleId = "";
String perm = "";
if (permission instanceof String) {
perm = (String) permission;
}
if (targetDomainObject instanceof Service<?>)
{
for (Module m : Constants.MODULES) {
if (m.getServiceClass().isAssignableFrom(targetDomainObject.getClass())) {
moduleId = m.getId();
}
}
perm += "_" + moduleId;
for (Role r : perms) {
if (r.getAuthority().equals(perm)) {
return true;
}
if (r.getAuthority().equals(Constants.ROLE_ADMIN)) {
return true;
}
}
}
return false;
}
@Override
public boolean hasPermission(Authentication authentication,
Serializable targetId, String targetType, Object permission) {
return false;
}
}

@ -0,0 +1,39 @@
package info.bukova.isspst;
public class Module {
private String id;
private String name;
private Class<?> serviceClass;
public Class<?> getServiceClass() {
return serviceClass;
}
public void setServiceClass(Class<?> serviceClass) {
this.serviceClass = serviceClass;
}
public Module(String id, String name, Class<?> serviceClass) {
this.id = id;
this.name = name;
this.serviceClass = serviceClass;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

@ -0,0 +1,7 @@
package info.bukova.isspst.dao;
import info.bukova.isspst.data.Permission;
public interface PermissionDao extends BaseDao<Permission> {
}

@ -0,0 +1,13 @@
package info.bukova.isspst.dao.jpa;
import info.bukova.isspst.dao.PermissionDao;
import info.bukova.isspst.data.Permission;
public class PermissionDaoJPA extends BaseDaoJPA<Permission> implements PermissionDao {
@Override
public String getEntityName() {
return Permission.class.getSimpleName();
}
}

@ -0,0 +1,69 @@
package info.bukova.isspst.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
@Entity
@Table(name="PERMISSION")
public class Permission extends BaseSimpleData implements GrantedAuthority {
/**
*
*/
private static final long serialVersionUID = 1L;
@Column(name="AUTHORITY")
private String authority;
@Column(name="DESCRIPTION")
private String description;
@Column(name="MODULE")
private String module;
public Permission(String authority, String description) {
this.authority = authority;
this.description = description;
this.module = "";
}
public Permission() {
}
@Override
public String getAuthority() {
return authority;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public void setAuthority(String authority) {
this.authority = authority;
}
@Override
public boolean equals(Object o) {
if ((o instanceof Permission) && ((Permission)o).getId() == this.getId()) {
return true;
} else {
return false;
}
}
}

@ -1,9 +1,17 @@
package info.bukova.isspst.data; package info.bukova.isspst.data;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import javax.persistence.Table;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
@Entity @Entity
@ -19,14 +27,19 @@ public class Role extends BaseSimpleData implements GrantedAuthority, DataModel
private String authority; private String authority;
@Column(name="DESCRIPTION") @Column(name="DESCRIPTION")
private String description; private String description;
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name="ROLE_PERMISSION", joinColumns={@JoinColumn(name="ROLE_ID")}, inverseJoinColumns={@JoinColumn(name="PERMISSION_ID")})
private List<Permission> permissions;
public Role(String authority, String description) { public Role(String authority, String description) {
this.authority = authority; this.authority = authority;
this.description = description; this.description = description;
this.permissions = new ArrayList<Permission>();
} }
public Role() { public Role() {
this.permissions = new ArrayList<Permission>();
} }
@Override @Override
@ -46,6 +59,18 @@ public class Role extends BaseSimpleData implements GrantedAuthority, DataModel
this.authority = authority; this.authority = authority;
} }
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
public void addPermission(Permission permission) {
this.permissions.add(permission);
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if ((o instanceof Role) && ((Role)o).getId() == this.getId()) { if ((o instanceof Role) && ((Role)o).getId() == this.getId()) {

@ -48,7 +48,26 @@ public class User extends BaseSimpleData implements UserDetails, DataModel {
@Override @Override
public List<Role> getAuthorities() { public List<Role> getAuthorities() {
return authorities; List<Role> roles = new ArrayList<Role>();
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());
for (Role chRole : roles) {
if (chRole.getAuthority().equals(role.getAuthority())) {
addRole = false;
}
}
if (addRole) {
roles.add(role);
}
}
}
return roles;
} }
@Override @Override
@ -100,6 +119,10 @@ public class User extends BaseSimpleData implements UserDetails, DataModel {
public void addAuthority(Role role) { public void addAuthority(Role role) {
this.authorities.add(role); this.authorities.add(role);
} }
public void removeAuthority(Role role) {
this.authorities.remove(role);
}
public String getFullName() { public String getFullName() {
String ret = ""; String ret = "";

@ -2,6 +2,9 @@ package info.bukova.isspst.services;
import java.util.Date; import java.util.Date;
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.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -12,6 +15,7 @@ public class AbstractOwnedService<T extends OwnedDataModel> extends AbstractServ
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_ADD')")
public void add(T entity) { public void add(T entity) {
validate(entity); validate(entity);
entity.setCreated(new Date()); entity.setCreated(new Date());
@ -21,19 +25,23 @@ public class AbstractOwnedService<T extends OwnedDataModel> extends AbstractServ
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_EDIT')")
public void update(T entity) { public void update(T entity) {
if (entity.getCreated() == null) { validate(entity);
add(entity); entity.setModifiedBy(getLoggedInUser());
} else { entity.setModified(new Date());
validate(entity); dao.modify(entity);
entity.setModifiedBy(getLoggedInUser());
entity.setModified(new Date());
dao.modify(entity);
}
} }
@Transactional
protected User getLoggedInUser() { protected User getLoggedInUser() {
return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); try {
String query = "from User where ID = " + ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
Query q = dao.getQuery(query);
return (User) q.uniqueResult();
} catch (NonUniqueResultException e) {
return null;
}
} }
} }

@ -14,6 +14,7 @@ import javax.validation.Validator;
import org.hibernate.NonUniqueResultException; import org.hibernate.NonUniqueResultException;
import org.hibernate.Query; import org.hibernate.Query;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractService<T extends DataModel> implements Service<T> { public abstract class AbstractService<T extends DataModel> implements Service<T> {
@ -25,8 +26,15 @@ public abstract class AbstractService<T extends DataModel> implements Service<T>
this.dao = dao; this.dao = dao;
} }
@Override
@PreAuthorize("hasPermission(this, 'PERM_ADD')")
public final T create() {
return createEntity();
}
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_ADD')")
public void add(T entity) { public void add(T entity) {
validate(entity); validate(entity);
entity.setCreated(new Date()); entity.setCreated(new Date());
@ -35,18 +43,16 @@ public abstract class AbstractService<T extends DataModel> implements Service<T>
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_EDIT')")
public void update(T entity) { public void update(T entity) {
if (entity.getCreated() == null) { validate(entity);
add(entity); entity.setModified(new Date());
} else { dao.modify(entity);
validate(entity);
entity.setModified(new Date());
dao.modify(entity);
}
} }
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_DELETE')")
public void delete(T entity) { public void delete(T entity) {
dao.delete(entity); dao.delete(entity);
} }
@ -80,6 +86,7 @@ public abstract class AbstractService<T extends DataModel> implements Service<T>
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_READ')")
public T getById(int id) { public T getById(int id) {
return dao.getById(id); return dao.getById(id);
@ -87,12 +94,14 @@ public abstract class AbstractService<T extends DataModel> implements Service<T>
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_READ')")
public List<T> getAll() { public List<T> getAll() {
return dao.getAll(); return dao.getAll();
} }
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_READ')")
public List<T> execQuery(String query) { public List<T> execQuery(String query) {
return dao.execQuery(query); return dao.execQuery(query);
} }
@ -100,6 +109,7 @@ public abstract class AbstractService<T extends DataModel> implements Service<T>
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
@Transactional @Transactional
@PreAuthorize("hasPermission(this, 'PERM_READ')")
public T selectSingle(String query) { public T selectSingle(String query) {
try { try {
Query q = dao.getQuery(query); Query q = dao.getQuery(query);
@ -112,5 +122,9 @@ public abstract class AbstractService<T extends DataModel> implements Service<T>
public void setValidator(Validator validator) { public void setValidator(Validator validator) {
this.validator = validator; this.validator = validator;
} }
protected T createEntity() {
return null;
}
} }

@ -6,6 +6,7 @@ import java.util.List;
public interface Service<T> { public interface Service<T> {
public T create();
public void add(T entity); public void add(T entity);
public void update(T entity); public void update(T entity);
public void delete(T entity); public void delete(T entity);

@ -0,0 +1,10 @@
package info.bukova.isspst.services.users;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.services.Service;
public interface PermissionService extends Service<Permission> {
public Permission getPermissionByModule(String moduleId, String permission);
}

@ -0,0 +1,17 @@
package info.bukova.isspst.services.users;
import org.springframework.transaction.annotation.Transactional;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.services.AbstractService;
public class PermissionServiceImpl extends AbstractService<Permission> implements PermissionService {
@Override
@Transactional
public Permission getPermissionByModule(String moduleId, String permission) {
return selectSingle("from Permission where MODULE = '" + moduleId + "' and AUTHORITY = '" + permission + "'");
}
}

@ -6,6 +6,7 @@ import info.bukova.isspst.services.ValidationException;
import java.util.Map; import java.util.Map;
import org.springframework.security.access.AccessDeniedException;
import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ExecutionArgParam; import org.zkoss.bind.annotation.ExecutionArgParam;
@ -19,11 +20,17 @@ public class FormViewModel<T extends DataModel> {
private T dataBean; private T dataBean;
private Map<String, String> errMessages; private Map<String, String> errMessages;
private Service<T> service; private Service<T> service;
private boolean newRec;
@Init @Init
public void init(@ExecutionArgParam("selected") T selected, @ExecutionArgParam("service") Service<T> service) { public void init(@ExecutionArgParam("selected") T selected, @ExecutionArgParam("service") Service<T> service) {
this.dataBean = selected; this.dataBean = selected;
this.service = service; this.service = service;
if (selected.getId() == 0 && selected.getCreated() == null) {
newRec = true;
} else {
newRec = false;
}
} }
public T getDataBean() { public T getDataBean() {
@ -34,7 +41,11 @@ public class FormViewModel<T extends DataModel> {
@NotifyChange("errMessages") @NotifyChange("errMessages")
public void save(@BindingParam("window") Window win) { public void save(@BindingParam("window") Window win) {
try { try {
doSave(); if (newRec) {
doAdd();
} else {
doSave();
}
win.detach(); win.detach();
} catch (ValidationException e) { } catch (ValidationException e) {
errMessages = e.getMessages(); errMessages = e.getMessages();
@ -45,8 +56,9 @@ public class FormViewModel<T extends DataModel> {
} }
Messagebox.show("Chyba validace", "Chyba", Messagebox.OK, Messagebox.ERROR); Messagebox.show("Chyba validace", "Chyba", Messagebox.OK, Messagebox.ERROR);
} catch (AccessDeniedException e) {
Messagebox.show("K vykobání této operace nemáte dostatečná oprávnění", "Chyba", Messagebox.OK, Messagebox.ERROR);
} catch (Exception e) { } catch (Exception e) {
dataBean.setCreated(null);
e.printStackTrace(); e.printStackTrace();
Messagebox.show("Chyba při ukládání záznamu", "Chyba", Messagebox.OK, Messagebox.ERROR); Messagebox.show("Chyba při ukládání záznamu", "Chyba", Messagebox.OK, Messagebox.ERROR);
} }
@ -64,6 +76,10 @@ public class FormViewModel<T extends DataModel> {
service.update(dataBean); service.update(dataBean);
} }
protected void doAdd() {
service.add(dataBean);
}
public boolean isCanSave() { public boolean isCanSave() {
return true; return true;
} }

@ -10,6 +10,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.AccessDeniedException;
import org.zkoss.bind.BindUtils; import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.Command;
@ -130,12 +131,17 @@ public class ListViewModel<T extends DataModel> {
public void addNew() { public void addNew() {
try { try {
newRecMode(); newRecMode();
editBean = dataClass.newInstance(); editBean = service.create();
if (dataBean == null) {
editBean = dataClass.newInstance();
}
showForm(); showForm();
} catch (InstantiationException e) { } catch (InstantiationException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} catch (AccessDeniedException e) {
Messagebox.show("K vykobání této operace nemáte dostatečná oprávnění", "Chyba", Messagebox.OK, Messagebox.ERROR);
} }
} }
@ -173,6 +179,8 @@ public class ListViewModel<T extends DataModel> {
BindUtils.postNotifyChange(null, null, ListViewModel.this, "dataBean"); BindUtils.postNotifyChange(null, null, ListViewModel.this, "dataBean");
} catch (DataIntegrityViolationException e) { } catch (DataIntegrityViolationException e) {
Messagebox.show("Chyba při mazání záznamu", "Chyba", Messagebox.OK, Messagebox.ERROR); Messagebox.show("Chyba při mazání záznamu", "Chyba", Messagebox.OK, Messagebox.ERROR);
} catch (AccessDeniedException e) {
Messagebox.show("K vykobání této operace nemáte dostatečná oprávnění", "Chyba", Messagebox.OK, Messagebox.ERROR);
} }
} }
} }

@ -0,0 +1,44 @@
package info.bukova.isspst.ui.users;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.Role;
public class PermissionCheck {
private Role role;
private Permission permission;
private boolean checked;
public PermissionCheck(Role role, Permission permission) {
this.role = role;
this.permission = permission;
if (role.getPermissions().contains(permission)) {
checked = true;
} else {
checked = false;
}
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
if (checked && !role.getPermissions().contains(permission)) {
role.addPermission(permission);
} else {
role.getPermissions().remove(permission);
}
}
}

@ -0,0 +1,34 @@
package info.bukova.isspst.ui.users;
import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.services.users.PermissionService;
import info.bukova.isspst.ui.FormViewModel;
import java.util.Arrays;
import java.util.List;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.select.annotation.WireVariable;
public class PermissionForm extends FormViewModel<Role> {
@WireVariable
private PermissionService permissionService;
private RolePermissions rolePerms;
@Init(superclass = true)
public void init() {
rolePerms = new RolePermissions(getDataBean(), permissionService.getAll());
}
public List<Module> getModules() {
return Arrays.asList(Constants.MODULES);
}
public RolePermissions getRolePerms() {
return rolePerms;
}
}

@ -0,0 +1,31 @@
package info.bukova.isspst.ui.users;
import java.util.Arrays;
import java.util.List;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.ui.ListViewModel;
public class PermissionsList extends ListViewModel<Role> {
@WireVariable
private RoleService roleService;
@Init
public void init() {
service = roleService;
dataClass = Role.class;
formZul = "permForm.zul";
}
public List<Module> getModules() {
return Arrays.asList(Constants.MODULES);
}
}

@ -36,7 +36,7 @@ public class RoleCheck {
if (checked && !user.getAuthorities().contains(role)) { if (checked && !user.getAuthorities().contains(role)) {
user.addAuthority(role); user.addAuthority(role);
} else { } else {
user.getAuthorities().remove(role); user.removeAuthority(role);
} }
} }

@ -0,0 +1,24 @@
package info.bukova.isspst.ui.users;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.Role;
import java.util.ArrayList;
import java.util.List;
public class RolePermissions {
private List<PermissionCheck> permissionChecks;
public RolePermissions(Role role, List<Permission> permissions) {
permissionChecks = new ArrayList<PermissionCheck>();
for (Permission p : permissions) {
permissionChecks.add(new PermissionCheck(role, p));
}
}
public List<PermissionCheck> getPermissionChecks() {
return permissionChecks;
}
}

@ -82,6 +82,14 @@ public class UserForm extends FormViewModel<User> {
} }
} }
@Override
protected void doAdd() {
if (!password.isEmpty()) {
userService.setPassword(getDataBean(), password);
userService.add(getDataBean());
}
}
@Override @Override
public boolean isCanSave() { public boolean isCanSave() {
return password.equals(retPasswd) && isLoginFree() && getDataBean().getUsername() != null && !getDataBean().getUsername().isEmpty(); return password.equals(retPasswd) && isLoginFree() && getDataBean().getUsername() != null && !getDataBean().getUsername().isEmpty();

@ -1,8 +1,18 @@
package info.bukova.isspst.ui.users; package info.bukova.isspst.ui.users;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init; import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.WireVariable; import org.zkoss.zk.ui.select.annotation.WireVariable;
import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User; import info.bukova.isspst.data.User;
import info.bukova.isspst.filters.UserFilter; import info.bukova.isspst.filters.UserFilter;
import info.bukova.isspst.services.users.UserService; import info.bukova.isspst.services.users.UserService;
@ -20,5 +30,46 @@ public class UsersList extends ListViewModel<User> {
formZul = "userForm.zul"; formZul = "userForm.zul";
dataFilter = new UserFilter(getFilterTemplate()); dataFilter = new UserFilter(getFilterTemplate());
} }
public List<Module> getModules() {
return Arrays.asList(Constants.MODULES);
}
@Override
@NotifyChange({"permissions", "dataBean"})
public void setDataBean(User user) {
super.setDataBean(user);
}
@Override
@GlobalCommand
@NotifyChange({"dataList", "dataBean", "permissions"})
public void refresh() {
super.refresh();
}
public List<Permission> getPermissions() {
if (getDataBean() == null) {
return null;
}
List<Permission> ret = new ArrayList<Permission>();
for (Role r : getDataBean().getAuthorities()) {
for (Permission p : r.getPermissions()) {
boolean addPerm = true;
for (Permission chPerm : ret) {
if (chPerm.getAuthority().equals(p.getAuthority())
&& chPerm.getModule().equals(p.getModule())) {
addPerm = false;
}
}
if (addPerm) {
ret.add(p);
}
}
}
return ret;
}
} }

@ -7,6 +7,7 @@
<session-factory> <session-factory>
<mapping class="info.bukova.isspst.data.User"></mapping> <mapping class="info.bukova.isspst.data.User"></mapping>
<mapping class="info.bukova.isspst.data.Role"></mapping> <mapping class="info.bukova.isspst.data.Role"></mapping>
<mapping class="info.bukova.isspst.data.Permission"></mapping>
<mapping class="info.bukova.isspst.data.BaseData"></mapping> <mapping class="info.bukova.isspst.data.BaseData"></mapping>
<mapping class="info.bukova.isspst.data.Address"></mapping> <mapping class="info.bukova.isspst.data.Address"></mapping>
<mapping class="info.bukova.isspst.data.Building"></mapping> <mapping class="info.bukova.isspst.data.Building"></mapping>

@ -1,5 +1,5 @@
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://127.0.0.1:3306/isspst jdbc.databaseurl=jdbc:mysql://127.0.0.1:3306/isspst?characterEncoding=utf8
jdbc.username=root jdbc.username=root
jdbc.password=xsacfgd jdbc.password=xsacfgd

@ -50,11 +50,23 @@
</bean> </bean>
<!-- Security --> <!-- Security -->
<security:global-method-security secured-annotations="enabled" /> <security:global-method-security pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler" />
</security:global-method-security>
<bean id="expressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="permissionEvaluator" />
</bean>
<bean id="permissionEvaluator" class="info.bukova.isspst.IsspstPermissionEvaluator"/>
<security:http auto-config="true"> <security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/app/**" access="ROLE_USER, ROLE_ADMIN"/> <security:intercept-url pattern="/app/**" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')"/>
<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN"/> <security:intercept-url pattern="/admin/users/**" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/admin/permissions/**" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/admin/addressbook/**" access="hasRole('PERM_READ_ADDRESSBOOK')"/>
<security:form-login login-page="/login.zhtml" <security:form-login login-page="/login.zhtml"
authentication-failure-handler-ref="loginFail"/> authentication-failure-handler-ref="loginFail"/>
<security:http-basic/> <security:http-basic/>
@ -96,6 +108,10 @@
<property name="sessionFactory" ref="sessionFactory"/> <property name="sessionFactory" ref="sessionFactory"/>
</bean> </bean>
<bean id="permissionDao" class="info.bukova.isspst.dao.jpa.PermissionDaoJPA">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Business logic --> <!-- Business logic -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
@ -137,5 +153,9 @@
<bean id="unmarshallerAres" class="org.castor.spring.xml.CastorUnmarshallerFactoryBean"> <bean id="unmarshallerAres" class="org.castor.spring.xml.CastorUnmarshallerFactoryBean">
<property name="xmlContext" ref="xmlCtxAres"/> <property name="xmlContext" ref="xmlCtxAres"/>
</bean> </bean>
<bean id="permissionService" class="info.bukova.isspst.services.users.PermissionServiceImpl">
<property name="dao" ref="permissionDao"/>
</bean>
</beans> </beans>

@ -0,0 +1,10 @@
<?page title="Uživatelé" contentType="text/html;charset=UTF-8"?>
<zk>
<zscript>
String gridZul = "permissions.zul";
</zscript>
<include src="../../app/template.zhtml"/>
</zk>

@ -0,0 +1,24 @@
<?page title="Uživatel" contentType="text/html;charset=UTF-8"?>
<zk>
<window id="editWin" title="Uživatel" border="normal" closable="true" width="550px" apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('info.bukova.isspst.ui.users.PermissionForm')">
<style src="/app/form.css"/>
<label value="@load(vm.dataBean.description)" style="font-weight: bold;"/>
<vbox children="@load(vm.modules)" width="530px">
<template name="children" var="module">
<groupbox closable="false" mold="3d" width="530px">
<caption label="@load(module.name)"/>
<hbox children="@load(vm.rolePerms.permissionChecks)">
<template name="children" var="perm">
<checkbox label="@load(perm.permission.description)" checked="@bind(perm.checked)" visible="@load(perm.permission.module eq module.id)"/>
</template>
</hbox>
</groupbox>
</template>
</vbox>
<include src="/app/formButtons.zul"/>
</window>
</zk>

@ -0,0 +1,42 @@
<?page title="Práva" contentType="text/html;charset=UTF-8"?>
<zk>
<?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?>
<window title="Práva" border="normal" apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('info.bukova.isspst.ui.users.PermissionsList')" height="570px">
<toolbar>
<toolbarbutton image="/img/edit.png" tooltiptext="Upravit" id="btnEdit" onClick="@command('edit')" disabled="@load(empty vm.dataBean ? 'true' : 'false')"/>
</toolbar>
<hbox width="100%">
<listbox model="@load(vm.dataList)" selectedItem="@bind(vm.dataBean)" width="300px">
<listhead>
<listheader label="Role"/>
</listhead>
<template name="model">
<listitem>
<listcell label="@load(each.description)"/>
</listitem>
</template>
</listbox>
<panel hflex="1" height="480px">
<panelchildren style="overflow:auto;">
<label value="Práva modulů:" style="font-weight: bold;"/>
<vbox children="@load(vm.modules)" hflex="1">
<template name="children" var="module">
<groupbox closable="false" mold="3d" hflex="1">
<caption label="@load(module.name)"/>
<hbox children="@load(vm.dataBean.permissions)">
<template name="children" var="perm">
<label value="@load(perm.description.concat(', '))" visible="@load(module.id eq perm.module)"/>
</template>
</hbox>
</groupbox>
</template>
</vbox>
</panelchildren>
</panel>
</hbox>
</window>
</zk>

@ -5,8 +5,9 @@
viewModel="@id('vm') @init('info.bukova.isspst.ui.users.UsersList')" height="570px"> viewModel="@id('vm') @init('info.bukova.isspst.ui.users.UsersList')" height="570px">
<include src="/app/toolbar.zul"/> <include src="/app/toolbar.zul"/>
<listbox model="@load(vm.dataList)" selectedItem="@bind(vm.dataBean)"> <hbox width="100%" height="500px">
<listbox model="@load(vm.dataList)" selectedItem="@bind(vm.dataBean)" width="650px" height="480px">
<auxhead sclass="category-center" visible="@load(vm.filter)"> <auxhead sclass="category-center" visible="@load(vm.filter)">
<auxheader> <auxheader>
<image src="/img/funnel.png" /> <image src="/img/funnel.png" />
@ -40,6 +41,26 @@
</listitem> </listitem>
</template> </template>
</listbox> </listbox>
<panel hflex="1" height="480px" width="70%">
<panelchildren style="overflow:auto;">
<label value="Efektivní práva:" style="font-weight: bold;"/>
<vbox children="@load(vm.modules)" hflex="1">
<template name="children" var="module">
<groupbox closable="false" mold="3d" hflex="1">
<caption label="@load(module.name)"/>
<hbox children="@load(vm.permissions)">
<template name="children" var="perm">
<label value="@load(perm.description.concat(', '))" visible="@load(module.id eq perm.module)"/>
</template>
</hbox>
</groupbox>
</template>
</vbox>
</panelchildren>
</panel>
</hbox>
</window> </window>
</zk> </zk>

@ -27,11 +27,12 @@
</tabpanel> </tabpanel>
<tabpanel> <tabpanel>
<menubar orient="vertical"> <menubar orient="vertical">
<menuitem label="Uživatelé" href="/admin/users" width="120px"/> <menuitem label="Uživatelé" href="/admin/users" disabled="${not sec:isAllGranted('ROLE_ADMIN')}" width="120px"/>
<menuitem label="Práva" href="/admin/permissions" disabled="${not sec:isAllGranted('ROLE_ADMIN')}"/>
<menuitem label="Střediska" href="/admin/users" disabled="${not sec:isAllGranted('ROLE_ADMIN')}"/> <menuitem label="Střediska" href="/admin/users" disabled="${not sec:isAllGranted('ROLE_ADMIN')}"/>
<menuitem label="${labels.AgendaBuildings}" href="/buildings"/> <menuitem label="${labels.AgendaBuildings}" href="/buildings" disabled="${not sec:isAllGranted('PERM_READ_BUILDINGS')}"/>
<menuitem label="Místnosti" href="/admin/users"/> <menuitem label="Místnosti" href="/admin/users"/>
<menuitem label="Dodavatelé" href="/admin/addressbook"/> <menuitem label="Dodavatelé" href="/admin/addressbook" disabled="${not sec:isAllGranted('PERM_READ_ADDRESSBOOK')}"/>
</menubar> </menubar>
</tabpanel> </tabpanel>
<tabpanel> <tabpanel>

Loading…
Cancel
Save