Commit cbd04c10 by Tuomas Riihimäki

Heavy refactoring on authorisation.

1 parent 3509774c
Showing with 424 additions and 190 deletions
...@@ -12,7 +12,7 @@ package fi.insomnia.bortal.beans { ...@@ -12,7 +12,7 @@ package fi.insomnia.bortal.beans {
import flash.utils.IExternalizable; import flash.utils.IExternalizable;
[Bindable] [Bindable]
public class BillLineBeanBase implements IExternalizable, BillLineBeanLocal { public class BillLineBeanBase implements IExternalizable {
public function readExternal(input:IDataInput):void { public function readExternal(input:IDataInput):void {
......
...@@ -16,13 +16,16 @@ package fi.insomnia.bortal.beans { ...@@ -16,13 +16,16 @@ package fi.insomnia.bortal.beans {
public class PlaceBeanBase implements IExternalizable { public class PlaceBeanBase implements IExternalizable {
private var _placeFacade:PlaceFacade; private var _placeFacade:PlaceFacade;
private var _userbean:UserBeanLocal;
public function readExternal(input:IDataInput):void { public function readExternal(input:IDataInput):void {
_placeFacade = input.readObject() as PlaceFacade; _placeFacade = input.readObject() as PlaceFacade;
_userbean = input.readObject() as UserBeanLocal;
} }
public function writeExternal(output:IDataOutput):void { public function writeExternal(output:IDataOutput):void {
output.writeObject(_placeFacade); output.writeObject(_placeFacade);
output.writeObject(_userbean);
} }
} }
} }
\ No newline at end of file
...@@ -17,15 +17,18 @@ package fi.insomnia.bortal.beans { ...@@ -17,15 +17,18 @@ package fi.insomnia.bortal.beans {
private var _eventBean:EventBeanLocal; private var _eventBean:EventBeanLocal;
private var _productFacade:ProductFacade; private var _productFacade:ProductFacade;
private var _userbean:UserBeanLocal;
public function readExternal(input:IDataInput):void { public function readExternal(input:IDataInput):void {
_eventBean = input.readObject() as EventBeanLocal; _eventBean = input.readObject() as EventBeanLocal;
_productFacade = input.readObject() as ProductFacade; _productFacade = input.readObject() as ProductFacade;
_userbean = input.readObject() as UserBeanLocal;
} }
public function writeExternal(output:IDataOutput):void { public function writeExternal(output:IDataOutput):void {
output.writeObject(_eventBean); output.writeObject(_eventBean);
output.writeObject(_productFacade); output.writeObject(_productFacade);
output.writeObject(_userbean);
} }
} }
} }
\ No newline at end of file
...@@ -21,12 +21,14 @@ package fi.insomnia.bortal.beans { ...@@ -21,12 +21,14 @@ package fi.insomnia.bortal.beans {
private var _eventBean:EventBeanLocal; private var _eventBean:EventBeanLocal;
private var _roleFacade:RoleFacade; private var _roleFacade:RoleFacade;
private var _rrfacade:RoleRightFacade; private var _rrfacade:RoleRightFacade;
private var _userbean:UserBeanLocal;
public function readExternal(input:IDataInput):void { public function readExternal(input:IDataInput):void {
_accessRightFacade = input.readObject() as AccessRightFacade; _accessRightFacade = input.readObject() as AccessRightFacade;
_eventBean = input.readObject() as EventBeanLocal; _eventBean = input.readObject() as EventBeanLocal;
_roleFacade = input.readObject() as RoleFacade; _roleFacade = input.readObject() as RoleFacade;
_rrfacade = input.readObject() as RoleRightFacade; _rrfacade = input.readObject() as RoleRightFacade;
_userbean = input.readObject() as UserBeanLocal;
} }
public function writeExternal(output:IDataOutput):void { public function writeExternal(output:IDataOutput):void {
...@@ -34,6 +36,7 @@ package fi.insomnia.bortal.beans { ...@@ -34,6 +36,7 @@ package fi.insomnia.bortal.beans {
output.writeObject(_eventBean); output.writeObject(_eventBean);
output.writeObject(_roleFacade); output.writeObject(_roleFacade);
output.writeObject(_rrfacade); output.writeObject(_rrfacade);
output.writeObject(_userbean);
} }
} }
} }
\ No newline at end of file
...@@ -12,25 +12,37 @@ package fi.insomnia.bortal.beans { ...@@ -12,25 +12,37 @@ package fi.insomnia.bortal.beans {
import flash.utils.IDataInput; import flash.utils.IDataInput;
import flash.utils.IDataOutput; import flash.utils.IDataOutput;
import flash.utils.IExternalizable; import flash.utils.IExternalizable;
import javax.ejb.EJBContext;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
import org.slf4j.Logger; import org.slf4j.Logger;
[Bindable] [Bindable]
public class SecurityBeanBase implements IExternalizable { public class SecurityBeanBase implements IExternalizable {
private var _context:EJBContext;
private var _entryFacade:LogEntryFacade; private var _entryFacade:LogEntryFacade;
private var _logger:Logger; private var _logger:Logger;
private var _manager:EntityManager;
private var _typeFacade:LogEntryTypeFacade; private var _typeFacade:LogEntryTypeFacade;
protected var _utx:UserTransaction;
public function readExternal(input:IDataInput):void { public function readExternal(input:IDataInput):void {
_context = input.readObject() as EJBContext;
_entryFacade = input.readObject() as LogEntryFacade; _entryFacade = input.readObject() as LogEntryFacade;
_logger = input.readObject() as Logger; _logger = input.readObject() as Logger;
_manager = input.readObject() as EntityManager;
_typeFacade = input.readObject() as LogEntryTypeFacade; _typeFacade = input.readObject() as LogEntryTypeFacade;
_utx = input.readObject() as UserTransaction;
} }
public function writeExternal(output:IDataOutput):void { public function writeExternal(output:IDataOutput):void {
output.writeObject(_context);
output.writeObject(_entryFacade); output.writeObject(_entryFacade);
output.writeObject(_logger); output.writeObject(_logger);
output.writeObject(_manager);
output.writeObject(_typeFacade); output.writeObject(_typeFacade);
output.writeObject(_utx);
} }
} }
} }
\ No newline at end of file
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
package fi.insomnia.bortal.beans { package fi.insomnia.bortal.beans {
import fi.insomnia.bortal.facade.AccessRightFacade; import fi.insomnia.bortal.facade.AccessRightFacade;
import fi.insomnia.bortal.facade.RoleFacade;
import fi.insomnia.bortal.facade.RoleRightFacade;
import fi.insomnia.bortal.facade.UserFacade; import fi.insomnia.bortal.facade.UserFacade;
import flash.utils.IDataInput; import flash.utils.IDataInput;
import flash.utils.IDataOutput; import flash.utils.IDataOutput;
...@@ -21,6 +23,8 @@ package fi.insomnia.bortal.beans { ...@@ -21,6 +23,8 @@ package fi.insomnia.bortal.beans {
private var _context:SessionContext; private var _context:SessionContext;
private var _eventBean:EventBeanLocal; private var _eventBean:EventBeanLocal;
private var _rolebean:RoleBeanLocal; private var _rolebean:RoleBeanLocal;
private var _rolefacade:RoleFacade;
private var _rrfacade:RoleRightFacade;
private var _secubean:SecurityBeanLocal; private var _secubean:SecurityBeanLocal;
private var _userFacade:UserFacade; private var _userFacade:UserFacade;
...@@ -29,6 +33,8 @@ package fi.insomnia.bortal.beans { ...@@ -29,6 +33,8 @@ package fi.insomnia.bortal.beans {
_context = input.readObject() as SessionContext; _context = input.readObject() as SessionContext;
_eventBean = input.readObject() as EventBeanLocal; _eventBean = input.readObject() as EventBeanLocal;
_rolebean = input.readObject() as RoleBeanLocal; _rolebean = input.readObject() as RoleBeanLocal;
_rolefacade = input.readObject() as RoleFacade;
_rrfacade = input.readObject() as RoleRightFacade;
_secubean = input.readObject() as SecurityBeanLocal; _secubean = input.readObject() as SecurityBeanLocal;
_userFacade = input.readObject() as UserFacade; _userFacade = input.readObject() as UserFacade;
} }
...@@ -38,6 +44,8 @@ package fi.insomnia.bortal.beans { ...@@ -38,6 +44,8 @@ package fi.insomnia.bortal.beans {
output.writeObject(_context); output.writeObject(_context);
output.writeObject(_eventBean); output.writeObject(_eventBean);
output.writeObject(_rolebean); output.writeObject(_rolebean);
output.writeObject(_rolefacade);
output.writeObject(_rrfacade);
output.writeObject(_secubean); output.writeObject(_secubean);
output.writeObject(_userFacade); output.writeObject(_userFacade);
} }
......
...@@ -97,11 +97,11 @@ public class BillBean implements BillBeanLocal { ...@@ -97,11 +97,11 @@ public class BillBean implements BillBeanLocal {
@Override @Override
public Bill createEmptyBill(User shoppingUser) { public Bill createEmptyBill(User shoppingUser) {
if (shoppingUser != null && userBean.hasCurrentUserPermission(Permission.USER_MANAGEMENT, RolePermission.EXECUTE)) { if (shoppingUser != null && !userBean.isCurrentUser(shoppingUser)) {
String msg = new StringBuilder("User tried to shop to ").append(shoppingUser.getId()).append(" another without sufficient rights").toString(); userBean.fatalPermission(Permission.USER_MANAGEMENT, RolePermission.EXECUTE, "User tried to shop to ", shoppingUser, " another without sufficient rights");
throw new PermissionDeniedException(secubean, userBean.getCurrentUser(), msg);
} }
if (shoppingUser == null) { if (shoppingUser == null) {
shoppingUser = userBean.getCurrentUser(); shoppingUser = userBean.getCurrentUser();
} }
...@@ -114,10 +114,10 @@ public class BillBean implements BillBeanLocal { ...@@ -114,10 +114,10 @@ public class BillBean implements BillBeanLocal {
@Override @Override
public BillLine addProductToBill(Bill bill, Product product, BigDecimal count) { public BillLine addProductToBill(Bill bill, Product product, BigDecimal count) {
// TODO: Lähetettyä laskua ei saa kaikki muokata! // If bill number > 0 bill has been sent and extra privileges are needed to modify.
// TODO: Jos ei olla tekemässä omaa laskua tarkistetaan onko riittävät if (!userBean.isCurrentUser(bill.getUser()) || bill.getBillNumber() > 0) {
// oikeudet. userBean.fatalPermission(Permission.USER_MANAGEMENT, RolePermission.EXECUTE, "User tried to modify bill ", bill, "without sufficient permissions");
}
BillLine line = new BillLine(bill, product.getName(), product.getUnitName(), count, product.getPrice(), product.getVat()); BillLine line = new BillLine(bill, product.getName(), product.getUnitName(), count, product.getPrice(), product.getVat());
billLineFacade.create(line); billLineFacade.create(line);
return line; return line;
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
*/ */
package fi.insomnia.bortal.beans; package fi.insomnia.bortal.beans;
import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.facade.PlaceFacade; import fi.insomnia.bortal.facade.PlaceFacade;
import fi.insomnia.bortal.model.Place; import fi.insomnia.bortal.model.Place;
import javax.ejb.EJB; import javax.ejb.EJB;
...@@ -19,7 +21,11 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -19,7 +21,11 @@ public class PlaceBean implements PlaceBeanLocal {
@EJB @EJB
private PlaceFacade placeFacade; private PlaceFacade placeFacade;
@EJB
private UserBeanLocal userbean;
public Place mergeChanges(Place place) { public Place mergeChanges(Place place) {
userbean.fatalPermission(Permission.TICKET_SALES, RolePermission.EXECUTE, "User tried to modify place ", place);
return placeFacade.merge(place); return placeFacade.merge(place);
} }
} }
...@@ -54,9 +54,7 @@ public class PlaceMapBean implements PlaceMapBeanLocal { ...@@ -54,9 +54,7 @@ public class PlaceMapBean implements PlaceMapBeanLocal {
public void printPlaceMapToStream(OutputStream outputStream, String filetype, Integer mapId, List<Integer> placeIds) throws IOException { public void printPlaceMapToStream(OutputStream outputStream, String filetype, Integer mapId, List<Integer> placeIds) throws IOException {
User user = userbean.getCurrentUser(); User user = userbean.getCurrentUser();
if (!userbean.hasPermission(Permission.TICKET_SALES, RolePermission.READ)) { userbean.fatalPermission(Permission.TICKET_SALES, RolePermission.READ, "User tried to print the placemap to Stream");
throw new PermissionDeniedException(secubean, user, "User has no right to view placemap ( TICKET_SALES, READ )");
}
long begin = new Date().getTime(); long begin = new Date().getTime();
Integer eventId = eventbean.getCurrentEvent().getId(); Integer eventId = eventbean.getCurrentEvent().getId();
......
...@@ -7,6 +7,8 @@ import javax.annotation.security.RolesAllowed; ...@@ -7,6 +7,8 @@ import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.facade.ProductFacade; import fi.insomnia.bortal.facade.ProductFacade;
import fi.insomnia.bortal.model.Product; import fi.insomnia.bortal.model.Product;
...@@ -21,6 +23,8 @@ public class ProductBean implements ProductBeanLocal { ...@@ -21,6 +23,8 @@ public class ProductBean implements ProductBeanLocal {
@EJB @EJB
private EventBeanLocal eventBean; private EventBeanLocal eventBean;
@EJB
private UserBeanLocal userbean;
/** /**
* Default constructor. * Default constructor.
...@@ -36,8 +40,9 @@ public class ProductBean implements ProductBeanLocal { ...@@ -36,8 +40,9 @@ public class ProductBean implements ProductBeanLocal {
} }
@Override @Override
@RolesAllowed("ADMIN_BASE")
public Product createProduct(String name, BigDecimal price) { public Product createProduct(String name, BigDecimal price) {
userbean.fatalPermission(Permission.PRODUCT, RolePermission.WRITE, "User tried to create product: ",name);
Product entity = new Product(eventBean.getCurrentEvent(), name, price); Product entity = new Product(eventBean.getCurrentEvent(), name, price);
productFacade.create(entity); productFacade.create(entity);
return entity; return entity;
...@@ -45,12 +50,14 @@ public class ProductBean implements ProductBeanLocal { ...@@ -45,12 +50,14 @@ public class ProductBean implements ProductBeanLocal {
@Override @Override
public List<Product> getProducts() { public List<Product> getProducts() {
userbean.fatalPermission(Permission.PRODUCT, RolePermission.READ, "User tried to fetch all products");
return productFacade.findAll(); return productFacade.findAll();
} }
@Override @Override
@RolesAllowed("ADMIN_BASE")
public void mergeChanges(Product product) { public void mergeChanges(Product product) {
userbean.fatalPermission(Permission.PRODUCT, RolePermission.WRITE, "User tried to save changes for product: ",product);
productFacade.merge(product); productFacade.merge(product);
} }
......
...@@ -17,13 +17,16 @@ import org.slf4j.LoggerFactory; ...@@ -17,13 +17,16 @@ import org.slf4j.LoggerFactory;
import fi.insomnia.bortal.enums.BeanRole; import fi.insomnia.bortal.enums.BeanRole;
import fi.insomnia.bortal.enums.Permission; import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.facade.AccessRightFacade; import fi.insomnia.bortal.facade.AccessRightFacade;
import fi.insomnia.bortal.facade.EventChildGenericFacade; import fi.insomnia.bortal.facade.EventChildGenericFacade;
import fi.insomnia.bortal.facade.RoleFacade; import fi.insomnia.bortal.facade.RoleFacade;
import fi.insomnia.bortal.facade.RoleRightFacade; import fi.insomnia.bortal.facade.RoleRightFacade;
import fi.insomnia.bortal.model.AccessRight; import fi.insomnia.bortal.model.AccessRight;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role; import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight; import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
/** /**
* *
...@@ -41,25 +44,33 @@ public class RoleBean implements RoleBeanLocal { ...@@ -41,25 +44,33 @@ public class RoleBean implements RoleBeanLocal {
@EJB @EJB
private RoleRightFacade rrfacade; private RoleRightFacade rrfacade;
@EJB
private UserBeanLocal userbean;
@EJB
private AccessRightFacade accessRightFacade; private AccessRightFacade accessRightFacade;
private static final Logger logger = LoggerFactory.getLogger(RoleBean.class); private static final Logger logger = LoggerFactory.getLogger(RoleBean.class);
public List<Role> listRoles() { public List<Role> listRoles() {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.READ, "User tried to listRoles");
return roleFacade.findAll(); return roleFacade.findAll();
} }
public Role mergeChanges(Role role) { public Role mergeChanges(Role role) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.WRITE, "User tried merge role changes for ", role);
return roleFacade.merge(role); return roleFacade.merge(role);
} }
public Role create(Role role) { public Role create(Role role) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.WRITE, "User tried to create role", role.getName());
roleFacade.create(role); roleFacade.create(role);
return role; return role;
} }
public List<Role> getPossibleParents(Role role) { public List<Role> getPossibleParents(Role role) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.READ, "User tried to get possible parents for role ", role);
List<Role> roleList = listRoles(); List<Role> roleList = listRoles();
if (role == null) if (role == null)
return roleList; return roleList;
...@@ -105,6 +116,8 @@ public class RoleBean implements RoleBeanLocal { ...@@ -105,6 +116,8 @@ public class RoleBean implements RoleBeanLocal {
@Override @Override
public RoleRight mergeChanges(RoleRight row) { public RoleRight mergeChanges(RoleRight row) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.WRITE, "User tried merge changes for RoleRight", row);
return rrfacade.merge(row); return rrfacade.merge(row);
} }
...@@ -112,11 +125,11 @@ public class RoleBean implements RoleBeanLocal { ...@@ -112,11 +125,11 @@ public class RoleBean implements RoleBeanLocal {
Role ret = roleFacade.findByName(PUBLIC_ROLE_NAME); Role ret = roleFacade.findByName(PUBLIC_ROLE_NAME);
if (ret == null) { if (ret == null) {
ret = new Role(eventBean.getCurrentEvent());
roleFacade.create(ret);
RoleRight rr = findRoleRight(ret, Permission.LOGIN);
rr.setRead(true);
ret = roleFacade.createRole(eventBean.getCurrentEvent(), PUBLIC_ROLE_NAME);
AccessRight perm = accessRightFacade.findByPermission(Permission.LOGIN);
RoleRight rr = rrfacade.createRoleRight(ret, perm);
rr.setRead(true);
} }
return ret; return ret;
...@@ -128,9 +141,9 @@ public class RoleBean implements RoleBeanLocal { ...@@ -128,9 +141,9 @@ public class RoleBean implements RoleBeanLocal {
} }
public RoleRight findRoleRight(Role role, AccessRight acr) { public RoleRight findRoleRight(Role role, AccessRight acr) {
RoleRight rr = rrfacade.find(eventBean.getCurrentEvent(), acr, role); RoleRight rr = rrfacade.find(acr, role);
if (rr == null) { if (rr == null) {
rr = new RoleRight(eventBean.getCurrentEvent(), role, acr, false, false, false); rr = new RoleRight(role, acr, false, false, false);
rrfacade.create(rr); rrfacade.create(rr);
} }
return rr; return rr;
......
...@@ -2,8 +2,20 @@ package fi.insomnia.bortal.beans; ...@@ -2,8 +2,20 @@ package fi.insomnia.bortal.beans;
import java.util.Calendar; import java.util.Calendar;
import javax.annotation.Resource;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.EJBContext;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -17,6 +29,7 @@ import fi.insomnia.bortal.model.User; ...@@ -17,6 +29,7 @@ import fi.insomnia.bortal.model.User;
* Session Bean implementation class SercurityBean * Session Bean implementation class SercurityBean
*/ */
@Stateless @Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class SecurityBean implements SecurityBeanLocal { public class SecurityBean implements SecurityBeanLocal {
private static final boolean DEBUG = true; private static final boolean DEBUG = true;
...@@ -26,11 +39,18 @@ public class SecurityBean implements SecurityBeanLocal { ...@@ -26,11 +39,18 @@ public class SecurityBean implements SecurityBeanLocal {
private LogEntryTypeFacade typeFacade; private LogEntryTypeFacade typeFacade;
@EJB @EJB
private LogEntryFacade entryFacade; private LogEntryFacade entryFacade;
@PersistenceContext
private EntityManager manager;
@Resource
UserTransaction utx;
@Override @Override
public LogEntry logPermissionDenied(User user, Exception exception) { public LogEntry logPermissionDenied(User user, Exception exception) {
LogEntry entry = logMessage(SecurityLogType.permissionDenied, user, exception.getMessage()); LogEntry entry = null;
entry = logMessage(SecurityLogType.permissionDenied, user, exception.getMessage());
logger.debug(entry.toString(), exception); logger.debug(entry.toString(), exception);
return entry; return entry;
} }
...@@ -58,16 +78,26 @@ public class SecurityBean implements SecurityBeanLocal { ...@@ -58,16 +78,26 @@ public class SecurityBean implements SecurityBeanLocal {
return logMessage(type, null, description); return logMessage(type, null, description);
} }
public LogEntry logMessage( SecurityLogType paramType, User user, String description) { @Resource
LogEntryType type = typeFacade.findOrCreate(paramType); private EJBContext context;
LogEntry entry = new LogEntry(Calendar.getInstance());
entry.setType(type); public LogEntry logMessage(SecurityLogType paramType, User user, String description) {
entry.setDescription(description); LogEntry entry = null;
entry.setUser(user); try {
utx.begin();
entryFacade.create(entry); LogEntryType type = typeFacade.findOrCreate(paramType);
if (DEBUG) { entry = new LogEntry(Calendar.getInstance());
logger.debug("SECURITY DEBUG: Type: \"{}\" user \"{}\", description \"{}\"", new String[] { paramType.name(), (user == null)?"null":user.getLogin(), description }); entry.setType(type);
entry.setDescription(description);
entry.setUser(user);
entryFacade.create(entry);
if (DEBUG) {
logger.debug("SECURITY DEBUG: Type: \"{}\" user \"{}\", description \"{}\"", new String[] { paramType.name(), (user == null) ? "null" : user.getLogin(), description });
}
utx.commit();
} catch (Exception e) {
logger.warn("Exception at SecurityBean", e);
} }
return entry; return entry;
} }
......
...@@ -2,6 +2,8 @@ package fi.insomnia.bortal.beans; ...@@ -2,6 +2,8 @@ package fi.insomnia.bortal.beans;
import java.security.Principal; import java.security.Principal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
...@@ -19,11 +21,14 @@ import fi.insomnia.bortal.enums.Permission; ...@@ -19,11 +21,14 @@ import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission; import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.exceptions.PermissionDeniedException; import fi.insomnia.bortal.exceptions.PermissionDeniedException;
import fi.insomnia.bortal.facade.AccessRightFacade; import fi.insomnia.bortal.facade.AccessRightFacade;
import fi.insomnia.bortal.facade.RoleFacade;
import fi.insomnia.bortal.facade.RoleRightFacade;
import fi.insomnia.bortal.facade.UserFacade; import fi.insomnia.bortal.facade.UserFacade;
import fi.insomnia.bortal.model.AccessRight; import fi.insomnia.bortal.model.AccessRight;
import fi.insomnia.bortal.model.Role; import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight; import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User; import fi.insomnia.bortal.model.User;
import fi.insomnia.bortal.utilities.ThreadLocalContextHolder;
/** /**
* Session Bean implementation class UserBean * Session Bean implementation class UserBean
...@@ -35,6 +40,9 @@ public class UserBean implements UserBeanLocal { ...@@ -35,6 +40,9 @@ public class UserBean implements UserBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(UserBean.class); private static final Logger logger = LoggerFactory.getLogger(UserBean.class);
public static final String DEFAULT_USER_LOGIN = "ANONYMOUS"; public static final String DEFAULT_USER_LOGIN = "ANONYMOUS";
@EJB
private RoleRightFacade rrfacade;
/** /**
* Java EE container injektoi tämän luokkamuuttujan luokan luonnin * Java EE container injektoi tämän luokkamuuttujan luokan luonnin
* yhteydessä. * yhteydessä.
...@@ -54,6 +62,8 @@ public class UserBean implements UserBeanLocal { ...@@ -54,6 +62,8 @@ public class UserBean implements UserBeanLocal {
@EJB @EJB
private EventBeanLocal eventBean; private EventBeanLocal eventBean;
@EJB
private RoleFacade rolefacade;
/** /**
* Default constructor. * Default constructor.
...@@ -133,18 +143,20 @@ public class UserBean implements UserBeanLocal { ...@@ -133,18 +143,20 @@ public class UserBean implements UserBeanLocal {
public boolean hasPermission(Permission target, RolePermission permission) { public boolean hasPermission(Permission target, RolePermission permission) {
User user = getCurrentUser(); User user = getCurrentUser();
logger.info("checking permission {}, {}", target, permission);
Calendar start = Calendar.getInstance();
AccessRight expectedRight = accessRightFacade.findByPermission(target); AccessRight expectedRight = accessRightFacade.findByPermission(target);
User dbusr = userFacade.find(user.getId()); Set<Role> checkedRoles = new HashSet<Role>();
if (dbusr != null) {
Set<Role> checkedRoles = new HashSet<Role>(); List<Role> rolelist = rolefacade.findForUser(user, eventBean.getCurrentEvent());
for (Role r : dbusr.getRoles()) { if (getRights(rolelist, expectedRight, permission, checkedRoles)) {
if (getRights(r, expectedRight, permission, checkedRoles)) { return true;
return true;
}
}
} }
long diffMs = Calendar.getInstance().getTimeInMillis() - start.getTimeInMillis();
logger.debug("");
// TODO: FIX THIS!! really bad idea.... // TODO: FIX THIS!! really bad idea....
if (user.isSuperadmin()) { if (user.isSuperadmin()) {
...@@ -154,41 +166,37 @@ public class UserBean implements UserBeanLocal { ...@@ -154,41 +166,37 @@ public class UserBean implements UserBeanLocal {
return false; return false;
} }
private static boolean getRights(Role role, AccessRight expectedRight, RolePermission permission, Set<Role> checkedRoles) { private boolean getRights(Collection<Role> roles, AccessRight expectedRight, RolePermission permission, Set<Role> checkedRoles) {
if (checkedRoles.contains(role)) { if(roles == null || roles.isEmpty())
{
return false; return false;
} }
for (RoleRight rr : rrfacade.find(roles, expectedRight)) {
for (RoleRight rr : role.getRoleRights()) { switch (permission) {
if (rr.getAccessRight().equals(expectedRight)) { case READ:
switch (permission) { if (rr.isRead()) {
case READ: return true;
if (rr.isRead()) { }
return true; break;
} case WRITE:
break; if (rr.isWrite()) {
case WRITE: return true;
if (rr.isWrite()) { }
return true; break;
} case EXECUTE:
break; if (rr.isExecute()) {
case EXECUTE: return true;
if (rr.isExecute()) {
return true;
}
} }
}
}
checkedRoles.add(role);
for (Role r : role.getParents()) {
if (getRights(r, expectedRight, permission, checkedRoles)) {
return true;
} }
} }
return false; checkedRoles.addAll(roles);
return getRights(rolefacade.findAllParentsExcluding(roles,checkedRoles), expectedRight,permission, checkedRoles);
} }
......
...@@ -45,12 +45,13 @@ public class AccessRightFacade extends IntegerPkGenericFacade<AccessRight> { ...@@ -45,12 +45,13 @@ public class AccessRightFacade extends IntegerPkGenericFacade<AccessRight> {
public AccessRight findByPermission(Permission target) { public AccessRight findByPermission(Permission target) {
// Fetch access right by name // Fetch access right by name
TypedQuery<AccessRight> q = em.createQuery("SELECT a FROM AccessRight a WHERE a.name = :name", AccessRight.class); TypedQuery<AccessRight> q = em.createNamedQuery("AccessRight.findByName", AccessRight.class);
q.setParameter("name", target.name()); q.setParameter("name", target.name());
AccessRight right = null; AccessRight right = null;
right = this.getSingleNullableResult(q); right = this.getSingleNullableResult(q);
if (right == null) { if (right == null) {
right = new AccessRight(target.name()); right = new AccessRight(target.name());
right.setDescription(target.getDescription());
create(right); create(right);
} }
......
package fi.insomnia.bortal.facade; package fi.insomnia.bortal.facade;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
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 javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role; import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.User;
@Stateless @Stateless
@LocalBean @LocalBean
public class RoleFacade extends EventChildGenericFacade<Role> { public class RoleFacade extends EventChildGenericFacade<Role> {
@PersistenceContext @PersistenceContext
private EntityManager em; private EntityManager em;
...@@ -23,12 +30,42 @@ public class RoleFacade extends EventChildGenericFacade<Role> { ...@@ -23,12 +30,42 @@ public class RoleFacade extends EventChildGenericFacade<Role> {
protected EntityManager getEm() { protected EntityManager getEm() {
return em; return em;
} }
public Role findByName(String name) { public Role findByName(String name) {
TypedQuery<Role> q = em.createNamedQuery("Role.findByRoleName", Role.class); TypedQuery<Role> q = em.createNamedQuery("Role.findByRoleName", Role.class);
q.setParameter("name", name); q.setParameter("name", name);
return this.getSingleNullableResult(q); return this.getSingleNullableResult(q);
} }
public List<Role> findForUser(User user, LanEvent event) {
TypedQuery<Role> q = getEm().createNamedQuery("Role.findForUserAndEvent", Role.class);
q.setParameter("user", user);
q.setParameter("event", event);
return q.getResultList();
}
public Collection<Role> findAllParentsExcluding(Collection<Role> roles, Collection<Role> excludedResults) {
Set<Role> ret = new HashSet<Role>();
for (Role r : roles) {
if (!excludedResults.contains(r)) {
ret.addAll(r.getParents());
}
}
ret.removeAll(excludedResults);
return ret;
// TypedQuery<Role> q
// =getEm().createNamedQuery("Role.findParentsExcluding",Role.class);
// q.setParameter("children", roles);
// q.setParameter("excluded", excludedResults);
// return q.getResultList();
}
public Role createRole(LanEvent event, String rolename) {
Role ret = new Role(event);
ret.setName(rolename);
create(ret);
return ret;
}
} }
package fi.insomnia.bortal.facade; package fi.insomnia.bortal.facade;
import java.util.Collection;
import java.util.List;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
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 javax.persistence.Query;
import javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.model.AccessRight; import fi.insomnia.bortal.model.AccessRight;
import fi.insomnia.bortal.model.LanEvent; import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role; import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight; import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
@Stateless @Stateless
@LocalBean @LocalBean
...@@ -26,12 +32,26 @@ public class RoleRightFacade extends EventChildGenericFacade<RoleRight> { ...@@ -26,12 +32,26 @@ public class RoleRightFacade extends EventChildGenericFacade<RoleRight> {
return em; return em;
} }
public RoleRight find(LanEvent event, AccessRight right, Role role) { public RoleRight find(AccessRight right, Role role) {
TypedQuery<RoleRight> q = this.getEm().createNamedQuery("RoleRight.findByRightAndRoleForEvent", RoleRight.class); TypedQuery<RoleRight> q = this.getEm().createNamedQuery("RoleRight.findByRightAndRole", RoleRight.class);
q.setParameter("accessright", right); q.setParameter("accessright", right);
q.setParameter("role", role); q.setParameter("role", role);
q.setParameter("event_id", event.getId()); return this.getSingleNullableResult(q);
return this.getSingleNullableResult(q); }
public List<RoleRight> find(Collection<Role> roles, AccessRight accessright) {
TypedQuery<RoleRight> q = getEm().createNamedQuery("RoleRight.findByRolesForAccessRight", RoleRight.class);
q.setParameter("roles", roles);
q.setParameter("accessright", accessright);
return q.getResultList();
}
public RoleRight createRoleRight(Role role, AccessRight perm) {
RoleRight ret = new RoleRight(role, perm, false, false, false);
create(ret);
getEm().flush();
return ret;
} }
} }
...@@ -9,8 +9,10 @@ import java.util.List; ...@@ -9,8 +9,10 @@ import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role; import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight; import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
/** /**
* *
...@@ -34,5 +36,8 @@ public interface RoleBeanLocal { ...@@ -34,5 +36,8 @@ public interface RoleBeanLocal {
public Role getOrCreatePublicRole(); public Role getOrCreatePublicRole();
// public List<Role> findRoles(User user, LanEvent currentEvent);
} }
...@@ -6,9 +6,7 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/x ...@@ -6,9 +6,7 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/x
<jta-data-source>jdbc/bortal</jta-data-source> <jta-data-source>jdbc/bortal</jta-data-source>
<properties> <properties>
<property name="eclipselink.ddl-generation" value="create-tables"/> <property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both"/> <property name="eclipselink.ddl-generation.output-mode" value="both"/>
<property name="eclipselink.cache.type.default" value="NONE"/>
</properties> </properties>
</persistence-unit> </persistence-unit>
</persistence> </persistence>
...@@ -28,10 +28,14 @@ import javax.persistence.Version; ...@@ -28,10 +28,14 @@ import javax.persistence.Version;
@NamedQuery(name = "AccessRight.findAll", query = "SELECT a FROM AccessRight a"), @NamedQuery(name = "AccessRight.findAll", query = "SELECT a FROM AccessRight a"),
@NamedQuery(name = "AccessRight.findByName", query = "SELECT a FROM AccessRight a WHERE a.name = :name") }) @NamedQuery(name = "AccessRight.findByName", query = "SELECT a FROM AccessRight a WHERE a.name = :name") })
public class AccessRight implements ModelInterface { public class AccessRight implements ModelInterface {
private static final long serialVersionUID = 1L;
/** /**
*
*/
private static final long serialVersionUID = -3786847490670470716L;
/**
* AccessRight is global entity, and thus does not have a reference to * AccessRight is global entity, and thus does not have a reference to
* Event. * Event.
*/ */
...@@ -44,7 +48,8 @@ public class AccessRight implements ModelInterface { ...@@ -44,7 +48,8 @@ public class AccessRight implements ModelInterface {
* Name of the access right. Code finds rights by this name, so this field * Name of the access right. Code finds rights by this name, so this field
* should not be changed under any circumstances. * should not be changed under any circumstances.
*/ */
@Column(name = "right_name", nullable = false, updatable = false)
@Column(name = "right_name", nullable = false, updatable = false, unique=true)
private String name; private String name;
/** /**
......
...@@ -27,7 +27,11 @@ import javax.persistence.Version; ...@@ -27,7 +27,11 @@ import javax.persistence.Version;
@NamedQueries( { @NamedQuery(name = "DiscountInstance.findAll", query = "SELECT d FROM DiscountInstance d") }) @NamedQueries( { @NamedQuery(name = "DiscountInstance.findAll", query = "SELECT d FROM DiscountInstance d") })
public class DiscountInstance implements EventChildInterface { public class DiscountInstance implements EventChildInterface {
private static final long serialVersionUID = 1L; /**
*
*/
private static final long serialVersionUID = 2192672129232748522L;
@EmbeddedId @EmbeddedId
private EventPk id; private EventPk id;
......
...@@ -28,9 +28,12 @@ import javax.persistence.Version; ...@@ -28,9 +28,12 @@ import javax.persistence.Version;
*/ */
@Entity @Entity
@Table(name = "roles", uniqueConstraints = { @UniqueConstraint(columnNames = { "event_id", "role_name" }) }) @Table(name = "roles", uniqueConstraints = { @UniqueConstraint(columnNames = { "event_id", "role_name" }) })
@NamedQueries( { @NamedQueries({
@NamedQuery(name = "Role.findAll", query = "SELECT r FROM Role r"), @NamedQuery(name = "Role.findAll", query = "SELECT r FROM Role r"),
@NamedQuery(name = "Role.findByRoleName", query = "SELECT r FROM Role r WHERE r.name = :name") }) @NamedQuery(name = "Role.findByRoleName", query = "SELECT r FROM Role r WHERE r.name = :name"),
// @NamedQuery(name="Role.findParentsExcluding",
// query="select r from Role where r.children in :roles and r not in :excluded"),
@NamedQuery(name = "Role.findForUserAndEvent", query = "SELECT r FROM Role r WHERE :user MEMBER OF r.users and r.event = :event") })
public class Role implements EventChildInterface { public class Role implements EventChildInterface {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
...@@ -48,9 +51,9 @@ public class Role implements EventChildInterface { ...@@ -48,9 +51,9 @@ public class Role implements EventChildInterface {
@ManyToMany @ManyToMany
@JoinTable(name = "role_children", joinColumns = { @JoinTable(name = "role_children", joinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "id"), @JoinColumn(name = "children_id", referencedColumnName = "id"),
@JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) }, inverseJoinColumns = { @JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) }, inverseJoinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "id"), @JoinColumn(name = "parent_id", referencedColumnName = "id"),
@JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) }) @JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) })
private List<Role> children = new ArrayList<Role>(); private List<Role> children = new ArrayList<Role>();
...@@ -60,9 +63,9 @@ public class Role implements EventChildInterface { ...@@ -60,9 +63,9 @@ public class Role implements EventChildInterface {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "role") @OneToMany(cascade = CascadeType.ALL, mappedBy = "role")
private List<RoleRight> roleRights; private List<RoleRight> roleRights;
@JoinColumns( { @JoinColumns({
@JoinColumn(name = "card_template_id", referencedColumnName = "id", updatable = false, insertable = false), @JoinColumn(name = "card_template_id", referencedColumnName = "id", updatable = false, insertable = false),
@JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) }) @JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) })
@ManyToOne @ManyToOne
private CardTemplate cardTemplate; private CardTemplate cardTemplate;
...@@ -85,6 +88,7 @@ public class Role implements EventChildInterface { ...@@ -85,6 +88,7 @@ public class Role implements EventChildInterface {
public Role(LanEvent event) { public Role(LanEvent event) {
this.id = new EventPk(event); this.id = new EventPk(event);
this.event = event;
} }
public Role(LanEvent event, String roleName) { public Role(LanEvent event, String roleName) {
......
...@@ -23,7 +23,10 @@ import javax.persistence.Version; ...@@ -23,7 +23,10 @@ import javax.persistence.Version;
@Entity @Entity
@Table(name = "role_rights", uniqueConstraints = {@UniqueConstraint(columnNames = { "event_id","role_id", "access_right_id" })}) @Table(name = "role_rights", uniqueConstraints = {@UniqueConstraint(columnNames = { "event_id","role_id", "access_right_id" })})
@NamedQueries( { @NamedQuery(name = "RoleRight.findAll", query = "SELECT r FROM RoleRight r"), @NamedQueries( { @NamedQuery(name = "RoleRight.findAll", query = "SELECT r FROM RoleRight r"),
@NamedQuery(name = "RoleRight.findByRightAndRoleForEvent", query = "SELECT r FROM RoleRight r where r.role = :role and r.accessRight = :accessright and r.id.eventId = :event_id")}) @NamedQuery(name = "RoleRight.findByRightAndRole", query = "SELECT r FROM RoleRight r where r.role = :role and r.accessRight = :accessright "),
@NamedQuery(name="RoleRight.findByRolesForAccessRight", query ="SELECT rr from RoleRight rr where rr.role in :roles and rr.accessRight = :accessright")
})
public class RoleRight implements EventChildInterface { public class RoleRight implements EventChildInterface {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
...@@ -56,13 +59,14 @@ public class RoleRight implements EventChildInterface { ...@@ -56,13 +59,14 @@ public class RoleRight implements EventChildInterface {
public RoleRight() { public RoleRight() {
} }
public RoleRight(LanEvent event) { public RoleRight(Role role) {
this.id = new EventPk(event);
this.id = new EventPk(role.getEvent());
this.role=role;
} }
public RoleRight(LanEvent event, Role role, AccessRight right, boolean read, boolean write, boolean execute) { public RoleRight( Role role, AccessRight right, boolean read, boolean write, boolean execute) {
this(event); this(role);
this.role = role;
this.accessRight = right; this.accessRight = right;
this.read = read; this.read = read;
this.write = write; this.write = write;
......
...@@ -103,16 +103,21 @@ ...@@ -103,16 +103,21 @@
</servlet-mapping> </servlet-mapping>
<error-page> <error-page>
<error-code>401</error-code> <error-code>401</error-code>
<location>/auth/notauthorized.jsf</location> <location>/permissionDeniedRedirect.jsp</location>
</error-page> </error-page>
<error-page> <error-page>
<error-code>403</error-code> <error-code>403</error-code>
<location>/auth/notauthorized.jsf</location> <location>/permissionDeniedRedirect.jsp</location>
</error-page> </error-page>
<error-page> <error-page>
<exception-type>fi.insomnia.bortal.exceptions.PermissionDeniedException</exception-type> <exception-type>fi.insomnia.bortal.exceptions.PermissionDeniedException</exception-type>
<location>/auth/notauthorized.jsf</location> <location>/permissionDeniedRedirect.jsp</location>
</error-page> </error-page>
<error-page>
<exception-type>import javax.servlet.ServletException</exception-type>
<location>/permissionDeniedRedirect.jsp</location>
</error-page>
<persistence-unit-ref> <persistence-unit-ref>
<persistence-unit-ref-name>BortalEMF</persistence-unit-ref-name> <persistence-unit-ref-name>BortalEMF</persistence-unit-ref-name>
......
...@@ -29,9 +29,10 @@ ...@@ -29,9 +29,10 @@
<div id="content"> <div id="content">
<div id="cwrap"> <div id="cwrap">
<ui:include src="/layout/insomnia1/sidebar-#{i18n[util.concat(thispage,'.pagegroup')]}.xhtml" /> <ui:include src="/layout/insomnia1/sidebar-#{i18n[util.concat(thispage,'.pagegroup')]}.xhtml" />
asd
<h:messages globalOnly="true" /> <h:messages globalOnly="true" />
<h:messages /> <h:messages />
foo
<ui:insert name="content" /> <ui:insert name="content" />
</div> </div>
</div> </div>
......
<% response.sendRedirect(request.getContextPath()+"/permissionDenied.jsf"); %></body>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Permission denied!</title>
Permission denied. Redirecting to
<a href="<%=request.getContextPath()+"/permissionDenied.jsf" %>">Login page.</a>
</head>
</html>
\ No newline at end of file
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:tools="http://java.sun.com/jsf/composite/tools">
<composite:interface>
<composite:attribute name="target" required="true" />
<composite:attribute name="permission" required="true" />
</composite:interface>
<composite:implementation>
prefatbean
<h:outputText rendered="#{sessionHandler.fatalPermission(cc.attrs.target, cc.attrs.permission)}" value=""/>
postfatbean
</composite:implementation>
</html>
\ No newline at end of file
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
<composite:implementation> <composite:implementation>
<tools:canRead target="PRODUCT" >
<h:form> <h:form>
<h:dataTable border="1" id="product" value="#{productView.products}" var="product"> <h:dataTable border="1" id="product" value="#{productView.products}" var="product">
<h:column> <h:column>
...@@ -32,17 +31,13 @@ ...@@ -32,17 +31,13 @@
<h:outputText value="#{product.price}" /> <h:outputText value="#{product.price}" />
</h:column> </h:column>
<h:column rendered="#{sessionHandler.canWrite('PRODUCT') }"> <h:column >
<f:facet name="header">
<h:outputText value="Edit" />
</f:facet>
<h:commandButton action="#{productView.edit()}" value="#{i18n['product.edit']}" /> <h:commandButton action="#{productView.edit()}" value="#{i18n['product.edit']}" />
</h:column> </h:column>
</h:dataTable> </h:dataTable>
</h:form> </h:form>
</tools:canRead>
......
...@@ -17,17 +17,10 @@ ...@@ -17,17 +17,10 @@
<composite:implementation> <composite:implementation>
<tools:fatalRight permission="ROLE_MANAGEMENT" right="WRITE" />
<h:form> <h:form>
<tools:canWrite target="ROLE_MANAGEMENT"> <ui:include src="form.xhtml" />
<f:facet name="errorMessage"> <h:commandButton value="#{i18n['role.create']}" action="#{roleView.create}" />
<h:outputText value="#{i18n['global.notauthorized']}" />
</f:facet>
<ui:include src="form.xhtml" />
<h:commandButton value="#{i18n['role.create']}" action="#{roleView.create}" />
</tools:canWrite>
</h:form> </h:form>
......
...@@ -9,56 +9,53 @@ ...@@ -9,56 +9,53 @@
<composite:implementation> <composite:implementation>
<tools:canWrite target="ROLE_MANAGEMENT"> <h:form>
<h:form> <f:facet name="errorMessage">
<f:facet name="errorMessage"> <h:outputText value="#{i18n['nasty.user']}" />
<h:outputText value="#{i18n['nasty.user']}" /> </f:facet>
</f:facet> <ui:include src="form.xhtml" />
<ui:include src="form.xhtml" /> <h:commandButton value="#{i18n['save']}" action="#{roleView.save}" />
<h:commandButton value="#{i18n['save']}" action="#{roleView.save}" /> </h:form>
<h:form>
</h:form> <h:dataTable border="1" id="rights" value="#{roleView.roleRights}" var="rr">
<h:form> <h:column>
<h:dataTable border="1" id="rights" value="#{roleView.roleRights}" var="rr"> <f:facet name="header">
<h:column> <h:outputText value="#{i18n['role.name']}" />
<f:facet name="header"> </f:facet>
<h:outputText value="#{i18n['role.name']}" /> <h:outputText value="#{rr.accessRight.name}" />
</f:facet> </h:column>
<h:outputText value="#{rr.accessRight.name}" /> <h:column>
</h:column> <f:facet name="header">
<h:column> <h:outputText value="#{i18n['role.description']}" />
<f:facet name="header"> </f:facet>
<h:outputText value="#{i18n['role.description']}" /> <h:outputText value="#{rr.accessRight.description}" />
</f:facet> </h:column>
<h:outputText value="#{rr.accessRight.description}" /> <h:column>
</h:column> <f:facet name="header">
<h:column> <h:outputText value="#{i18n['role.read']}" />
<f:facet name="header"> </f:facet>
<h:outputText value="#{i18n['role.read']}" /> <h:selectBooleanCheckbox value="#{rr.read}" />
</f:facet> </h:column>
<h:selectBooleanCheckbox value="#{rr.read}" /> <h:column>
</h:column> <f:facet name="header">
<h:column> <h:outputText value="#{i18n['role.write']}" />
<f:facet name="header"> </f:facet>
<h:outputText value="#{i18n['role.write']}" /> <h:selectBooleanCheckbox value="#{rr.write}" />
</f:facet> </h:column>
<h:selectBooleanCheckbox value="#{rr.write}" /> <h:column>
</h:column> <f:facet name="header">
<h:column> <h:outputText value="#{i18n['role.execute']}" />
<f:facet name="header"> </f:facet>
<h:outputText value="#{i18n['role.execute']}" /> <h:selectBooleanCheckbox value="#{rr.execute}" />
</f:facet> </h:column>
<h:selectBooleanCheckbox value="#{rr.execute}" /> <h:column>
</h:column> <h:commandButton value="#{i18n['role.edit.save']}" action="#{roleView.editRoleRight}" />
<h:column> </h:column>
<h:commandButton value="#{i18n['role.edit.save']}" action="#{roleView.editRoleRight}" /> </h:dataTable>
</h:column> </h:form>
</h:dataTable>
</h:form>
</tools:canWrite>
</composite:implementation> </composite:implementation>
......
...@@ -16,9 +16,7 @@ ...@@ -16,9 +16,7 @@
<composite:implementation> <composite:implementation>
<h:form> <h:form>
<tools:canRead target="ROLE_MANAGEMENT">
<h:dataTable border="1" id="user" value="#{roleView.roles}" var="role"> <h:dataTable border="1" id="user" value="#{roleView.roles}" var="role">
<h:column> <h:column>
<f:facet name="header"> <f:facet name="header">
...@@ -32,11 +30,10 @@ ...@@ -32,11 +30,10 @@
</f:facet> </f:facet>
<h:outputText value="#{role.name}" /> <h:outputText value="#{role.name}" />
</h:column> </h:column>
<h:column rendered="#{sessionHandler.canWrite('ROLE_MANAGEMENT') }"> <h:column>
<h:commandButton action="#{roleView.edit()}" value="#{i18n['role.edit']}" /> <h:commandButton action="#{roleView.edit()}" value="#{i18n['role.edit']}" />
</h:column> </h:column>
</h:dataTable> </h:dataTable>
</tools:canRead>
</h:form> </h:form>
......
...@@ -14,9 +14,9 @@ ...@@ -14,9 +14,9 @@
<composite:interface> <composite:interface>
</composite:interface> </composite:interface>
<composite:implementation> <composite:implementation >
prefatal
<tools:canRead target="USER_MANAGEMENT" >
<h:form> <h:form>
<h:dataTable border="1" id="user" value="#{userView.users}" var="user"> <h:dataTable border="1" id="user" value="#{userView.users}" var="user">
<h:column> <h:column>
...@@ -51,14 +51,13 @@ ...@@ -51,14 +51,13 @@
<h:outputText value="#{user.email}" /> <h:outputText value="#{user.email}" />
</h:column> </h:column>
<h:column rendered="#{sessionHandler.canWrite('USER_MANAGEMENT') }"> <h:column>
<h:commandButton action="#{userView.edit()}" value="#{i18n['user.edit']}" /> <h:commandButton action="#{userView.edit()}" value="#{i18n['user.edit']}" />
</h:column> </h:column>
</h:dataTable> </h:dataTable>
</h:form> </h:form>
</tools:canRead>
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
<h:body> <h:body>
<ui:composition template="/layout/#{sessionHandler.layout}/template.xhtml"> <ui:composition template="/layout/#{sessionHandler.layout}/template.xhtml">
<ui:param name="thispage" value="page.user.create" /> <ui:param name="thispage" value="page.user.create" />
<ui:define name="content"> <ui:define name="content">
<users:list /> <users:list />
</ui:define> </ui:define>
......
...@@ -11,12 +11,14 @@ import javax.servlet.ServletException; ...@@ -11,12 +11,14 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import fi.insomnia.bortal.beans.EventBeanLocal; import fi.insomnia.bortal.beans.EventBeanLocal;
import fi.insomnia.bortal.exceptions.PermissionDeniedException;
import fi.insomnia.bortal.utilities.ThreadLocalContextHolder; import fi.insomnia.bortal.utilities.ThreadLocalContextHolder;
/** /**
...@@ -25,7 +27,7 @@ import fi.insomnia.bortal.utilities.ThreadLocalContextHolder; ...@@ -25,7 +27,7 @@ import fi.insomnia.bortal.utilities.ThreadLocalContextHolder;
public class HostnameFilter implements Filter { public class HostnameFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HostnameFilter.class); private static final Logger logger = LoggerFactory.getLogger(HostnameFilter.class);
/** /**
* Default constructor. * Default constructor.
*/ */
...@@ -66,13 +68,36 @@ public class HostnameFilter implements Filter { ...@@ -66,13 +68,36 @@ public class HostnameFilter implements Filter {
String hostname = url.substring(beginindex, lastindex); String hostname = url.substring(beginindex, lastindex);
logger.debug("Setting hostname to {} ", hostname); logger.debug("Setting hostname to {} ", hostname);
httpRequest.getSession().setAttribute(EventBeanLocal.HTTP_URL_HOSTNAME, hostname); httpRequest.getSession().setAttribute(EventBeanLocal.HTTP_URL_HOSTNAME, hostname);
ThreadLocalContextHolder.put(EventBeanLocal.HTTP_URL_HOSTNAME, hostname); ThreadLocalContextHolder.put(EventBeanLocal.HTTP_URL_HOSTNAME, hostname);
} }
// pass the request along the filter chain // pass the request along the filter chain
chain.doFilter(request, response); try {
ThreadLocalContextHolder.cleanupThread(); chain.doFilter(request, response);
} catch (Throwable t) {
logger.debug("Got exception {} at hostnamefilter", t.getClass());
Throwable cause = t.getCause();
while (cause != null) {
logger.debug("exception cause: {}", cause.getClass());
cause = cause.getCause();
if(cause instanceof PermissionDeniedException)
{
if (response instanceof HttpServletResponse) {
HttpServletResponse httpresp = (HttpServletResponse) response;
httpresp.reset();
httpresp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpresp.getWriter().println("Permission denied!!");
throw (PermissionDeniedException)cause;
}
}
}
} finally {
ThreadLocalContextHolder.cleanupThread();
}
} }
/** /**
......
...@@ -12,6 +12,7 @@ import javax.faces.context.ExceptionHandlerWrapper; ...@@ -12,6 +12,7 @@ import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext; import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent; import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext; import javax.faces.event.ExceptionQueuedEventContext;
import javax.servlet.ServletException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -41,23 +42,21 @@ public class BortalExceptionHandler extends ExceptionHandlerWrapper { ...@@ -41,23 +42,21 @@ public class BortalExceptionHandler extends ExceptionHandlerWrapper {
logger.debug("Found exception! handing it: {}", t.getClass().toString()); logger.debug("Found exception! handing it: {}", t.getClass().toString());
if (t instanceof ViewExpiredException) { if (t instanceof ViewExpiredException) {
errorpage(i, t, "viewExpired"); errorpage(i, t, "viewExpired");
} }
Throwable cause = t; Throwable cause = t.getCause();
for(int loop = 0; loop < 20 && cause != null; ++loop) { for (int loop = 0; loop < 20 && cause != null; ++loop) {
logger.debug("Cause not null, but {}, checking" + t.getClass().toString()); logger.debug("Cause not null, but {}: {}, checking" + cause.getClass(), cause.getMessage());
if (cause instanceof PermissionDeniedException || if (cause instanceof PermissionDeniedException ||
cause instanceof EJBAccessException || cause instanceof EJBAccessException ||
cause instanceof PermissionDeniedException ) { cause instanceof PermissionDeniedException) {
logger.debug("Found Permission Denied cause: {}", cause); logger.debug("Found Permission Denied cause: {}, {}", cause.getClass(), cause.getMessage());
errorpage(i, t, "permissionDenied"); // errorpage(i, t, "permissionDenied");
break;
} }
cause = cause.getCause(); cause = cause.getCause();
} }
} }
// At this point, the queue will not contain any ViewExpiredEvents. // At this point, the queue will not contain any ViewExpiredEvents.
...@@ -74,10 +73,12 @@ public class BortalExceptionHandler extends ExceptionHandlerWrapper { ...@@ -74,10 +73,12 @@ public class BortalExceptionHandler extends ExceptionHandlerWrapper {
if (t instanceof ViewExpiredException) { if (t instanceof ViewExpiredException) {
vee = (ViewExpiredException) t; vee = (ViewExpiredException) t;
} }
FacesContext fc = FacesContext.getCurrentInstance(); FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap(); Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler(); NavigationHandler nav = fc.getApplication().getNavigationHandler();
try { try {
// Push some useful stuff to the request scope for // Push some useful stuff to the request scope for
// use in the page // use in the page
......
...@@ -66,6 +66,16 @@ public class SessionHandler { ...@@ -66,6 +66,16 @@ public class SessionHandler {
return hasPermission(target, perm); return hasPermission(target, perm);
} }
public void fatalPermission(String target, String permission)
{
fatalPermission(Permission.getPermission(target), RolePermission.valueOf(permission));
}
public void fatalPermission(Permission target, RolePermission permission )
{
userbean.fatalPermission(target, permission,"Fail from MBean SessionHandler");
}
private HttpSession getHttpSession() { private HttpSession getHttpSession() {
FacesContext ctx = FacesContext.getCurrentInstance(); FacesContext ctx = FacesContext.getCurrentInstance();
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!