From cbfe9207ad7c9bba96b39c550d250d12097fd06f Mon Sep 17 00:00:00 2001
From: Roberto Sánchez <roberto.sanchez@curisit.net>
Date: Thu, 23 Jan 2014 19:21:10 +0000
Subject: [PATCH] #395 feature - Implemented license section at 75%

---
 securis/src/main/java/net/curisit/securis/services/LicenseResource.java |  137 ++++++++++++++++++++++++++++++++-------------
 1 files changed, 98 insertions(+), 39 deletions(-)

diff --git a/securis/src/main/java/net/curisit/securis/services/LicenseResource.java b/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
index 0722d55..005ef97 100644
--- a/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
+++ b/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
@@ -7,16 +7,15 @@
 import javax.inject.Provider;
 import javax.persistence.EntityManager;
 import javax.persistence.TypedQuery;
-import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
 import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
@@ -28,6 +27,8 @@
 import net.curisit.securis.db.License;
 import net.curisit.securis.db.Pack;
 import net.curisit.securis.db.User;
+import net.curisit.securis.security.BasicSecurityContext;
+import net.curisit.securis.security.Securable;
 import net.curisit.securis.utils.TokenHelper;
 
 import org.slf4j.Logger;
@@ -40,7 +41,7 @@
  * 
  * @author roberto <roberto.sanchez@curisit.net>
  */
-@Path("/organization")
+@Path("/license")
 public class LicenseResource {
 
 	private static final Logger log = LoggerFactory.getLogger(LicenseResource.class);
@@ -60,14 +61,25 @@
 	 */
 	@GET
 	@Path("/")
+	@Securable
 	@Produces(
 		{ MediaType.APPLICATION_JSON })
-	public Response index() {
+	public Response index(@QueryParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
 		log.info("Getting licenses list ");
 
 		EntityManager em = emProvider.get();
-		TypedQuery<License> q = em.createNamedQuery("list-licenses-by-pack", License.class);
 
+		if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+			Pack pack = em.find(Pack.class, packId);
+			if (pack == null)
+				return Response.ok().build();
+			if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
+				log.error("Pack with id {} not accesible by user {}", pack, bsc.getUserPrincipal());
+				return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack licenses").build();
+			}
+		}
+		TypedQuery<License> q = em.createNamedQuery("list-licenses-by-pack", License.class);
+		q.setParameter("packId", packId);
 		List<License> list = q.getResultList();
 
 		return Response.ok(list).build();
@@ -79,9 +91,10 @@
 	 */
 	@GET
 	@Path("/{licId}")
+	@Securable
 	@Produces(
 		{ MediaType.APPLICATION_JSON })
-	public Response get(@PathParam("licId") String licId, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
+	public Response get(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) {
 		log.info("Getting organization data for id: {}: ", licId);
 		if (licId == null || licId.equals("")) {
 			log.error("License ID is mandatory");
@@ -89,21 +102,28 @@
 		}
 
 		EntityManager em = emProvider.get();
-		License lt = em.find(License.class, Integer.parseInt(licId));
-		if (lt == null) {
+		License lic = em.find(License.class, licId);
+		if (lic == null) {
 			log.error("License with id {} not found in DB", licId);
-			return Response.status(Status.NOT_FOUND).build();
+			return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License not found for ID: " + licId).build();
 		}
-		return Response.ok(lt).build();
+		if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+			if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
+				log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
+				return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
+			}
+		}
+		return Response.ok(lic).build();
 	}
 
 	@POST
 	@Path("/")
 	@Consumes(MediaType.APPLICATION_JSON)
+	@Securable
 	@Produces(
 		{ MediaType.APPLICATION_JSON })
 	@Transactional
-	public Response create(License lic, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
+	public Response create(License lic, @Context BasicSecurityContext bsc) {
 		log.info("Creating new organization");
 		EntityManager em = emProvider.get();
 		Pack pack = null;
@@ -112,6 +132,13 @@
 			if (pack == null) {
 				log.error("License pack with id {} not found in DB", lic.getPackId());
 				return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
+			} else {
+				if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+					if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
+						log.error("License for pack with id {} can not be created by user {}", pack.getId(), bsc.getUserPrincipal());
+						return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized action on pack license").build();
+					}
+				}
 			}
 		}
 
@@ -124,16 +151,11 @@
 			return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's created by user not found with ID: " + createdByUsername).build();
 		}
 
-		try {
-			User canceledBy = getUser(lic.getCanceledById(), em);
-			lic.setCanceledBy(canceledBy);
-		} catch (CurisException ex) {
-			String canceledByUsername = lic.getCreatedById();
-			log.error("License canceled by user with id {} not found in DB", canceledByUsername);
-			return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's canceled by user not found with ID: " + canceledByUsername).build();
-		}
-
+		// ODO: Manage status if request data is set
+		lic.setCanceledBy(null);
+		lic.setStatus(License.Status.CREATED);
 		lic.setCreationTimestamp(new Date());
+		lic.setModificationTimestamp(lic.getCreationTimestamp());
 		em.persist(lic);
 
 		return Response.ok(lic).build();
@@ -153,22 +175,30 @@
 	@PUT
 	@POST
 	@Path("/{licId}")
+	@Securable
 	@Transactional
 	@Consumes(MediaType.APPLICATION_JSON)
 	@Produces(
 		{ MediaType.APPLICATION_JSON })
-	public Response modify(License lic, @PathParam("licId") String licId, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
+	public Response modify(License lic, @PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) {
 		log.info("Modifying organization with id: {}", licId);
 		EntityManager em = emProvider.get();
 
-		Pack pack = null;
-		if (lic.getPackId() != null) {
-			pack = em.find(Pack.class, lic.getPackId());
-			if (pack == null) {
-				log.error("License pack with id {} not found in DB", lic.getPackId());
-				return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
-			}
-		}
+		// Pack pack = null;
+		// if (lic.getPackId() != null) {
+		// pack = em.find(Pack.class, lic.getPackId());
+		// if (pack == null) {
+		// log.error("License pack with id {} not found in DB", lic.getPackId());
+		// return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
+		// } else {
+		// if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+		// if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
+		// log.error("License for pack with id {} can not be modified by user {}", pack.getId(), bsc.getUserPrincipal());
+		// return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized action on pack license").build();
+		// }
+		// }
+		// }
+		// }
 		User createdBy = null;
 		try {
 			createdBy = getUser(lic.getCreatedById(), em);
@@ -186,30 +216,59 @@
 			log.error("License canceled by user with id {} not found in DB", canceledByUsername);
 			return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's canceled by user not found with ID: " + canceledByUsername).build();
 		}
+		License currentLicense = em.find(License.class, lic.getId());
+		if (currentLicense == null) {
+			log.error("License with id {} not found in DB", licId);
+			return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License not found for ID: " + licId).build();
+		}
+		if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+			if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
+				log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
+				return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
+			}
+		}
+		// TODO: set status based in current one and dates ? use custom actions ?
+		currentLicense.setCreatedBy(createdBy);
+		currentLicense.setCanceledBy(canceledBy);
+		// currentLicense.setPack(pack);
+		currentLicense.setCode(lic.getCode());
+		currentLicense.setFullName(lic.getFullName());
+		currentLicense.setEmail(lic.getEmail());
+		currentLicense.setRequestData(lic.getRequestData());
+		currentLicense.setModificationTimestamp(new Date());
+		em.persist(currentLicense);
 
-		lic.setCreatedBy(createdBy);
-		lic.setCanceledBy(canceledBy);
-		lic.setPack(pack);
-		em.persist(lic);
-
-		return Response.ok(lic).build();
+		return Response.ok(currentLicense).build();
 	}
 
 	@DELETE
 	@Path("/{licId}")
 	@Transactional
+	@Securable
 	@Produces(
 		{ MediaType.APPLICATION_JSON })
-	public Response delete(@PathParam("licId") String licId, @Context HttpServletRequest request) {
+	public Response delete(@PathParam("licId") String licId, @Context BasicSecurityContext bsc) {
 		log.info("Deleting license with id: {}", licId);
 		EntityManager em = emProvider.get();
-		License org = em.find(License.class, Integer.parseInt(licId));
-		if (org == null) {
+		License lic = em.find(License.class, Integer.parseInt(licId));
+		if (lic == null) {
 			log.error("License with id {} can not be deleted, It was not found in DB", licId);
 			return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License was not found, ID: " + licId).build();
 		}
 
-		em.remove(org);
+		if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+			if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
+				log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
+				return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
+			}
+		}
+
+		if (lic.getStatus() != License.Status.CANCELED || lic.getStatus() != License.Status.CREATED) {
+			log.error("License {} can not be deleted with status {}", lic.getCode(), lic.getStatus());
+			return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License can not be deleted in current status").build();
+		}
+
+		em.remove(lic);
 		return Response.ok(Utils.createMap("success", true, "id", licId)).build();
 	}
 

--
Gitblit v1.3.2