Commit cbd04c10 by Tuomas Riihimäki

Heavy refactoring on authorisation.

1 parent 3509774c
Showing with 335 additions and 101 deletions
......@@ -12,7 +12,7 @@ package fi.insomnia.bortal.beans {
import flash.utils.IExternalizable;
[Bindable]
public class BillLineBeanBase implements IExternalizable, BillLineBeanLocal {
public class BillLineBeanBase implements IExternalizable {
public function readExternal(input:IDataInput):void {
......
......@@ -16,13 +16,16 @@ package fi.insomnia.bortal.beans {
public class PlaceBeanBase implements IExternalizable {
private var _placeFacade:PlaceFacade;
private var _userbean:UserBeanLocal;
public function readExternal(input:IDataInput):void {
_placeFacade = input.readObject() as PlaceFacade;
_userbean = input.readObject() as UserBeanLocal;
}
public function writeExternal(output:IDataOutput):void {
output.writeObject(_placeFacade);
output.writeObject(_userbean);
}
}
}
\ No newline at end of file
......@@ -17,15 +17,18 @@ package fi.insomnia.bortal.beans {
private var _eventBean:EventBeanLocal;
private var _productFacade:ProductFacade;
private var _userbean:UserBeanLocal;
public function readExternal(input:IDataInput):void {
_eventBean = input.readObject() as EventBeanLocal;
_productFacade = input.readObject() as ProductFacade;
_userbean = input.readObject() as UserBeanLocal;
}
public function writeExternal(output:IDataOutput):void {
output.writeObject(_eventBean);
output.writeObject(_productFacade);
output.writeObject(_userbean);
}
}
}
\ No newline at end of file
......@@ -21,12 +21,14 @@ package fi.insomnia.bortal.beans {
private var _eventBean:EventBeanLocal;
private var _roleFacade:RoleFacade;
private var _rrfacade:RoleRightFacade;
private var _userbean:UserBeanLocal;
public function readExternal(input:IDataInput):void {
_accessRightFacade = input.readObject() as AccessRightFacade;
_eventBean = input.readObject() as EventBeanLocal;
_roleFacade = input.readObject() as RoleFacade;
_rrfacade = input.readObject() as RoleRightFacade;
_userbean = input.readObject() as UserBeanLocal;
}
public function writeExternal(output:IDataOutput):void {
......@@ -34,6 +36,7 @@ package fi.insomnia.bortal.beans {
output.writeObject(_eventBean);
output.writeObject(_roleFacade);
output.writeObject(_rrfacade);
output.writeObject(_userbean);
}
}
}
\ No newline at end of file
......@@ -12,25 +12,37 @@ package fi.insomnia.bortal.beans {
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
import javax.ejb.EJBContext;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
import org.slf4j.Logger;
[Bindable]
public class SecurityBeanBase implements IExternalizable {
private var _context:EJBContext;
private var _entryFacade:LogEntryFacade;
private var _logger:Logger;
private var _manager:EntityManager;
private var _typeFacade:LogEntryTypeFacade;
protected var _utx:UserTransaction;
public function readExternal(input:IDataInput):void {
_context = input.readObject() as EJBContext;
_entryFacade = input.readObject() as LogEntryFacade;
_logger = input.readObject() as Logger;
_manager = input.readObject() as EntityManager;
_typeFacade = input.readObject() as LogEntryTypeFacade;
_utx = input.readObject() as UserTransaction;
}
public function writeExternal(output:IDataOutput):void {
output.writeObject(_context);
output.writeObject(_entryFacade);
output.writeObject(_logger);
output.writeObject(_manager);
output.writeObject(_typeFacade);
output.writeObject(_utx);
}
}
}
\ No newline at end of file
......@@ -8,6 +8,8 @@
package fi.insomnia.bortal.beans {
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 flash.utils.IDataInput;
import flash.utils.IDataOutput;
......@@ -21,6 +23,8 @@ package fi.insomnia.bortal.beans {
private var _context:SessionContext;
private var _eventBean:EventBeanLocal;
private var _rolebean:RoleBeanLocal;
private var _rolefacade:RoleFacade;
private var _rrfacade:RoleRightFacade;
private var _secubean:SecurityBeanLocal;
private var _userFacade:UserFacade;
......@@ -29,6 +33,8 @@ package fi.insomnia.bortal.beans {
_context = input.readObject() as SessionContext;
_eventBean = input.readObject() as EventBeanLocal;
_rolebean = input.readObject() as RoleBeanLocal;
_rolefacade = input.readObject() as RoleFacade;
_rrfacade = input.readObject() as RoleRightFacade;
_secubean = input.readObject() as SecurityBeanLocal;
_userFacade = input.readObject() as UserFacade;
}
......@@ -38,6 +44,8 @@ package fi.insomnia.bortal.beans {
output.writeObject(_context);
output.writeObject(_eventBean);
output.writeObject(_rolebean);
output.writeObject(_rolefacade);
output.writeObject(_rrfacade);
output.writeObject(_secubean);
output.writeObject(_userFacade);
}
......
......@@ -98,10 +98,10 @@ public class BillBean implements BillBeanLocal {
@Override
public Bill createEmptyBill(User shoppingUser) {
if (shoppingUser != null && userBean.hasCurrentUserPermission(Permission.USER_MANAGEMENT, RolePermission.EXECUTE)) {
String msg = new StringBuilder("User tried to shop to ").append(shoppingUser.getId()).append(" another without sufficient rights").toString();
throw new PermissionDeniedException(secubean, userBean.getCurrentUser(), msg);
if (shoppingUser != null && !userBean.isCurrentUser(shoppingUser)) {
userBean.fatalPermission(Permission.USER_MANAGEMENT, RolePermission.EXECUTE, "User tried to shop to ", shoppingUser, " another without sufficient rights");
}
if (shoppingUser == null) {
shoppingUser = userBean.getCurrentUser();
}
......@@ -114,10 +114,10 @@ public class BillBean implements BillBeanLocal {
@Override
public BillLine addProductToBill(Bill bill, Product product, BigDecimal count) {
// TODO: Lähetettyä laskua ei saa kaikki muokata!
// TODO: Jos ei olla tekemässä omaa laskua tarkistetaan onko riittävät
// oikeudet.
// If bill number > 0 bill has been sent and extra privileges are needed to modify.
if (!userBean.isCurrentUser(bill.getUser()) || bill.getBillNumber() > 0) {
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());
billLineFacade.create(line);
return line;
......
......@@ -4,6 +4,8 @@
*/
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.model.Place;
import javax.ejb.EJB;
......@@ -19,7 +21,11 @@ public class PlaceBean implements PlaceBeanLocal {
@EJB
private PlaceFacade placeFacade;
@EJB
private UserBeanLocal userbean;
public Place mergeChanges(Place place) {
userbean.fatalPermission(Permission.TICKET_SALES, RolePermission.EXECUTE, "User tried to modify place ", place);
return placeFacade.merge(place);
}
}
......@@ -54,9 +54,7 @@ public class PlaceMapBean implements PlaceMapBeanLocal {
public void printPlaceMapToStream(OutputStream outputStream, String filetype, Integer mapId, List<Integer> placeIds) throws IOException {
User user = userbean.getCurrentUser();
if (!userbean.hasPermission(Permission.TICKET_SALES, RolePermission.READ)) {
throw new PermissionDeniedException(secubean, user, "User has no right to view placemap ( TICKET_SALES, READ )");
}
userbean.fatalPermission(Permission.TICKET_SALES, RolePermission.READ, "User tried to print the placemap to Stream");
long begin = new Date().getTime();
Integer eventId = eventbean.getCurrentEvent().getId();
......
......@@ -7,6 +7,8 @@ import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
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.model.Product;
......@@ -21,6 +23,8 @@ public class ProductBean implements ProductBeanLocal {
@EJB
private EventBeanLocal eventBean;
@EJB
private UserBeanLocal userbean;
/**
* Default constructor.
......@@ -36,8 +40,9 @@ public class ProductBean implements ProductBeanLocal {
}
@Override
@RolesAllowed("ADMIN_BASE")
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);
productFacade.create(entity);
return entity;
......@@ -45,12 +50,14 @@ public class ProductBean implements ProductBeanLocal {
@Override
public List<Product> getProducts() {
userbean.fatalPermission(Permission.PRODUCT, RolePermission.READ, "User tried to fetch all products");
return productFacade.findAll();
}
@Override
@RolesAllowed("ADMIN_BASE")
public void mergeChanges(Product product) {
userbean.fatalPermission(Permission.PRODUCT, RolePermission.WRITE, "User tried to save changes for product: ",product);
productFacade.merge(product);
}
......
......@@ -17,13 +17,16 @@ import org.slf4j.LoggerFactory;
import fi.insomnia.bortal.enums.BeanRole;
import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.facade.AccessRightFacade;
import fi.insomnia.bortal.facade.EventChildGenericFacade;
import fi.insomnia.bortal.facade.RoleFacade;
import fi.insomnia.bortal.facade.RoleRightFacade;
import fi.insomnia.bortal.model.AccessRight;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
/**
*
......@@ -41,25 +44,33 @@ public class RoleBean implements RoleBeanLocal {
@EJB
private RoleRightFacade rrfacade;
@EJB
private UserBeanLocal userbean;
@EJB
private AccessRightFacade accessRightFacade;
private static final Logger logger = LoggerFactory.getLogger(RoleBean.class);
public List<Role> listRoles() {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.READ, "User tried to listRoles");
return roleFacade.findAll();
}
public Role mergeChanges(Role role) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.WRITE, "User tried merge role changes for ", role);
return roleFacade.merge(role);
}
public Role create(Role role) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.WRITE, "User tried to create role", role.getName());
roleFacade.create(role);
return 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();
if (role == null)
return roleList;
......@@ -105,6 +116,8 @@ public class RoleBean implements RoleBeanLocal {
@Override
public RoleRight mergeChanges(RoleRight row) {
userbean.fatalPermission(Permission.ROLE_MANAGEMENT, RolePermission.WRITE, "User tried merge changes for RoleRight", row);
return rrfacade.merge(row);
}
......@@ -112,11 +125,11 @@ public class RoleBean implements RoleBeanLocal {
Role ret = roleFacade.findByName(PUBLIC_ROLE_NAME);
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;
......@@ -128,9 +141,9 @@ public class RoleBean implements RoleBeanLocal {
}
public RoleRight findRoleRight(Role role, AccessRight acr) {
RoleRight rr = rrfacade.find(eventBean.getCurrentEvent(), acr, role);
RoleRight rr = rrfacade.find(acr, role);
if (rr == null) {
rr = new RoleRight(eventBean.getCurrentEvent(), role, acr, false, false, false);
rr = new RoleRight(role, acr, false, false, false);
rrfacade.create(rr);
}
return rr;
......
......@@ -2,8 +2,20 @@ package fi.insomnia.bortal.beans;
import java.util.Calendar;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBContext;
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;
......@@ -17,6 +29,7 @@ import fi.insomnia.bortal.model.User;
* Session Bean implementation class SercurityBean
*/
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class SecurityBean implements SecurityBeanLocal {
private static final boolean DEBUG = true;
......@@ -26,11 +39,18 @@ public class SecurityBean implements SecurityBeanLocal {
private LogEntryTypeFacade typeFacade;
@EJB
private LogEntryFacade entryFacade;
@PersistenceContext
private EntityManager manager;
@Resource
UserTransaction utx;
@Override
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);
return entry;
}
......@@ -58,16 +78,26 @@ public class SecurityBean implements SecurityBeanLocal {
return logMessage(type, null, description);
}
public LogEntry logMessage( SecurityLogType paramType, User user, String description) {
@Resource
private EJBContext context;
public LogEntry logMessage(SecurityLogType paramType, User user, String description) {
LogEntry entry = null;
try {
utx.begin();
LogEntryType type = typeFacade.findOrCreate(paramType);
LogEntry entry = new LogEntry(Calendar.getInstance());
entry = new LogEntry(Calendar.getInstance());
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 });
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;
}
......
......@@ -2,6 +2,8 @@ package fi.insomnia.bortal.beans;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
......@@ -19,11 +21,14 @@ import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.exceptions.PermissionDeniedException;
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.model.AccessRight;
import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
import fi.insomnia.bortal.utilities.ThreadLocalContextHolder;
/**
* Session Bean implementation class UserBean
......@@ -35,6 +40,9 @@ public class UserBean implements UserBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(UserBean.class);
public static final String DEFAULT_USER_LOGIN = "ANONYMOUS";
@EJB
private RoleRightFacade rrfacade;
/**
* Java EE container injektoi tämän luokkamuuttujan luokan luonnin
* yhteydessä.
......@@ -54,6 +62,8 @@ public class UserBean implements UserBeanLocal {
@EJB
private EventBeanLocal eventBean;
@EJB
private RoleFacade rolefacade;
/**
* Default constructor.
......@@ -133,18 +143,20 @@ public class UserBean implements UserBeanLocal {
public boolean hasPermission(Permission target, RolePermission permission) {
User user = getCurrentUser();
logger.info("checking permission {}, {}", target, permission);
Calendar start = Calendar.getInstance();
AccessRight expectedRight = accessRightFacade.findByPermission(target);
User dbusr = userFacade.find(user.getId());
if (dbusr != null) {
Set<Role> checkedRoles = new HashSet<Role>();
for (Role r : dbusr.getRoles()) {
if (getRights(r, expectedRight, permission, checkedRoles)) {
List<Role> rolelist = rolefacade.findForUser(user, eventBean.getCurrentEvent());
if (getRights(rolelist, expectedRight, permission, checkedRoles)) {
return true;
}
}
}
long diffMs = Calendar.getInstance().getTimeInMillis() - start.getTimeInMillis();
logger.debug("");
// TODO: FIX THIS!! really bad idea....
if (user.isSuperadmin()) {
......@@ -154,14 +166,14 @@ public class UserBean implements UserBeanLocal {
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;
}
for (RoleRight rr : rrfacade.find(roles, expectedRight)) {
for (RoleRight rr : role.getRoleRights()) {
if (rr.getAccessRight().equals(expectedRight)) {
switch (permission) {
case READ:
if (rr.isRead()) {
......@@ -177,18 +189,14 @@ public class UserBean implements UserBeanLocal {
if (rr.isExecute()) {
return true;
}
}
}
}
checkedRoles.add(role);
checkedRoles.addAll(roles);
return getRights(rolefacade.findAllParentsExcluding(roles,checkedRoles), expectedRight,permission, checkedRoles);
for (Role r : role.getParents()) {
if (getRights(r, expectedRight, permission, checkedRoles)) {
return true;
}
}
return false;
}
......
......@@ -45,12 +45,13 @@ public class AccessRightFacade extends IntegerPkGenericFacade<AccessRight> {
public AccessRight findByPermission(Permission target) {
// 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());
AccessRight right = null;
right = this.getSingleNullableResult(q);
if (right == null) {
right = new AccessRight(target.name());
right.setDescription(target.getDescription());
create(right);
}
......
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.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.User;
@Stateless
@LocalBean
public class RoleFacade extends EventChildGenericFacade<Role> {
@PersistenceContext
private EntityManager em;
......@@ -30,5 +37,35 @@ public class RoleFacade extends EventChildGenericFacade<Role> {
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;
import java.util.Collection;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.model.AccessRight;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
@Stateless
@LocalBean
......@@ -26,12 +32,26 @@ public class RoleRightFacade extends EventChildGenericFacade<RoleRight> {
return em;
}
public RoleRight find(LanEvent event, AccessRight right, Role role) {
TypedQuery<RoleRight> q = this.getEm().createNamedQuery("RoleRight.findByRightAndRoleForEvent", RoleRight.class);
public RoleRight find(AccessRight right, Role role) {
TypedQuery<RoleRight> q = this.getEm().createNamedQuery("RoleRight.findByRightAndRole", RoleRight.class);
q.setParameter("accessright", right);
q.setParameter("role", role);
q.setParameter("event_id", event.getId());
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;
import javax.ejb.Local;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Role;
import fi.insomnia.bortal.model.RoleRight;
import fi.insomnia.bortal.model.User;
/**
*
......@@ -34,5 +36,8 @@ public interface RoleBeanLocal {
public Role getOrCreatePublicRole();
// public List<Role> findRoles(User user, LanEvent currentEvent);
}
......@@ -7,8 +7,6 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/x
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both"/>
<property name="eclipselink.cache.type.default" value="NONE"/>
</properties>
</persistence-unit>
</persistence>
......@@ -28,10 +28,14 @@ import javax.persistence.Version;
@NamedQuery(name = "AccessRight.findAll", query = "SELECT a FROM AccessRight a"),
@NamedQuery(name = "AccessRight.findByName", query = "SELECT a FROM AccessRight a WHERE a.name = :name") })
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
* Event.
*/
......@@ -44,7 +48,8 @@ public class AccessRight implements ModelInterface {
* Name of the access right. Code finds rights by this name, so this field
* 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;
/**
......
......@@ -27,7 +27,11 @@ import javax.persistence.Version;
@NamedQueries( { @NamedQuery(name = "DiscountInstance.findAll", query = "SELECT d FROM DiscountInstance d") })
public class DiscountInstance implements EventChildInterface {
private static final long serialVersionUID = 1L;
/**
*
*/
private static final long serialVersionUID = 2192672129232748522L;
@EmbeddedId
private EventPk id;
......
......@@ -28,9 +28,12 @@ import javax.persistence.Version;
*/
@Entity
@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.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 {
private static final long serialVersionUID = 1L;
......@@ -48,9 +51,9 @@ public class Role implements EventChildInterface {
@ManyToMany
@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 = "role_id", referencedColumnName = "id"),
@JoinColumn(name = "parent_id", referencedColumnName = "id"),
@JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) })
private List<Role> children = new ArrayList<Role>();
......@@ -60,7 +63,7 @@ public class Role implements EventChildInterface {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "role")
private List<RoleRight> roleRights;
@JoinColumns( {
@JoinColumns({
@JoinColumn(name = "card_template_id", referencedColumnName = "id", updatable = false, insertable = false),
@JoinColumn(name = "event_id", referencedColumnName = "event_id", updatable = false, insertable = false) })
@ManyToOne
......@@ -85,6 +88,7 @@ public class Role implements EventChildInterface {
public Role(LanEvent event) {
this.id = new EventPk(event);
this.event = event;
}
public Role(LanEvent event, String roleName) {
......
......@@ -23,7 +23,10 @@ import javax.persistence.Version;
@Entity
@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"),
@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 {
private static final long serialVersionUID = 1L;
......@@ -56,13 +59,14 @@ public class RoleRight implements EventChildInterface {
public RoleRight() {
}
public RoleRight(LanEvent event) {
this.id = new EventPk(event);
public RoleRight(Role role) {
this.id = new EventPk(role.getEvent());
this.role=role;
}
public RoleRight(LanEvent event, Role role, AccessRight right, boolean read, boolean write, boolean execute) {
this(event);
this.role = role;
public RoleRight( Role role, AccessRight right, boolean read, boolean write, boolean execute) {
this(role);
this.accessRight = right;
this.read = read;
this.write = write;
......
......@@ -103,16 +103,21 @@
</servlet-mapping>
<error-page>
<error-code>401</error-code>
<location>/auth/notauthorized.jsf</location>
<location>/permissionDeniedRedirect.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/auth/notauthorized.jsf</location>
<location>/permissionDeniedRedirect.jsp</location>
</error-page>
<error-page>
<exception-type>fi.insomnia.bortal.exceptions.PermissionDeniedException</exception-type>
<location>/auth/notauthorized.jsf</location>
<location>/permissionDeniedRedirect.jsp</location>
</error-page>
<error-page>
<exception-type>import javax.servlet.ServletException</exception-type>
<location>/permissionDeniedRedirect.jsp</location>
</error-page>
<persistence-unit-ref>
<persistence-unit-ref-name>BortalEMF</persistence-unit-ref-name>
......
......@@ -29,9 +29,10 @@
<div id="content">
<div id="cwrap">
<ui:include src="/layout/insomnia1/sidebar-#{i18n[util.concat(thispage,'.pagegroup')]}.xhtml" />
asd
<h:messages globalOnly="true" />
<h:messages />
foo
<ui:insert name="content" />
</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 @@
<composite:implementation>
<tools:canRead target="PRODUCT" >
<h:form>
<h:dataTable border="1" id="product" value="#{productView.products}" var="product">
<h:column>
......@@ -32,17 +31,13 @@
<h:outputText value="#{product.price}" />
</h:column>
<h:column rendered="#{sessionHandler.canWrite('PRODUCT') }">
<f:facet name="header">
<h:outputText value="Edit" />
</f:facet>
<h:column >
<h:commandButton action="#{productView.edit()}" value="#{i18n['product.edit']}" />
</h:column>
</h:dataTable>
</h:form>
</tools:canRead>
......
......@@ -17,17 +17,10 @@
<composite:implementation>
<tools:fatalRight permission="ROLE_MANAGEMENT" right="WRITE" />
<h:form>
<tools:canWrite target="ROLE_MANAGEMENT">
<f:facet name="errorMessage">
<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>
......
......@@ -10,12 +10,10 @@
<composite:implementation>
<tools:canWrite target="ROLE_MANAGEMENT">
<h:form>
<f:facet name="errorMessage">
<h:outputText value="#{i18n['nasty.user']}" />
</f:facet>
<ui:include src="form.xhtml" />
<h:commandButton value="#{i18n['save']}" action="#{roleView.save}" />
......@@ -58,7 +56,6 @@
</h:column>
</h:dataTable>
</h:form>
</tools:canWrite>
</composite:implementation>
......
......@@ -16,9 +16,7 @@
<composite:implementation>
<h:form>
<tools:canRead target="ROLE_MANAGEMENT">
<h:dataTable border="1" id="user" value="#{roleView.roles}" var="role">
<h:column>
<f:facet name="header">
......@@ -32,11 +30,10 @@
</f:facet>
<h:outputText value="#{role.name}" />
</h:column>
<h:column rendered="#{sessionHandler.canWrite('ROLE_MANAGEMENT') }">
<h:column>
<h:commandButton action="#{roleView.edit()}" value="#{i18n['role.edit']}" />
</h:column>
</h:dataTable>
</tools:canRead>
</h:form>
......
......@@ -14,9 +14,9 @@
<composite:interface>
</composite:interface>
<composite:implementation>
<composite:implementation >
prefatal
<tools:canRead target="USER_MANAGEMENT" >
<h:form>
<h:dataTable border="1" id="user" value="#{userView.users}" var="user">
<h:column>
......@@ -51,14 +51,13 @@
<h:outputText value="#{user.email}" />
</h:column>
<h:column rendered="#{sessionHandler.canWrite('USER_MANAGEMENT') }">
<h:column>
<h:commandButton action="#{userView.edit()}" value="#{i18n['user.edit']}" />
</h:column>
</h:dataTable>
</h:form>
</tools:canRead>
......
......@@ -10,6 +10,7 @@
<h:body>
<ui:composition template="/layout/#{sessionHandler.layout}/template.xhtml">
<ui:param name="thispage" value="page.user.create" />
<ui:define name="content">
<users:list />
</ui:define>
......
......@@ -11,12 +11,14 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.insomnia.bortal.beans.EventBeanLocal;
import fi.insomnia.bortal.exceptions.PermissionDeniedException;
import fi.insomnia.bortal.utilities.ThreadLocalContextHolder;
/**
......@@ -71,9 +73,32 @@ public class HostnameFilter implements Filter {
}
// pass the request along the filter chain
try {
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();
}
}
/**
* @see Filter#init(FilterConfig)
......
......@@ -12,6 +12,7 @@ import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import javax.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -44,20 +45,18 @@ public class BortalExceptionHandler extends ExceptionHandlerWrapper {
errorpage(i, t, "viewExpired");
}
Throwable cause = t;
for(int loop = 0; loop < 20 && cause != null; ++loop) {
logger.debug("Cause not null, but {}, checking" + t.getClass().toString());
Throwable cause = t.getCause();
for (int loop = 0; loop < 20 && cause != null; ++loop) {
logger.debug("Cause not null, but {}: {}, checking" + cause.getClass(), cause.getMessage());
if (cause instanceof PermissionDeniedException ||
cause instanceof EJBAccessException ||
cause instanceof PermissionDeniedException ) {
logger.debug("Found Permission Denied cause: {}", cause);
errorpage(i, t, "permissionDenied");
break;
}
cause instanceof PermissionDeniedException) {
logger.debug("Found Permission Denied cause: {}, {}", cause.getClass(), cause.getMessage());
// errorpage(i, t, "permissionDenied");
}
cause = cause.getCause();
}
}
// At this point, the queue will not contain any ViewExpiredEvents.
......@@ -75,9 +74,11 @@ public class BortalExceptionHandler extends ExceptionHandlerWrapper {
vee = (ViewExpiredException) t;
}
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
// Push some useful stuff to the request scope for
// use in the page
......
......@@ -67,6 +67,16 @@ public class SessionHandler {
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() {
FacesContext ctx = FacesContext.getCurrentInstance();
HttpSession sess = (HttpSession) ctx.getExternalContext().getSession(false);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!