From 8d99c88af55041ff06e6b9372b6b1f66220bed38 Mon Sep 17 00:00:00 2001
From: rsanchez <rsanchez@curisit.net>
Date: Mon, 10 Apr 2017 16:08:58 +0000
Subject: [PATCH] #3529 feature - Added applications to user profile and upgrade to angular4

---
 securis/src/main/java/net/curisit/securis/ioc/RequestsInterceptor.java |  288 +++++++++++++++++++++++++++++++--------------------------
 1 files changed, 156 insertions(+), 132 deletions(-)

diff --git a/securis/src/main/java/net/curisit/securis/ioc/RequestsInterceptor.java b/securis/src/main/java/net/curisit/securis/ioc/RequestsInterceptor.java
index 0ac32bb..391ec7f 100644
--- a/securis/src/main/java/net/curisit/securis/ioc/RequestsInterceptor.java
+++ b/securis/src/main/java/net/curisit/securis/ioc/RequestsInterceptor.java
@@ -21,12 +21,6 @@
 import javax.ws.rs.ext.WriterInterceptor;
 import javax.ws.rs.ext.WriterInterceptorContext;
 
-import net.curisit.securis.db.User;
-import net.curisit.securis.security.BasicSecurityContext;
-import net.curisit.securis.security.Securable;
-import net.curisit.securis.utils.CacheTTL;
-import net.curisit.securis.utils.TokenHelper;
-
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import org.jboss.resteasy.core.Dispatcher;
@@ -36,158 +30,188 @@
 import org.jboss.resteasy.spi.HttpRequest;
 import org.jboss.resteasy.spi.ResteasyProviderFactory;
 
+import net.curisit.securis.db.User;
+import net.curisit.securis.security.BasicSecurityContext;
+import net.curisit.securis.security.Securable;
+import net.curisit.securis.utils.CacheTTL;
+import net.curisit.securis.utils.TokenHelper;
+
 @Provider
 @Priority(Priorities.AUTHENTICATION)
 public class RequestsInterceptor implements ContainerRequestFilter, WriterInterceptor {
-    private static final Logger LOG = LogManager.getLogger(RequestsInterceptor.class);
+	private static final Logger LOG = LogManager.getLogger(RequestsInterceptor.class);
 
-    @Context
-    private HttpServletResponse servletResponse;
+	@Context
+	private HttpServletResponse servletResponse;
 
-    @Context
-    private HttpServletRequest servletRequest;
+	@Context
+	private HttpServletRequest servletRequest;
 
-    @Inject
-    private CacheTTL cache;
+	@Inject
+	private CacheTTL cache;
 
-    @Inject
-    private TokenHelper tokenHelper;
+	@Inject
+	private TokenHelper tokenHelper;
 
-    @Context
-    private Dispatcher dispatcher;
+	@Context
+	private Dispatcher dispatcher;
 
-    @Inject
-    private EntityManagerProvider emProvider;
+	@Inject
+	private EntityManagerProvider emProvider;
 
-    @Override
-    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
-        EntityManager em = emProvider.getEntityManager();
-        LOG.debug("GETTING EM: {}", em);
+	@Override
+	public void filter(ContainerRequestContext containerRequestContext) throws IOException {
+		EntityManager em = emProvider.getEntityManager();
+		LOG.debug("GETTING EM: {}", em);
 
-        ResteasyProviderFactory.pushContext(EntityManager.class, em);
+		ResteasyProviderFactory.pushContext(EntityManager.class, em);
 
-        ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) containerRequestContext
-                .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
-        Method method = methodInvoker.getMethod();
+		ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) containerRequestContext.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
+		Method method = methodInvoker.getMethod();
 
-        LOG.debug("Stored in context, em: {}, {}", em, method.toGenericString());
+		LOG.debug("Stored in context, em: {}, {}", em, method.toGenericString());
 
-        boolean next = checkSecurableMethods(containerRequestContext, method);
-        if (next) {
-            prepareTransaction(containerRequestContext, method, em);
-        }
-    }
+		boolean next = checkSecurableMethods(containerRequestContext, method);
+		if (next) {
+			prepareTransaction(containerRequestContext, method, em);
+		}
+	}
 
-    private void prepareTransaction(ContainerRequestContext containerRequestContext, Method method, EntityManager em) {
+	private void prepareTransaction(ContainerRequestContext containerRequestContext, Method method, EntityManager em) {
 
-        if (method.isAnnotationPresent(EnsureTransaction.class)) {
-            LOG.debug("Beginning a new transaction");
-            em.getTransaction().begin();
-        }
-    }
+		if (method.isAnnotationPresent(EnsureTransaction.class)) {
+			LOG.debug("Beginning a new transaction");
+			em.getTransaction().begin();
+		}
+	}
 
-    private boolean checkSecurableMethods(ContainerRequestContext containerRequestContext, Method method) {
-        if (!method.isAnnotationPresent(Securable.class)) {
-            return true;
-        }
-        String token = servletRequest.getHeader(TokenHelper.TOKEN_HEADER_PÀRAM);
-        if (token == null || !tokenHelper.isTokenValid(token)) {
-            LOG.warn("Access denied, Token not valid: {} for method: {}::{}", token, method.getDeclaringClass(), method.getName());
-            containerRequestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
-            return false;
-        } else {
+	private boolean checkSecurableMethods(ContainerRequestContext containerRequestContext, Method method) {
+		if (!method.isAnnotationPresent(Securable.class)) {
+			return true;
+		}
+		String token = servletRequest.getHeader(TokenHelper.TOKEN_HEADER_PÀRAM);
+		if (token == null || !tokenHelper.isTokenValid(token)) {
+			LOG.warn("Access denied, Token not valid: {} for method: {}::{}", token, method.getDeclaringClass(), method.getName());
+			containerRequestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
+			return false;
+		} else {
+			Securable securable = method.getAnnotation(Securable.class);
+			// If roles == 0 we only need to validate the token
+			String username = tokenHelper.extractUserFromToken(token);
+			int userRoles = getUserRoles(username);
+			if (securable.roles() != 0 && (securable.roles() & userRoles) == 0) {
+				LOG.warn("Method {} requires roles: {}, but user {} hasn't got them", method.getName(), securable.roles(), username);
+				containerRequestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
+				return false;
+			}
+			Set<Integer> orgs = getUserOrganizations(username);
+			Set<Integer> apps = getUserApplications(username);
 
-            // If roles == 0 we only need to validate the token
-            String username = tokenHelper.extractUserFromToken(token);
-            int userRoles = getUserRoles(username);
-            Set<Integer> orgs = getUserOrganizations(username);
+			BasicSecurityContext scw = new BasicSecurityContext(username, userRoles, servletRequest.isSecure());
+			scw.setOrganizationsIds(orgs);
+			scw.setApplicationsIds(apps);
+			containerRequestContext.setSecurityContext(scw);
+			// Next line provide injection in resource methods
+			ResteasyProviderFactory.pushContext(BasicSecurityContext.class, scw);
+			LOG.debug("Added custom SecurityContext for user {}, orgs: {}", username, orgs);
+		}
+		return true;
 
-            BasicSecurityContext scw = new BasicSecurityContext(username, userRoles, servletRequest.isSecure());
-            scw.setOrganizationsIds(orgs);
-            containerRequestContext.setSecurityContext(scw);
-            // Next line provide injection in resource methods
-            ResteasyProviderFactory.pushContext(BasicSecurityContext.class, scw);
-            LOG.debug("Added custom SecurityContext for user {}, orgs: {}", username, orgs);
-        }
-        return true;
+	}
 
-    }
+	private Set<Integer> getUserOrganizations(String username) {
+		@SuppressWarnings("unchecked")
+		Set<Integer> userOrgs = cache.get("orgs_" + username, Set.class);
+		if (userOrgs == null) {
+			EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
 
-    private Set<Integer> getUserOrganizations(String username) {
-        @SuppressWarnings("unchecked")
-        Set<Integer> userOrgs = cache.get("orgs_" + username, Set.class);
-        if (userOrgs == null) {
-            EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
+			// Theorically this shouldn't be never null, but just in case...
+			User user = em.find(User.class, username);
+			if (user != null) {
+				userOrgs = user.getAllOrgsIds();
+				// We store user orgs in cache only for one hour
+				cache.set("orgs_" + username, userOrgs, 3600);
+			}
+		}
 
-            // Theorically this shouldn't be never null, but just in case...
-            User user = em.find(User.class, username);
-            if (user != null) {
-                userOrgs = user.getAllOrgsIds();
-                // We store user orgs in cache only for one hour
-                cache.set("orgs_" + username, userOrgs, 3600);
-            }
-        }
+		return userOrgs;
+	}
 
-        return userOrgs;
-    }
+	private Set<Integer> getUserApplications(String username) {
+		@SuppressWarnings("unchecked")
+		Set<Integer> userApps = cache.get("apps_" + username, Set.class);
+		if (userApps == null) {
+			EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
 
-    private int getUserRoles(String username) {
-        if (username == null) {
-            return 0;
-        }
-        Integer userRoles = cache.get("roles_" + username, Integer.class);
-        if (userRoles == null) {
-            EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
+			// Theorically this shouldn't be never null, but just in case...
+			User user = em.find(User.class, username);
+			if (user != null) {
+				userApps = user.getAllAppsIds();
+				// We store user orgs in cache only for one hour
+				cache.set("apps_" + username, userApps, 3600);
+			}
+		}
 
-            User user = em.find(User.class, username);
-            if (user != null) {
-                userRoles = 0;
-                List<Integer> roles = user.getRoles();
-                if (roles != null) {
-                    for (Integer rol : roles) {
-                        userRoles += rol;
-                    }
-                }
-                // We store user roles in cache only for one hour
-                cache.set("roles_" + username, userRoles, 3600);
-                cache.set("orgs_" + username, user.getOrgsIds(), 3600);
-            }
-        }
-        return userRoles == null ? 0 : userRoles.intValue();
-    }
+		return userApps;
+	}
 
-    // @Override
-    public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
-        return null;
-    }
+	private int getUserRoles(String username) {
+		if (username == null) {
+			return 0;
+		}
+		Integer userRoles = cache.get("roles_" + username, Integer.class);
+		if (userRoles == null) {
+			EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
 
-    @Override
-    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
-        context.proceed();
-        EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
-        try {
-            if (em != null && em.getTransaction().isActive()) {
-                if (servletResponse.getStatus() == Status.OK.getStatusCode()) {
-                    em.getTransaction().commit();
-                    LOG.debug("COMMIT");
-                } else {
-                    // This code is never executed if there is an error the
-                    // filter chain is broken
-                    em.getTransaction().rollback();
-                    LOG.debug("ROLLBACK");
-                }
-            }
-        } finally {
-            if (em.isOpen()) {
-                LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
-                try {
-                    em.close();
-                } catch (Exception ex) {
-                    ex.printStackTrace();
-                    LOG.error("Error closing EM: {}, {}", em, ex);
-                }
-            }
-        }
-    }
+			User user = em.find(User.class, username);
+			if (user != null) {
+				userRoles = 0;
+				List<Integer> roles = user.getRoles();
+				if (roles != null) {
+					for (Integer rol : roles) {
+						userRoles += rol;
+					}
+				}
+				// We store user roles in cache only for one hour
+				cache.set("roles_" + username, userRoles, 3600);
+				cache.set("orgs_" + username, user.getOrgsIds(), 3600);
+			}
+		}
+		return userRoles == null ? 0 : userRoles.intValue();
+	}
+
+	// @Override
+	public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
+		return null;
+	}
+
+	@Override
+	public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
+		context.proceed();
+		EntityManager em = ResteasyProviderFactory.getContextData(EntityManager.class);
+		try {
+			if (em != null && em.getTransaction().isActive()) {
+				if (servletResponse.getStatus() == Status.OK.getStatusCode()) {
+					em.getTransaction().commit();
+					LOG.debug("COMMIT");
+				} else {
+					// This code is never executed if there is an error the
+					// filter chain is broken
+					em.getTransaction().rollback();
+					LOG.debug("ROLLBACK");
+				}
+			}
+		} finally {
+			if (em.isOpen()) {
+				LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
+				try {
+					em.close();
+				} catch (Exception ex) {
+					ex.printStackTrace();
+					LOG.error("Error closing EM: {}, {}", em, ex);
+				}
+			}
+		}
+	}
 
 }

--
Gitblit v1.3.2