From 1ed7bc42993b3d23d92dfc38dfd34026a4619ae7 Mon Sep 17 00:00:00 2001
From: rsanchez <rsanchez@curisit.net>
Date: Mon, 05 Dec 2016 15:23:22 +0000
Subject: [PATCH] #3410 #3411 fix - Fixed user roles and organizations and Pack date fields on saving action
---
securis/pom.xml | 2
securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java | 98 ++--
securis/src/main/java/net/curisit/securis/services/UserResource.java | 463 +++++++++---------
securis/changes.sql | 5
securis/src/main/java/net/curisit/securis/db/LicenseType.java | 185 +++---
securis/src/main/java/net/curisit/securis/services/PackResource.java | 642 ++++++++++++-------------
6 files changed, 685 insertions(+), 710 deletions(-)
diff --git a/securis/changes.sql b/securis/changes.sql
new file mode 100644
index 0000000..70bc51a
--- /dev/null
+++ b/securis/changes.sql
@@ -0,0 +1,5 @@
+ALTER TABLE license ADD activation_code VARCHAR(100) NULL;
+ALTER TABLE application ADD code VARCHAR(4) NULL;
+alter table application_metadata modify column value VARCHAR(512) NULL;
+alter table licensetype_metadata modify column value VARCHAR(512) NULL;
+alter table pack_metadata modify column value VARCHAR(512) NULL;
\ No newline at end of file
diff --git a/securis/pom.xml b/securis/pom.xml
index de4d451..fb1c231 100644
--- a/securis/pom.xml
+++ b/securis/pom.xml
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>net.curisit</groupId>
<artifactId>securis-server</artifactId>
- <version>1.1.7</version>
+ <version>1.1.8</version>
<name>SeCuris</name>
<description>CurisTEC Server Licenses</description>
<dependencies>
diff --git a/securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java b/securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
index a794bc5..8578d51 100644
--- a/securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
+++ b/securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
@@ -11,65 +11,65 @@
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
-import net.curisit.securis.services.exception.SeCurisServiceException;
-import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
-
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import net.curisit.securis.services.exception.SeCurisServiceException;
+import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
+
@Provider
public class DefaultExceptionHandler implements ExceptionMapper<Exception> {
- private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
+ private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
- public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;
- public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";
- public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";
+ public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;
+ public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";
+ public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";
- public DefaultExceptionHandler() {
- LOG.info("Creating DefaultExceptionHandler ");
- }
+ public DefaultExceptionHandler() {
+ LOG.info("Creating DefaultExceptionHandler ");
+ }
- @Context
- HttpServletRequest request;
- @Context
- SecurityContext bsc;
- @Context
- EntityManager em;
+ @Context
+ HttpServletRequest request;
+ @Context
+ SecurityContext bsc;
+ @Context
+ EntityManager em;
- @Override
- public Response toResponse(Exception e) {
- releaseEntityManager();
- if (e instanceof ForbiddenException) {
- LOG.warn("ForbiddenException: {}", e);
- return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
- .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();
- }
+ @Override
+ public Response toResponse(Exception e) {
+ releaseEntityManager();
+ if (e instanceof ForbiddenException) {
+ LOG.warn("ForbiddenException: {}", e.toString());
+ return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
+ .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();
+ }
- if (e instanceof SeCurisServiceException) {
- LOG.warn("SeCurisServiceException: {}", e);
- return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
- .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();
- }
+ if (e instanceof SeCurisServiceException) {
+ LOG.warn("SeCurisServiceException: {}", e.toString());
+ return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
+ .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();
+ }
- LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
- LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
- LOG.error("Request url: " + request.getRequestURL(), e);
- return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
- }
+ LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
+ LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
+ LOG.error("Request url: " + request.getRequestURL(), e);
+ return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
+ }
- private void releaseEntityManager() {
- try {
- if (em != null && em.isOpen()) {
- LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
- if (em.isJoinedToTransaction()) {
- em.getTransaction().rollback();
- LOG.info("ROLLBACK");
- }
- em.close();
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- LOG.error("Error closing EM: {}, {}", em, ex);
- }
- }
+ private void releaseEntityManager() {
+ try {
+ if (em != null && em.isOpen()) {
+ LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
+ if (em.isJoinedToTransaction()) {
+ em.getTransaction().rollback();
+ LOG.info("ROLLBACK");
+ }
+ em.close();
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ LOG.error("Error closing EM: {}, {}", em, ex);
+ }
+ }
}
diff --git a/securis/src/main/java/net/curisit/securis/db/LicenseType.java b/securis/src/main/java/net/curisit/securis/db/LicenseType.java
index cfaef9d..a34e3ef 100644
--- a/securis/src/main/java/net/curisit/securis/db/LicenseType.java
+++ b/securis/src/main/java/net/curisit/securis/db/LicenseType.java
@@ -37,125 +37,122 @@
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "license_type")
-@NamedQueries({
- @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt"),
- @NamedQuery(name = "list-application-license_types", query = "SELECT lt FROM LicenseType lt where lt.application.id = :appId")
-})
+@NamedQueries({ @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt"),
+ @NamedQuery(name = "list-application-license_types", query = "SELECT lt FROM LicenseType lt where lt.application.id = :appId") })
public class LicenseType implements Serializable {
- @SuppressWarnings("unused")
- private static final Logger LOG = LogManager.getLogger(LicenseType.class);
- private static final long serialVersionUID = 1L;
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LogManager.getLogger(LicenseType.class);
+ private static final long serialVersionUID = 1L;
- @Id
- @GeneratedValue
- private Integer id;
+ @Id
+ @GeneratedValue
+ private Integer id;
- private String code;
- private String name;
- private String description;
+ private String code;
+ private String name;
+ private String description;
- @Column(name = "creation_timestamp")
- @JsonProperty("creation_timestamp")
- private Date creationTimestamp;
+ @Column(name = "creation_timestamp")
+ @JsonProperty("creation_timestamp")
+ private Date creationTimestamp;
- @JsonIgnore
- @ManyToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "application_id")
- private Application application;
+ @JsonIgnore
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumn(name = "application_id")
+ private Application application;
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")
- @JsonManagedReference
- private Set<LicenseTypeMetadata> metadata;
+ @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")
+ @JsonManagedReference
+ private Set<LicenseTypeMetadata> metadata;
- public Set<LicenseTypeMetadata> getMetadata() {
- return metadata;
- }
+ public Set<LicenseTypeMetadata> getMetadata() {
+ return metadata;
+ }
- public void setMetadata(Set<LicenseTypeMetadata> metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(Set<LicenseTypeMetadata> metadata) {
+ this.metadata = metadata;
+ }
- public Integer getId() {
- return id;
- }
+ public Integer getId() {
+ return id;
+ }
- public void setId(Integer id) {
- this.id = id;
- }
+ public void setId(Integer id) {
+ this.id = id;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public String getCode() {
- return code;
- }
+ public String getCode() {
+ return code;
+ }
- public void setCode(String code) {
- this.code = code;
- }
+ public void setCode(String code) {
+ this.code = code;
+ }
- public Application getApplication() {
- LOG.info("Getting APP from LicType");
- return application;
- }
+ public Application getApplication() {
+ return application;
+ }
- @JsonProperty("application_name")
- public String getApplicationName() {
- return application == null ? null : application.getName();
- }
+ @JsonProperty("application_name")
+ public String getApplicationName() {
+ return application == null ? null : application.getName();
+ }
- @JsonProperty("application_id")
- public Integer getApplicationId() {
- return application == null ? null : application.getId();
- }
+ @JsonProperty("application_id")
+ public Integer getApplicationId() {
+ return application == null ? null : application.getId();
+ }
- @JsonProperty("application_id")
- public void setApplicationId(Integer appId) {
- if (appId == null) {
- application = null;
- } else {
- application = new Application();
- application.setId(appId);
- }
- }
+ @JsonProperty("application_id")
+ public void setApplicationId(Integer appId) {
+ if (appId == null) {
+ application = null;
+ } else {
+ application = new Application();
+ application.setId(appId);
+ }
+ }
- public void setApplication(Application application) {
- this.application = application;
- }
+ public void setApplication(Application application) {
+ this.application = application;
+ }
- public Date getCreationTimestamp() {
- return creationTimestamp;
- }
+ public Date getCreationTimestamp() {
+ return creationTimestamp;
+ }
- public void setCreationTimestamp(Date creationTimestamp) {
- this.creationTimestamp = creationTimestamp;
- }
+ public void setCreationTimestamp(Date creationTimestamp) {
+ this.creationTimestamp = creationTimestamp;
+ }
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof LicenseType))
- return false;
- LicenseType other = (LicenseType) obj;
- return id.equals(other.id);
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof LicenseType))
+ return false;
+ LicenseType other = (LicenseType) obj;
+ return id.equals(other.id);
+ }
- @Override
- public int hashCode() {
+ @Override
+ public int hashCode() {
- return (id == null ? 0 : id.hashCode());
- }
+ return (id == null ? 0 : id.hashCode());
+ }
}
diff --git a/securis/src/main/java/net/curisit/securis/services/PackResource.java b/securis/src/main/java/net/curisit/securis/services/PackResource.java
index 2c677b3..4bdf7f6 100644
--- a/securis/src/main/java/net/curisit/securis/services/PackResource.java
+++ b/securis/src/main/java/net/curisit/securis/services/PackResource.java
@@ -24,6 +24,9 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
import net.curisit.integrity.commons.Utils;
import net.curisit.securis.DefaultExceptionHandler;
import net.curisit.securis.SeCurisException;
@@ -44,9 +47,6 @@
import net.curisit.securis.utils.LicUtils;
import net.curisit.securis.utils.TokenHelper;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-
/**
* Pack resource, this service will provide methods to create, modify and delete
* packs
@@ -56,383 +56,363 @@
@Path("/pack")
public class PackResource {
- private static final Logger LOG = LogManager.getLogger(PackResource.class);
+ private static final Logger LOG = LogManager.getLogger(PackResource.class);
- @Inject
- TokenHelper tokenHelper;
+ @Inject
+ TokenHelper tokenHelper;
- @Context
- EntityManager em;
+ @Context
+ EntityManager em;
- @Inject
- private LicenseHelper licenseHelper;
+ @Inject
+ private LicenseHelper licenseHelper;
- /**
- *
- * @return the server version in format majorVersion.minorVersion
- */
- @GET
- @Path("/")
- @Securable
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response index(@Context BasicSecurityContext bsc) {
- LOG.info("Getting packs list ");
+ /**
+ *
+ * @return the server version in format majorVersion.minorVersion
+ */
+ @GET
+ @Path("/")
+ @Securable
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response index(@Context BasicSecurityContext bsc) {
+ LOG.info("Getting packs list ");
- // EntityManager em = emProvider.get();
- em.clear();
+ // EntityManager em = emProvider.get();
+ em.clear();
- TypedQuery<Pack> q;
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
- LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
- q = em.createNamedQuery("list-packs", Pack.class);
- } else {
- q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
- if (bsc.getOrganizationsIds() == null) {
- Response.ok().build();
- }
- q.setParameter("list_ids", bsc.getOrganizationsIds());
- }
+ TypedQuery<Pack> q;
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
+ LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
+ q = em.createNamedQuery("list-packs", Pack.class);
+ } else {
+ q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
+ if (bsc.getOrganizationsIds() == null) {
+ Response.ok().build();
+ }
+ q.setParameter("list_ids", bsc.getOrganizationsIds());
+ }
- List<Pack> list = q.getResultList();
+ List<Pack> list = q.getResultList();
- return Response.ok(list).build();
- }
+ return Response.ok(list).build();
+ }
- private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
- LOG.error("Pack with id {} not accesible by user {}", pack, user);
- return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
- }
+ private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
+ LOG.error("Pack with id {} not accesible by user {}", pack, user);
+ return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
+ }
- /**
- *
- * @return the server version in format majorVersion.minorVersion
- */
- @GET
- @Path("/{packId}")
- @Securable
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
- LOG.info("Getting pack data for id: {}: ", packId);
- if (packId == null || "".equals(packId)) {
- LOG.error("Pack ID is mandatory");
- return Response.status(Status.NOT_FOUND).build();
- }
+ /**
+ *
+ * @return the server version in format majorVersion.minorVersion
+ */
+ @GET
+ @Path("/{packId}")
+ @Securable
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
+ LOG.info("Getting pack data for id: {}: ", packId);
+ if (packId == null || "".equals(packId)) {
+ LOG.error("Pack ID is mandatory");
+ return Response.status(Status.NOT_FOUND).build();
+ }
- // EntityManager em = emProvider.get();
- em.clear();
- Pack pack = em.find(Pack.class, packId);
- if (pack == null) {
- LOG.error("Pack with id {} not found in DB", packId);
- return Response.status(Status.NOT_FOUND).build();
- }
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE)
- && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {
- return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
- }
- return Response.ok(pack).build();
- }
+ // EntityManager em = emProvider.get();
+ em.clear();
+ Pack pack = em.find(Pack.class, packId);
+ if (pack == null) {
+ LOG.error("Pack with id {} not found in DB", packId);
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE) && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {
+ return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
+ }
+ return Response.ok(pack).build();
+ }
- @POST
- @Path("/")
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- @EnsureTransaction
- public Response create(Pack pack, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
- LOG.info("Creating new pack");
- // EntityManager em = emProvider.get();
+ @POST
+ @Path("/")
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ @EnsureTransaction
+ public Response create(Pack pack, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
+ LOG.info("Creating new pack");
+ // EntityManager em = emProvider.get();
- if (checkIfCodeExists(pack.getCode(), em)) {
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is already used in an existing pack");
- }
+ if (checkIfCodeExists(pack.getCode(), em)) {
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is already used in an existing pack");
+ }
- try {
- setPackOrganization(pack, pack.getOrgId(), em);
- } catch (SeCurisException e) {
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
- }
+ try {
+ setPackOrganization(pack, pack.getOrgId(), em);
+ } catch (SeCurisException e) {
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
+ }
- try {
- setPackLicenseType(pack, pack.getLicTypeId(), em);
- } catch (SeCurisException e) {
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
- }
+ try {
+ setPackLicenseType(pack, pack.getLicTypeId(), em);
+ } catch (SeCurisException e) {
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
+ }
- User user = em.find(User.class, bsc.getUserPrincipal().getName());
+ User user = em.find(User.class, bsc.getUserPrincipal().getName());
- pack.setStatus(PackStatus.CREATED);
- pack.setCreatedBy(user);
- pack.setCreationTimestamp(new Date());
- em.persist(pack);
- Set<PackMetadata> newMD = pack.getMetadata();
+ pack.setStatus(PackStatus.CREATED);
+ pack.setCreatedBy(user);
+ pack.setCreationTimestamp(new Date());
+ em.persist(pack);
+ Set<PackMetadata> newMD = pack.getMetadata();
- if (newMD != null) {
- for (PackMetadata md : newMD) {
- md.setPack(pack);
- em.persist(md);
- }
- }
- pack.setMetadata(newMD);
- return Response.ok(pack).build();
- }
+ if (newMD != null) {
+ for (PackMetadata md : newMD) {
+ md.setPack(pack);
+ em.persist(md);
+ }
+ }
+ pack.setMetadata(newMD);
+ return Response.ok(pack).build();
+ }
- /**
- * Check if there is some pack with the same code
- *
- * @param code
- * Pack code
- * @param em
- * DB session object
- * @return <code>true</code> if code is already used, <code>false</code>
- * otherwise
- */
- private boolean checkIfCodeExists(String code, EntityManager em) {
- TypedQuery<Pack> query = em.createNamedQuery("pack-by-code", Pack.class);
- query.setParameter("code", code);
- int packs = query.getResultList().size();
- return packs > 0;
- }
+ /**
+ * Check if there is some pack with the same code
+ *
+ * @param code
+ * Pack code
+ * @param em
+ * DB session object
+ * @return <code>true</code> if code is already used, <code>false</code>
+ * otherwise
+ */
+ private boolean checkIfCodeExists(String code, EntityManager em) {
+ TypedQuery<Pack> query = em.createNamedQuery("pack-by-code", Pack.class);
+ query.setParameter("code", code);
+ int packs = query.getResultList().size();
+ return packs > 0;
+ }
- /**
- *
- * @return The next available code suffix in pack for license code
- * @throws SeCurisServiceException
- */
- @GET
- @Path("/{packId}/next_license_code")
- @Securable
- @Produces({
- MediaType.TEXT_PLAIN
- })
- public Response getCodeSuffix(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
- // EntityManager em = emProvider.get();
+ /**
+ *
+ * @return The next available code suffix in pack for license code
+ * @throws SeCurisServiceException
+ */
+ @GET
+ @Path("/{packId}/next_license_code")
+ @Securable
+ @Produces({ MediaType.TEXT_PLAIN })
+ public Response getCodeSuffix(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
+ // EntityManager em = emProvider.get();
- if (packId == null) {
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is mandatory");
- }
- Integer codeSuffix = licenseHelper.getNextCodeSuffix(packId, em);
- Pack pack = em.find(Pack.class, packId);
- ;
+ if (packId == null) {
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is mandatory");
+ }
+ Integer codeSuffix = licenseHelper.getNextCodeSuffix(packId, em);
+ Pack pack = em.find(Pack.class, packId);
+ ;
- String licCode = LicUtils.getLicenseCode(pack.getCode(), codeSuffix);
- return Response.ok(licCode).build();
- }
+ String licCode = LicUtils.getLicenseCode(pack.getCode(), codeSuffix);
+ return Response.ok(licCode).build();
+ }
- private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
- LicenseType lt = null;
- if (licTypeId != null) {
- lt = em.find(LicenseType.class, pack.getLicTypeId());
- if (lt == null) {
- LOG.error("Pack license type with id {} not found in DB", licTypeId);
- throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
- }
- }
- pack.setLicenseType(lt);
- }
+ private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
+ LicenseType lt = null;
+ if (licTypeId != null) {
+ lt = em.find(LicenseType.class, pack.getLicTypeId());
+ if (lt == null) {
+ LOG.error("Pack license type with id {} not found in DB", licTypeId);
+ throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
+ }
+ }
+ pack.setLicenseType(lt);
+ }
- private Set<String> getMdKeys(Set<PackMetadata> mds) {
- Set<String> ids = new HashSet<String>();
- if (mds != null) {
- for (PackMetadata md : mds) {
- ids.add(md.getKey());
- }
- }
- return ids;
- }
+ private Set<String> getMdKeys(Set<PackMetadata> mds) {
+ Set<String> ids = new HashSet<String>();
+ if (mds != null) {
+ for (PackMetadata md : mds) {
+ ids.add(md.getKey());
+ }
+ }
+ return ids;
+ }
- @PUT
- @POST
- @Path("/{packId}")
- @EnsureTransaction
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response modify(Pack pack, @PathParam("packId") Integer packId) {
- LOG.info("Modifying pack with id: {}", packId);
- // EntityManager em = emProvider.get();
- Pack currentPack = em.find(Pack.class, packId);
+ @PUT
+ @POST
+ @Path("/{packId}")
+ @EnsureTransaction
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response modify(Pack pack, @PathParam("packId") Integer packId) {
+ LOG.info("Modifying pack with id: {}", packId);
+ // EntityManager em = emProvider.get();
+ Pack currentPack = em.find(Pack.class, packId);
- try {
- setPackOrganization(currentPack, pack.getOrgId(), em);
- } catch (SeCurisException e) {
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
- }
+ try {
+ setPackOrganization(currentPack, pack.getOrgId(), em);
+ } catch (SeCurisException e) {
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
+ }
- try {
- setPackLicenseType(currentPack, pack.getLicTypeId(), em);
- } catch (SeCurisException e) {
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
- }
+ try {
+ setPackLicenseType(currentPack, pack.getLicTypeId(), em);
+ } catch (SeCurisException e) {
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
+ }
- currentPack.setLicensePreactivation(pack.isLicensePreactivation());
- currentPack.setCode(pack.getCode());
- currentPack.setComments(pack.getComments());
- currentPack.setNumLicenses(pack.getNumLicenses());
- currentPack.setPreactivationValidPeriod(pack.getPreactivationValidPeriod());
- currentPack.setRenewValidPeriod(pack.getRenewValidPeriod());
+ currentPack.setLicensePreactivation(pack.isLicensePreactivation());
+ currentPack.setCode(pack.getCode());
+ currentPack.setComments(pack.getComments());
+ currentPack.setNumLicenses(pack.getNumLicenses());
+ currentPack.setPreactivationValidPeriod(pack.getPreactivationValidPeriod());
+ currentPack.setRenewValidPeriod(pack.getRenewValidPeriod());
+ currentPack.setInitValidDate(pack.getInitValidDate());
+ currentPack.setEndValidDate(pack.getEndValidDate());
- Set<PackMetadata> newMD = pack.getMetadata();
- Set<String> newMdKeys = getMdKeys(newMD);
- for (PackMetadata currentMd : currentPack.getMetadata()) {
- if (!newMdKeys.contains(currentMd.getKey())) {
- em.remove(currentMd);
- }
- }
+ Set<PackMetadata> newMD = pack.getMetadata();
+ Set<String> newMdKeys = getMdKeys(newMD);
+ for (PackMetadata currentMd : currentPack.getMetadata()) {
+ if (!newMdKeys.contains(currentMd.getKey())) {
+ em.remove(currentMd);
+ }
+ }
- if (newMD != null) {
- Set<PackMetadata> oldMD = currentPack.getMetadata();
- Set<String> oldMdKeys = getMdKeys(newMD);
- for (PackMetadata md : newMD) {
- if (oldMdKeys.contains(md.getKey())) {
- em.merge(md);
- } else {
- md.setPack(currentPack);
- em.persist(md);
- }
- }
- }
- currentPack.setMetadata(newMD);
- em.merge(currentPack);
+ if (newMD != null) {
+ Set<String> oldMdKeys = getMdKeys(newMD);
+ for (PackMetadata md : newMD) {
+ if (oldMdKeys.contains(md.getKey())) {
+ em.merge(md);
+ } else {
+ md.setPack(currentPack);
+ em.persist(md);
+ }
+ }
+ }
+ currentPack.setMetadata(newMD);
+ em.merge(currentPack);
- return Response.ok(currentPack).build();
- }
+ return Response.ok(currentPack).build();
+ }
- @POST
- @Path("/{packId}/activate")
- @EnsureTransaction
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response activate(@PathParam("packId") Integer packId) throws SeCurisServiceException {
- LOG.info("Activating pack with id: {}", packId);
- // EntityManager em = emProvider.get();
+ @POST
+ @Path("/{packId}/activate")
+ @EnsureTransaction
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response activate(@PathParam("packId") Integer packId) throws SeCurisServiceException {
+ LOG.info("Activating pack with id: {}", packId);
+ // EntityManager em = emProvider.get();
- Pack currentPack = em.find(Pack.class, packId);
+ Pack currentPack = em.find(Pack.class, packId);
- if (!Pack.Status.isActionValid(Pack.Action.ACTIVATION, currentPack.getStatus())) {
- LOG.error("Pack with id {} cannot be activaed from status {}", packId, currentPack.getStatus().name());
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be activated in status: " + currentPack.getStatus().name());
- }
+ if (!Pack.Status.isActionValid(Pack.Action.ACTIVATION, currentPack.getStatus())) {
+ LOG.error("Pack with id {} cannot be activaed from status {}", packId, currentPack.getStatus().name());
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be activated in status: " + currentPack.getStatus().name());
+ }
- currentPack.setStatus(PackStatus.ACTIVE);
- em.persist(currentPack);
+ currentPack.setStatus(PackStatus.ACTIVE);
+ em.persist(currentPack);
- return Response.ok(currentPack).build();
- }
+ return Response.ok(currentPack).build();
+ }
- @POST
- @Path("/{packId}/putonhold")
- @EnsureTransaction
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response onhold(@PathParam("packId") Integer packId) throws SeCurisServiceException {
- LOG.info("Putting On hold pack with id: {}", packId);
- // EntityManager em = emProvider.get();
+ @POST
+ @Path("/{packId}/putonhold")
+ @EnsureTransaction
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response onhold(@PathParam("packId") Integer packId) throws SeCurisServiceException {
+ LOG.info("Putting On hold pack with id: {}", packId);
+ // EntityManager em = emProvider.get();
- Pack currentPack = em.find(Pack.class, packId);
+ Pack currentPack = em.find(Pack.class, packId);
- if (!Pack.Status.isActionValid(Pack.Action.PUT_ONHOLD, currentPack.getStatus())) {
- LOG.error("Pack with id {} cannot be put on hold from status {}", packId, currentPack.getStatus().name());
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be put on hold in status: " + currentPack.getStatus().name());
- }
+ if (!Pack.Status.isActionValid(Pack.Action.PUT_ONHOLD, currentPack.getStatus())) {
+ LOG.error("Pack with id {} cannot be put on hold from status {}", packId, currentPack.getStatus().name());
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be put on hold in status: " + currentPack.getStatus().name());
+ }
- currentPack.setStatus(PackStatus.ON_HOLD);
- em.persist(currentPack);
+ currentPack.setStatus(PackStatus.ON_HOLD);
+ em.persist(currentPack);
- return Response.ok(currentPack).build();
- }
+ return Response.ok(currentPack).build();
+ }
- @POST
- @Path("/{packId}/cancel")
- @EnsureTransaction
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response cancel(@PathParam("packId") Integer packId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc)
- throws SeCurisServiceException {
- LOG.info("Cancelling pack with id: {}", packId);
- // EntityManager em = emProvider.get();
+ @POST
+ @Path("/{packId}/cancel")
+ @EnsureTransaction
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response cancel(@PathParam("packId") Integer packId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
+ LOG.info("Cancelling pack with id: {}", packId);
+ // EntityManager em = emProvider.get();
- Pack currentPack = em.find(Pack.class, packId);
+ Pack currentPack = em.find(Pack.class, packId);
- if (!Pack.Status.isActionValid(Pack.Action.CANCEL, currentPack.getStatus())) {
- LOG.error("Pack with id {} cannot cancelled from status {}", packId, currentPack.getStatus().name());
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be cancelled in status: " + currentPack.getStatus().name());
- }
+ if (!Pack.Status.isActionValid(Pack.Action.CANCEL, currentPack.getStatus())) {
+ LOG.error("Pack with id {} cannot cancelled from status {}", packId, currentPack.getStatus().name());
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be cancelled in status: " + currentPack.getStatus().name());
+ }
- Set<License> licenses = currentPack.getLicenses();
- for (License license : licenses) {
- if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
- licenseHelper.cancelLicense(license, "Pack cancellation. " + reason, bsc, em);
- }
- }
- currentPack.setStatus(PackStatus.CANCELLED);
- em.persist(currentPack);
+ Set<License> licenses = currentPack.getLicenses();
+ for (License license : licenses) {
+ if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
+ licenseHelper.cancelLicense(license, "Pack cancellation. " + reason, bsc, em);
+ }
+ }
+ currentPack.setStatus(PackStatus.CANCELLED);
+ em.persist(currentPack);
- return Response.ok(currentPack).build();
- }
+ return Response.ok(currentPack).build();
+ }
- private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
- Organization org = null;
- if (orgId != null) {
- org = em.find(Organization.class, orgId);
- if (org == null) {
- LOG.error("Organization pack with id {} not found in DB", orgId);
- throw new SeCurisException("Pack organization not found with ID: " + orgId);
- }
- }
- currentPack.setOrganization(org);
- }
+ private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
+ Organization org = null;
+ if (orgId != null) {
+ org = em.find(Organization.class, orgId);
+ if (org == null) {
+ LOG.error("Organization pack with id {} not found in DB", orgId);
+ throw new SeCurisException("Pack organization not found with ID: " + orgId);
+ }
+ }
+ currentPack.setOrganization(org);
+ }
- @DELETE
- @Path("/{packId}")
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- @EnsureTransaction
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response delete(@PathParam("packId") String packId) throws SeCurisServiceException {
- LOG.info("Deleting pack with id: {}", packId);
- // EntityManager em = emProvider.get();
- Pack pack = em.find(Pack.class, Integer.parseInt(packId));
- if (pack == null) {
- LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId)
- .build();
- }
- // Pack metadata is removed in cascade automatically.
+ @DELETE
+ @Path("/{packId}")
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ @EnsureTransaction
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response delete(@PathParam("packId") String packId) throws SeCurisServiceException {
+ LOG.info("Deleting pack with id: {}", packId);
+ // EntityManager em = emProvider.get();
+ Pack pack = em.find(Pack.class, Integer.parseInt(packId));
+ if (pack == null) {
+ LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId).build();
+ }
+ // Pack metadata is removed in cascade automatically.
- Set<License> licenses = pack.getLicenses();
- for (License license : licenses) {
- if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "An active license cannot be deleted. License code: " + license.getCode());
- }
- em.remove(license);
- }
+ Set<License> licenses = pack.getLicenses();
+ for (License license : licenses) {
+ if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "An active license cannot be deleted. License code: " + license.getCode());
+ }
+ em.remove(license);
+ }
- em.remove(pack);
- return Response.ok(Utils.createMap("success", true, "id", packId)).build();
- }
+ em.remove(pack);
+ return Response.ok(Utils.createMap("success", true, "id", packId)).build();
+ }
}
diff --git a/securis/src/main/java/net/curisit/securis/services/UserResource.java b/securis/src/main/java/net/curisit/securis/services/UserResource.java
index 058289b..9a81e89 100644
--- a/securis/src/main/java/net/curisit/securis/services/UserResource.java
+++ b/securis/src/main/java/net/curisit/securis/services/UserResource.java
@@ -28,6 +28,9 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
import net.curisit.integrity.commons.Utils;
import net.curisit.securis.DefaultExceptionHandler;
import net.curisit.securis.SeCurisException;
@@ -38,10 +41,8 @@
import net.curisit.securis.security.Securable;
import net.curisit.securis.services.exception.SeCurisServiceException;
import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
+import net.curisit.securis.utils.CacheTTL;
import net.curisit.securis.utils.TokenHelper;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
/**
* User resource
@@ -52,266 +53,258 @@
@RequestScoped
public class UserResource {
- @Inject
- TokenHelper tokenHelper;
+ @Inject
+ TokenHelper tokenHelper;
- @Context
- EntityManager em;
+ @Inject
+ private CacheTTL cache;
- private static final Logger LOG = LogManager.getLogger(UserResource.class);
+ @Context
+ EntityManager em;
- public UserResource() {
- }
+ private static final Logger LOG = LogManager.getLogger(UserResource.class);
- /**
- *
- * @return the server version in format majorVersion.minorVersion
- */
- @GET
- @Path("/")
- @Produces({
- MediaType.APPLICATION_JSON
- })
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- public Response index() {
- LOG.info("Getting users list ");
+ public UserResource() {
+ }
- // EntityManager em = emProvider.get();
- em.clear();
- TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
+ /**
+ *
+ * @return the server version in format majorVersion.minorVersion
+ */
+ @GET
+ @Path("/")
+ @Produces({ MediaType.APPLICATION_JSON })
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ public Response index() {
+ LOG.info("Getting users list ");
- List<User> list = q.getResultList();
+ // EntityManager em = emProvider.get();
+ em.clear();
+ TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
- return Response.ok(list).build();
- }
+ List<User> list = q.getResultList();
- /**
- *
- * @return The user
- */
- @GET
- @Path("/{uid}")
- @Produces({
- MediaType.APPLICATION_JSON
- })
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
- LOG.info("Getting user data for id: {}: ", uid);
- if (uid == null || "".equals(uid)) {
- LOG.error("User ID is mandatory");
- return Response.status(Status.NOT_FOUND).build();
- }
+ return Response.ok(list).build();
+ }
- // EntityManager em = emProvider.get();
- em.clear();
- User lt = em.find(User.class, uid);
- if (lt == null) {
- LOG.error("User with id {} not found in DB", uid);
- return Response.status(Status.NOT_FOUND).build();
- }
- return Response.ok(lt).build();
- }
+ /**
+ *
+ * @return The user
+ */
+ @GET
+ @Path("/{uid}")
+ @Produces({ MediaType.APPLICATION_JSON })
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
+ LOG.info("Getting user data for id: {}: ", uid);
+ if (uid == null || "".equals(uid)) {
+ LOG.error("User ID is mandatory");
+ return Response.status(Status.NOT_FOUND).build();
+ }
- @POST
- @Path("/")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- @EnsureTransaction
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
- LOG.info("Creating new user");
- // EntityManager em = emProvider.get();
- User currentUser = em.find(User.class, user.getUsername());
- if (currentUser != null) {
- LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());
- return modify(user, user.getUsername(), token);
- }
+ // EntityManager em = emProvider.get();
+ em.clear();
+ User lt = em.find(User.class, uid);
+ if (lt == null) {
+ LOG.error("User with id {} not found in DB", uid);
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ return Response.ok(lt).build();
+ }
- try {
- this.setUserOrg(user, user.getOrgsIds(), em);
- } catch (SeCurisException e) {
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
- }
- if (user.getPassword() != null && !"".equals(user.getPassword())) {
- user.setPassword(Utils.sha256(user.getPassword()));
- } else {
- return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE)
- .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "User password is mandatory").build();
- }
- user.setModificationTimestamp(new Date());
- user.setLastLogin(null);
- user.setCreationTimestamp(new Date());
- em.persist(user);
+ @POST
+ @Path("/")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ @EnsureTransaction
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
+ LOG.info("Creating new user");
+ // EntityManager em = emProvider.get();
+ User currentUser = em.find(User.class, user.getUsername());
+ if (currentUser != null) {
+ LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());
+ return modify(user, user.getUsername(), token);
+ }
- return Response.ok(user).build();
- }
+ try {
+ this.setUserOrg(user, user.getOrgsIds(), em);
+ } catch (SeCurisException e) {
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
+ }
+ if (user.getPassword() != null && !"".equals(user.getPassword())) {
+ user.setPassword(Utils.sha256(user.getPassword()));
+ } else {
+ return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "User password is mandatory")
+ .build();
+ }
+ user.setModificationTimestamp(new Date());
+ user.setLastLogin(null);
+ user.setCreationTimestamp(new Date());
+ em.persist(user);
- private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {
- Set<Organization> orgs = null;
- if (orgsIds != null && !orgsIds.isEmpty()) {
- orgs = new HashSet<>();
- for (Integer orgId : orgsIds) {
- Organization o = em.find(Organization.class, orgId);
- if (o == null) {
- LOG.error("User organization with id {} not found in DB", orgId);
- throw new SeCurisException("User's organization not found with ID: " + orgId);
- }
- orgs.add(o);
- }
- }
+ return Response.ok(user).build();
+ }
- user.setOrganizations(orgs);
+ private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {
+ Set<Organization> orgs = null;
+ if (orgsIds != null && !orgsIds.isEmpty()) {
+ orgs = new HashSet<>();
+ for (Integer orgId : orgsIds) {
+ Organization o = em.find(Organization.class, orgId);
+ if (o == null) {
+ LOG.error("User organization with id {} not found in DB", orgId);
+ throw new SeCurisException("User's organization not found with ID: " + orgId);
+ }
+ orgs.add(o);
+ }
+ }
- }
+ user.setOrganizations(orgs);
- @PUT
- @POST
- @Path("/{uid}")
- @EnsureTransaction
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces({
- MediaType.APPLICATION_JSON
- })
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
- LOG.info("Modifying user with id: {}", uid);
- // EntityManager em = emProvider.get();
- User currentUser = em.find(User.class, uid);
- if (currentUser == null) {
- LOG.info("User with id {} not found in DB, we'll try to create it", uid);
- return create(user, token);
- }
+ }
- try {
- this.setUserOrg(currentUser, user.getOrgsIds(), em);
- } catch (SeCurisException e) {
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
- }
- currentUser.setFirstName(user.getFirstName());
- currentUser.setLastName(user.getLastName());
- currentUser.setRoles(user.getRoles());
- currentUser.setLang(user.getLang());
- currentUser.setModificationTimestamp(new Date());
- if (user.getPassword() != null && !"".equals(user.getPassword())) {
- currentUser.setPassword(Utils.sha256(user.getPassword()));
- } else {
- // Password has not been modified
- // return
- // Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
- // "User password is mandatory").build();
- }
+ @PUT
+ @POST
+ @Path("/{uid}")
+ @EnsureTransaction
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces({ MediaType.APPLICATION_JSON })
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
+ LOG.info("Modifying user with id: {}", uid);
+ // EntityManager em = emProvider.get();
+ User currentUser = em.find(User.class, uid);
+ if (currentUser == null) {
+ LOG.info("User with id {} not found in DB, we'll try to create it", uid);
+ return create(user, token);
+ }
- currentUser.setLastLogin(user.getLastLogin());
+ try {
+ this.setUserOrg(currentUser, user.getOrgsIds(), em);
+ } catch (SeCurisException e) {
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
+ }
+ currentUser.setFirstName(user.getFirstName());
+ currentUser.setLastName(user.getLastName());
+ currentUser.setRoles(user.getRoles());
+ currentUser.setLang(user.getLang());
+ currentUser.setModificationTimestamp(new Date());
+ if (user.getPassword() != null && !"".equals(user.getPassword())) {
+ currentUser.setPassword(Utils.sha256(user.getPassword()));
+ } else {
+ // Password has not been modified
+ // return
+ // Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
+ // "User password is mandatory").build();
+ }
- em.persist(currentUser);
+ currentUser.setLastLogin(user.getLastLogin());
- return Response.ok(currentUser).build();
- }
+ em.persist(currentUser);
+ clearUserCache(currentUser.getUsername());
- @DELETE
- @Path("/{uid}")
- @EnsureTransaction
- @Produces({
- MediaType.APPLICATION_JSON
- })
- @Securable
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
- public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
- LOG.info("Deleting app with id: {}", uid);
- // EntityManager em = emProvider.get();
- User app = em.find(User.class, uid);
- if (app == null) {
- LOG.error("User with id {} can not be deleted, It was not found in DB", uid);
- return Response.status(Status.NOT_FOUND).build();
- }
+ return Response.ok(currentUser).build();
+ }
- em.remove(app);
- return Response.ok(Utils.createMap("success", true, "id", uid)).build();
- }
+ @DELETE
+ @Path("/{uid}")
+ @EnsureTransaction
+ @Produces({ MediaType.APPLICATION_JSON })
+ @Securable
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
+ public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
+ LOG.info("Deleting app with id: {}", uid);
+ // EntityManager em = emProvider.get();
+ User user = em.find(User.class, uid);
+ if (user == null) {
+ LOG.error("User with id {} can not be deleted, It was not found in DB", uid);
+ return Response.status(Status.NOT_FOUND).build();
+ }
- @POST
- @Path("/login")
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response login(@FormParam("username") String username, @FormParam("password") String password, @Context HttpServletRequest request)
- throws SeCurisServiceException {
- LOG.info("index session: " + request.getSession());
- LOG.info("user: {}, pass: {}", username, password);
- LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
- LOG.info("is user in role: {} == {} ? ", "admin", request.isUserInRole("admin"));
+ em.remove(user);
+ clearUserCache(user.getUsername());
+ return Response.ok(Utils.createMap("success", true, "id", uid)).build();
+ }
- // EntityManager em = emProvider.get();
- User user = em.find(User.class, username);
- if (user == null) {
- LOG.error("Inknown username {} used in login service", username);
- throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
- }
- String securedPassword = Utils.sha256(password);
+ private void clearUserCache(String username) {
+ cache.remove("roles_" + username);
+ cache.remove("orgs_" + username);
+ }
- if (securedPassword == null || !securedPassword.equals(user.getPassword())) {
- throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
- }
- user.setLastLogin(new Date());
- em.getTransaction().begin();
- try {
- em.persist(user);
- em.getTransaction().commit();
- } catch (PersistenceException ex) {
- LOG.error("Error updating last login date for user: {}", username);
- LOG.error(ex);
- em.getTransaction().rollback();
- }
- String tokenAuth = tokenHelper.generateToken(username);
- return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
- }
+ @POST
+ @Path("/login")
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response login(@FormParam("username") String username, @FormParam("password") String password, @Context HttpServletRequest request) throws SeCurisServiceException {
+ LOG.info("index session: " + request.getSession());
- /**
- * Check if current token is valid
- *
- * @param user
- * @param password
- * @param request
- * @return
- */
- @POST
- @Path("/check")
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
- if (token == null) {
- token = token2;
- }
- if (token == null) {
- return Response.status(Status.FORBIDDEN).build();
- }
+ // EntityManager em = emProvider.get();
+ User user = em.find(User.class, username);
+ if (user == null) {
+ LOG.error("Unknown username {} used in login service", username);
+ throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
+ }
+ String securedPassword = Utils.sha256(password);
- LOG.info("Token : " + token);
- String user = tokenHelper.extractUserFromToken(token);
- LOG.info("Token user: " + user);
- Date date = tokenHelper.extractDateCreationFromToken(token);
- LOG.info("Token date: " + date);
- boolean valid = tokenHelper.isTokenValid(token);
+ if (securedPassword == null || !securedPassword.equals(user.getPassword())) {
+ throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
+ }
+ user.setLastLogin(new Date());
+ em.getTransaction().begin();
+ try {
+ em.persist(user);
+ em.getTransaction().commit();
+ } catch (PersistenceException ex) {
+ LOG.error("Error updating last login date for user: {}", username);
+ LOG.error(ex);
+ em.getTransaction().rollback();
+ }
+ clearUserCache(username);
- LOG.info("Is Token valid: " + valid);
+ String tokenAuth = tokenHelper.generateToken(username);
+ return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
+ }
- return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();
- }
+ /**
+ * Check if current token is valid
+ *
+ * @param user
+ * @param password
+ * @param request
+ * @return
+ */
+ @POST
+ @Path("/check")
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
+ if (token == null) {
+ token = token2;
+ }
+ if (token == null) {
+ return Response.status(Status.FORBIDDEN).build();
+ }
- @GET
- @Path("/logout")
- @Produces({
- MediaType.APPLICATION_JSON
- })
- public Response logout(@Context HttpServletRequest request) {
- request.getSession().invalidate();
- return Response.ok().build();
- }
+ LOG.info("Token : " + token);
+ String user = tokenHelper.extractUserFromToken(token);
+ LOG.info("Token user: " + user);
+ Date date = tokenHelper.extractDateCreationFromToken(token);
+ LOG.info("Token date: " + date);
+ boolean valid = tokenHelper.isTokenValid(token);
+
+ LOG.info("Is Token valid: " + valid);
+
+ return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();
+ }
+
+ @GET
+ @Path("/logout")
+ @Produces({ MediaType.APPLICATION_JSON })
+ public Response logout(@Context HttpServletRequest request) {
+ request.getSession().invalidate();
+ return Response.ok().build();
+ }
}
--
Gitblit v1.3.2