package net.curisit.securis.services; import java.io.IOException; import java.util.Date; import java.util.List; import javax.inject.Inject; import javax.inject.Provider; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; 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; import javax.ws.rs.core.Response.Status; import net.curisit.integrity.commons.Utils; import net.curisit.securis.DefaultExceptionHandler; import net.curisit.securis.db.License; import net.curisit.securis.db.LicenseHistory; 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.services.exception.SeCurisServiceException; import net.curisit.securis.utils.TokenHelper; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.persist.Transactional; /** * License resource, this service will provide methods to create, modify and delete licenses * * @author roberto */ @Path("/license") public class LicenseResource { private static final Logger log = LoggerFactory.getLogger(LicenseResource.class); @Inject TokenHelper tokenHelper; @Inject Provider emProvider; public LicenseResource() { } /** * * @return the server version in format majorVersion.minorVersion */ @GET @Path("/") @Securable @Produces( { MediaType.APPLICATION_JSON }) public Response index(@QueryParam("packId") Integer packId, @Context BasicSecurityContext bsc) { log.info("Getting licenses list "); EntityManager em = emProvider.get(); 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 q = em.createNamedQuery("list-licenses-by-pack", License.class); q.setParameter("packId", packId); List list = q.getResultList(); return Response.ok(list).build(); } /** * * @return the server version in format majorVersion.minorVersion * @throws SeCurisServiceException */ @GET @Path("/{licId}") @Securable @Produces( { MediaType.APPLICATION_JSON }) public Response get(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { log.info("Getting organization data for id: {}: ", licId); EntityManager em = emProvider.get(); License lic = getCurrentLicense(licId, bsc, em); return Response.ok(lic).build(); } /** * * @return The license file, only of license is active * @throws SeCurisServiceException */ @GET @Path("/{licId}/download") @Securable @Produces( { MediaType.APPLICATION_OCTET_STREAM }) public Response download(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { EntityManager em = emProvider.get(); License lic = getCurrentLicense(licId, bsc, em); if (lic.getLicenseData() == null) { log.error("License with id {} has not license file generated", licId, bsc.getUserPrincipal()); throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License has not contain data to generate license file"); } if (License.Status.isActionValid(License.Action.DOWNLOAD, lic.getStatus())) { log.error("License with id {} is not active, so It can not downloaded", licId, bsc.getUserPrincipal()); throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License is not active, so It can not be downloaded"); } return Response.ok(lic.getLicenseData()).build(); } @PUT @POST @Path("/{licId}/activate") @Securable @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces( { MediaType.APPLICATION_JSON }) public Response activate(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { EntityManager em = emProvider.get(); License lic = getCurrentLicense(licId, bsc, em); if (License.Status.isActionValid(License.Action.ACTIVATION, lic.getStatus())) { log.error("License with id {} can not be activated from current license status", licId); throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId + " can not be activated from the current license status"); } lic.setStatus(License.Status.ACTIVE); lic.setModificationTimestamp(new Date()); em.persist(lic); User user = getUser(bsc.getUserPrincipal().getName(), em); em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE)); return Response.ok(lic).build(); } @PUT @POST @Path("/{licId}/send") @Securable @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces( { MediaType.APPLICATION_JSON }) public Response send(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { EntityManager em = emProvider.get(); License lic = getCurrentLicense(licId, bsc, em); User user = getUser(bsc.getUserPrincipal().getName(), em); // TODO: Send mail with lic file lic.setModificationTimestamp(new Date()); em.persist(lic); em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.SEND, "Email sent to: " + lic.getEmail())); return Response.ok(lic).build(); } @PUT @POST @Path("/{licId}/cancel") @Securable @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces( { MediaType.APPLICATION_JSON }) public Response cancel(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { EntityManager em = emProvider.get(); License lic = getCurrentLicense(licId, bsc, em); if (License.Status.isActionValid(License.Action.CANCEL, lic.getStatus())) { log.error("License with id {} can not be canceled from current license status", licId); throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId + " can not be canceled from the current license status"); } lic.setStatus(License.Status.CANCELED); lic.setModificationTimestamp(new Date()); em.persist(lic); User user = getUser(bsc.getUserPrincipal().getName(), em); em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CANCEL)); return Response.ok(lic).build(); } @POST @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Securable @Produces( { MediaType.APPLICATION_JSON }) @Transactional public Response create(License lic, @Context BasicSecurityContext bsc) throws SeCurisServiceException { log.info("Creating new license from create()"); 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(); } 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(); } } } } User createdBy = getUser(bsc.getUserPrincipal().getName(), em); // ODO: Manage status if request data is set lic.setCreatedBy(createdBy); lic.setStatus(License.Status.CREATED); lic.setCreationTimestamp(new Date()); lic.setModificationTimestamp(lic.getCreationTimestamp()); em.persist(lic); em.persist(createLicenseHistoryAction(lic, createdBy, LicenseHistory.Actions.CREATE)); return Response.ok(lic).build(); } @POST @Path("/") @Consumes(MediaType.MULTIPART_FORM_DATA) @Securable @Produces( { MediaType.APPLICATION_JSON }) @Transactional public Response createWithFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException { License lic = new License(); lic.setCode(mpfdi.getFormDataPart("code", String.class, null)); lic.setRequestData(mpfdi.getFormDataPart("request_data", String.class, null)); lic.setPackId(mpfdi.getFormDataPart("pack_id", Integer.class, null)); lic.setFullName(mpfdi.getFormDataPart("full_name", String.class, null)); lic.setEmail(mpfdi.getFormDataPart("email", String.class, null)); lic.setComments(mpfdi.getFormDataPart("comments", String.class, null)); return create(lic, bsc); } @PUT @POST @Path("/{licId}") @Securable @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces( { MediaType.APPLICATION_JSON }) public Response modify(License lic, @PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { log.info("Modifying organization with id: {}", licId); EntityManager em = emProvider.get(); License currentLicense = getCurrentLicense(licId, bsc, em); currentLicense.setCode(lic.getCode()); currentLicense.setFullName(lic.getFullName()); currentLicense.setEmail(lic.getEmail()); currentLicense.setRequestData(lic.getRequestData()); currentLicense.setModificationTimestamp(new Date()); em.persist(currentLicense); return Response.ok(currentLicense).build(); } @DELETE @Path("/{licId}") @Transactional @Securable @Produces( { MediaType.APPLICATION_JSON }) public Response delete(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException { log.info("Deleting license with id: {}", licId); EntityManager em = emProvider.get(); License lic = getCurrentLicense(licId, bsc, em); 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(); } private License getCurrentLicense(Integer licId, BasicSecurityContext bsc, EntityManager em) throws SeCurisServiceException { if (licId == null || licId.equals("")) { log.error("License ID is mandatory"); throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "Missing license ID"); } License lic = em.find(License.class, licId); if (lic == null) { log.error("License with id {} not found in DB", licId); throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "License not found for ID: " + licId); } 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()); throw new SeCurisServiceException(Status.UNAUTHORIZED.getStatusCode(), "Unathorized access to license data"); } } return lic; } private User getUser(String username, EntityManager em) throws SeCurisServiceException { User user = null; if (username != null) { user = em.find(User.class, username); if (user == null) { throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "User not found with username: " + username); } } return user; } private LicenseHistory createLicenseHistoryAction(License lic, User user, String action, String comments) { LicenseHistory lh = new LicenseHistory(); lh.setLicense(lic); lh.setUser(user); lh.setTimestamp(new Date()); lh.setAction(action); lh.setComments(comments); return lh; } private LicenseHistory createLicenseHistoryAction(License lic, User user, String action) { return createLicenseHistoryAction(lic, user, action, null); } }