securis/changes.sql
.. .. @@ -0,0 +1,5 @@ 1 +ALTER TABLE license ADD activation_code VARCHAR(100) NULL;2 +ALTER TABLE application ADD code VARCHAR(4) NULL;3 +alter table application_metadata modify column value VARCHAR(512) NULL;4 +alter table licensetype_metadata modify column value VARCHAR(512) NULL;5 +alter table pack_metadata modify column value VARCHAR(512) NULL;securis/pom.xml
.. .. @@ -3,7 +3,7 @@ 3 3 <modelVersion>4.0.0</modelVersion> 4 4 <groupId>net.curisit</groupId> 5 5 <artifactId>securis-server</artifactId> 6 - <version>1.1.7</version>6 + <version>1.1.8</version>7 7 <name>SeCuris</name> 8 8 <description>CurisTEC Server Licenses</description> 9 9 <dependencies> securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
.. .. @@ -11,65 +11,65 @@ 11 11 import javax.ws.rs.ext.ExceptionMapper; 12 12 import javax.ws.rs.ext.Provider; 13 13 14 -import net.curisit.securis.services.exception.SeCurisServiceException;15 -import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;16 -17 14 import org.apache.logging.log4j.LogManager; 18 15 import org.apache.logging.log4j.Logger; 19 16 17 +import net.curisit.securis.services.exception.SeCurisServiceException;18 +import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;19 +20 20 @Provider 21 21 public class DefaultExceptionHandler implements ExceptionMapper<Exception> { 22 - private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);22 + private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);23 23 24 - public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;25 - public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";26 - public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";24 + public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;25 + public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";26 + public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";27 27 28 - public DefaultExceptionHandler() {29 - LOG.info("Creating DefaultExceptionHandler ");30 - }28 + public DefaultExceptionHandler() {29 + LOG.info("Creating DefaultExceptionHandler ");30 + }31 31 32 - @Context33 - HttpServletRequest request;34 - @Context35 - SecurityContext bsc;36 - @Context37 - EntityManager em;32 + @Context33 + HttpServletRequest request;34 + @Context35 + SecurityContext bsc;36 + @Context37 + EntityManager em;38 38 39 - @Override40 - public Response toResponse(Exception e) {41 - releaseEntityManager();42 - if (e instanceof ForbiddenException) {43 - LOG.warn("ForbiddenException: {}", e);44 - return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)45 - .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();46 - }39 + @Override40 + public Response toResponse(Exception e) {41 + releaseEntityManager();42 + if (e instanceof ForbiddenException) {43 + LOG.warn("ForbiddenException: {}", e.toString());44 + return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)45 + .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();46 + }47 47 48 - if (e instanceof SeCurisServiceException) {49 - LOG.warn("SeCurisServiceException: {}", e);50 - return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())51 - .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();52 - }48 + if (e instanceof SeCurisServiceException) {49 + LOG.warn("SeCurisServiceException: {}", e.toString());50 + return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())51 + .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();52 + }53 53 54 - LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());55 - LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));56 - LOG.error("Request url: " + request.getRequestURL(), e);57 - return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();58 - }54 + LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());55 + LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));56 + LOG.error("Request url: " + request.getRequestURL(), e);57 + return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();58 + }59 59 60 - private void releaseEntityManager() {61 - try {62 - if (em != null && em.isOpen()) {63 - LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());64 - if (em.isJoinedToTransaction()) {65 - em.getTransaction().rollback();66 - LOG.info("ROLLBACK");67 - }68 - em.close();69 - }70 - } catch (Exception ex) {71 - ex.printStackTrace();72 - LOG.error("Error closing EM: {}, {}", em, ex);73 - }74 - }60 + private void releaseEntityManager() {61 + try {62 + if (em != null && em.isOpen()) {63 + LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());64 + if (em.isJoinedToTransaction()) {65 + em.getTransaction().rollback();66 + LOG.info("ROLLBACK");67 + }68 + em.close();69 + }70 + } catch (Exception ex) {71 + ex.printStackTrace();72 + LOG.error("Error closing EM: {}, {}", em, ex);73 + }74 + }75 75 } securis/src/main/java/net/curisit/securis/db/LicenseType.java
.. .. @@ -37,125 +37,122 @@ 37 37 @JsonIgnoreProperties(ignoreUnknown = true) 38 38 @Entity 39 39 @Table(name = "license_type") 40 -@NamedQueries({41 - @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt"),42 - @NamedQuery(name = "list-application-license_types", query = "SELECT lt FROM LicenseType lt where lt.application.id = :appId")43 -})40 +@NamedQueries({ @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt"),41 + @NamedQuery(name = "list-application-license_types", query = "SELECT lt FROM LicenseType lt where lt.application.id = :appId") })44 42 public class LicenseType implements Serializable { 45 43 46 - @SuppressWarnings("unused")47 - private static final Logger LOG = LogManager.getLogger(LicenseType.class);48 - private static final long serialVersionUID = 1L;44 + @SuppressWarnings("unused")45 + private static final Logger LOG = LogManager.getLogger(LicenseType.class);46 + private static final long serialVersionUID = 1L;49 47 50 - @Id51 - @GeneratedValue52 - private Integer id;48 + @Id49 + @GeneratedValue50 + private Integer id;53 51 54 - private String code;55 - private String name;56 - private String description;52 + private String code;53 + private String name;54 + private String description;57 55 58 - @Column(name = "creation_timestamp")59 - @JsonProperty("creation_timestamp")60 - private Date creationTimestamp;56 + @Column(name = "creation_timestamp")57 + @JsonProperty("creation_timestamp")58 + private Date creationTimestamp;61 59 62 - @JsonIgnore63 - @ManyToOne(fetch = FetchType.LAZY)64 - @JoinColumn(name = "application_id")65 - private Application application;60 + @JsonIgnore61 + @ManyToOne(fetch = FetchType.LAZY)62 + @JoinColumn(name = "application_id")63 + private Application application;66 64 67 - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")68 - @JsonManagedReference69 - private Set<LicenseTypeMetadata> metadata;65 + @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")66 + @JsonManagedReference67 + private Set<LicenseTypeMetadata> metadata;70 68 71 - public Set<LicenseTypeMetadata> getMetadata() {72 - return metadata;73 - }69 + public Set<LicenseTypeMetadata> getMetadata() {70 + return metadata;71 + }74 72 75 - public void setMetadata(Set<LicenseTypeMetadata> metadata) {76 - this.metadata = metadata;77 - }73 + public void setMetadata(Set<LicenseTypeMetadata> metadata) {74 + this.metadata = metadata;75 + }78 76 79 - public Integer getId() {80 - return id;81 - }77 + public Integer getId() {78 + return id;79 + }82 80 83 - public void setId(Integer id) {84 - this.id = id;85 - }81 + public void setId(Integer id) {82 + this.id = id;83 + }86 84 87 - public String getName() {88 - return name;89 - }85 + public String getName() {86 + return name;87 + }90 88 91 - public void setName(String name) {92 - this.name = name;93 - }89 + public void setName(String name) {90 + this.name = name;91 + }94 92 95 - public String getDescription() {96 - return description;97 - }93 + public String getDescription() {94 + return description;95 + }98 96 99 - public void setDescription(String description) {100 - this.description = description;101 - }97 + public void setDescription(String description) {98 + this.description = description;99 + }102 100 103 - public String getCode() {104 - return code;105 - }101 + public String getCode() {102 + return code;103 + }106 104 107 - public void setCode(String code) {108 - this.code = code;109 - }105 + public void setCode(String code) {106 + this.code = code;107 + }110 108 111 - public Application getApplication() {112 - LOG.info("Getting APP from LicType");113 - return application;114 - }109 + public Application getApplication() {110 + return application;111 + }115 112 116 - @JsonProperty("application_name")117 - public String getApplicationName() {118 - return application == null ? null : application.getName();119 - }113 + @JsonProperty("application_name")114 + public String getApplicationName() {115 + return application == null ? null : application.getName();116 + }120 117 121 - @JsonProperty("application_id")122 - public Integer getApplicationId() {123 - return application == null ? null : application.getId();124 - }118 + @JsonProperty("application_id")119 + public Integer getApplicationId() {120 + return application == null ? null : application.getId();121 + }125 122 126 - @JsonProperty("application_id")127 - public void setApplicationId(Integer appId) {128 - if (appId == null) {129 - application = null;130 - } else {131 - application = new Application();132 - application.setId(appId);133 - }134 - }123 + @JsonProperty("application_id")124 + public void setApplicationId(Integer appId) {125 + if (appId == null) {126 + application = null;127 + } else {128 + application = new Application();129 + application.setId(appId);130 + }131 + }135 132 136 - public void setApplication(Application application) {137 - this.application = application;138 - }133 + public void setApplication(Application application) {134 + this.application = application;135 + }139 136 140 - public Date getCreationTimestamp() {141 - return creationTimestamp;142 - }137 + public Date getCreationTimestamp() {138 + return creationTimestamp;139 + }143 140 144 - public void setCreationTimestamp(Date creationTimestamp) {145 - this.creationTimestamp = creationTimestamp;146 - }141 + public void setCreationTimestamp(Date creationTimestamp) {142 + this.creationTimestamp = creationTimestamp;143 + }147 144 148 - @Override149 - public boolean equals(Object obj) {150 - if (!(obj instanceof LicenseType))151 - return false;152 - LicenseType other = (LicenseType) obj;153 - return id.equals(other.id);154 - }145 + @Override146 + public boolean equals(Object obj) {147 + if (!(obj instanceof LicenseType))148 + return false;149 + LicenseType other = (LicenseType) obj;150 + return id.equals(other.id);151 + }155 152 156 - @Override157 - public int hashCode() {153 + @Override154 + public int hashCode() {158 155 159 - return (id == null ? 0 : id.hashCode());160 - }156 + return (id == null ? 0 : id.hashCode());157 + }161 158 } securis/src/main/java/net/curisit/securis/services/PackResource.java
.. .. @@ -24,6 +24,9 @@ 24 24 import javax.ws.rs.core.Response; 25 25 import javax.ws.rs.core.Response.Status; 26 26 27 +import org.apache.logging.log4j.LogManager;28 +import org.apache.logging.log4j.Logger;29 +27 30 import net.curisit.integrity.commons.Utils; 28 31 import net.curisit.securis.DefaultExceptionHandler; 29 32 import net.curisit.securis.SeCurisException; .. .. @@ -44,9 +47,6 @@ 44 47 import net.curisit.securis.utils.LicUtils; 45 48 import net.curisit.securis.utils.TokenHelper; 46 49 47 -import org.apache.logging.log4j.LogManager;48 -import org.apache.logging.log4j.Logger;49 -50 50 /** 51 51 * Pack resource, this service will provide methods to create, modify and delete 52 52 * packs .. .. @@ -56,383 +56,363 @@ 56 56 @Path("/pack") 57 57 public class PackResource { 58 58 59 - private static final Logger LOG = LogManager.getLogger(PackResource.class);59 + private static final Logger LOG = LogManager.getLogger(PackResource.class);60 60 61 - @Inject62 - TokenHelper tokenHelper;61 + @Inject62 + TokenHelper tokenHelper;63 63 64 - @Context65 - EntityManager em;64 + @Context65 + EntityManager em;66 66 67 - @Inject68 - private LicenseHelper licenseHelper;67 + @Inject68 + private LicenseHelper licenseHelper;69 69 70 - /**71 - *72 - * @return the server version in format majorVersion.minorVersion73 - */74 - @GET75 - @Path("/")76 - @Securable77 - @Produces({78 - MediaType.APPLICATION_JSON79 - })80 - public Response index(@Context BasicSecurityContext bsc) {81 - LOG.info("Getting packs list ");70 + /**71 + *72 + * @return the server version in format majorVersion.minorVersion73 + */74 + @GET75 + @Path("/")76 + @Securable77 + @Produces({ MediaType.APPLICATION_JSON })78 + public Response index(@Context BasicSecurityContext bsc) {79 + LOG.info("Getting packs list ");82 80 83 - // EntityManager em = emProvider.get();84 - em.clear();81 + // EntityManager em = emProvider.get();82 + em.clear();85 83 86 - TypedQuery<Pack> q;87 - if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {88 - LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());89 - q = em.createNamedQuery("list-packs", Pack.class);90 - } else {91 - q = em.createNamedQuery("list-packs-by-orgs", Pack.class);92 - if (bsc.getOrganizationsIds() == null) {93 - Response.ok().build();94 - }95 - q.setParameter("list_ids", bsc.getOrganizationsIds());96 - }84 + TypedQuery<Pack> q;85 + if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {86 + LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());87 + q = em.createNamedQuery("list-packs", Pack.class);88 + } else {89 + q = em.createNamedQuery("list-packs-by-orgs", Pack.class);90 + if (bsc.getOrganizationsIds() == null) {91 + Response.ok().build();92 + }93 + q.setParameter("list_ids", bsc.getOrganizationsIds());94 + }97 95 98 - List<Pack> list = q.getResultList();96 + List<Pack> list = q.getResultList();99 97 100 - return Response.ok(list).build();101 - }98 + return Response.ok(list).build();99 + }102 100 103 - private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {104 - LOG.error("Pack with id {} not accesible by user {}", pack, user);105 - return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();106 - }101 + private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {102 + LOG.error("Pack with id {} not accesible by user {}", pack, user);103 + return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();104 + }107 105 108 - /**109 - *110 - * @return the server version in format majorVersion.minorVersion111 - */112 - @GET113 - @Path("/{packId}")114 - @Securable115 - @Produces({116 - MediaType.APPLICATION_JSON117 - })118 - public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {119 - LOG.info("Getting pack data for id: {}: ", packId);120 - if (packId == null || "".equals(packId)) {121 - LOG.error("Pack ID is mandatory");122 - return Response.status(Status.NOT_FOUND).build();123 - }106 + /**107 + *108 + * @return the server version in format majorVersion.minorVersion109 + */110 + @GET111 + @Path("/{packId}")112 + @Securable113 + @Produces({ MediaType.APPLICATION_JSON })114 + public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {115 + LOG.info("Getting pack data for id: {}: ", packId);116 + if (packId == null || "".equals(packId)) {117 + LOG.error("Pack ID is mandatory");118 + return Response.status(Status.NOT_FOUND).build();119 + }124 120 125 - // EntityManager em = emProvider.get();126 - em.clear();127 - Pack pack = em.find(Pack.class, packId);128 - if (pack == null) {129 - LOG.error("Pack with id {} not found in DB", packId);130 - return Response.status(Status.NOT_FOUND).build();131 - }132 - if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE)133 - && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {134 - return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());135 - }136 - return Response.ok(pack).build();137 - }121 + // EntityManager em = emProvider.get();122 + em.clear();123 + Pack pack = em.find(Pack.class, packId);124 + if (pack == null) {125 + LOG.error("Pack with id {} not found in DB", packId);126 + return Response.status(Status.NOT_FOUND).build();127 + }128 + if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE) && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {129 + return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());130 + }131 + return Response.ok(pack).build();132 + }138 133 139 - @POST140 - @Path("/")141 - @Securable142 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)143 - @Consumes(MediaType.APPLICATION_JSON)144 - @Produces({145 - MediaType.APPLICATION_JSON146 - })147 - @EnsureTransaction148 - public Response create(Pack pack, @Context BasicSecurityContext bsc) throws SeCurisServiceException {149 - LOG.info("Creating new pack");150 - // EntityManager em = emProvider.get();134 + @POST135 + @Path("/")136 + @Securable137 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)138 + @Consumes(MediaType.APPLICATION_JSON)139 + @Produces({ MediaType.APPLICATION_JSON })140 + @EnsureTransaction141 + public Response create(Pack pack, @Context BasicSecurityContext bsc) throws SeCurisServiceException {142 + LOG.info("Creating new pack");143 + // EntityManager em = emProvider.get();151 144 152 - if (checkIfCodeExists(pack.getCode(), em)) {153 - throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is already used in an existing pack");154 - }145 + if (checkIfCodeExists(pack.getCode(), em)) {146 + throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is already used in an existing pack");147 + }155 148 156 - try {157 - setPackOrganization(pack, pack.getOrgId(), em);158 - } catch (SeCurisException e) {159 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();160 - }149 + try {150 + setPackOrganization(pack, pack.getOrgId(), em);151 + } catch (SeCurisException e) {152 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();153 + }161 154 162 - try {163 - setPackLicenseType(pack, pack.getLicTypeId(), em);164 - } catch (SeCurisException e) {165 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();166 - }155 + try {156 + setPackLicenseType(pack, pack.getLicTypeId(), em);157 + } catch (SeCurisException e) {158 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();159 + }167 160 168 - User user = em.find(User.class, bsc.getUserPrincipal().getName());161 + User user = em.find(User.class, bsc.getUserPrincipal().getName());169 162 170 - pack.setStatus(PackStatus.CREATED);171 - pack.setCreatedBy(user);172 - pack.setCreationTimestamp(new Date());173 - em.persist(pack);174 - Set<PackMetadata> newMD = pack.getMetadata();163 + pack.setStatus(PackStatus.CREATED);164 + pack.setCreatedBy(user);165 + pack.setCreationTimestamp(new Date());166 + em.persist(pack);167 + Set<PackMetadata> newMD = pack.getMetadata();175 168 176 - if (newMD != null) {177 - for (PackMetadata md : newMD) {178 - md.setPack(pack);179 - em.persist(md);180 - }181 - }182 - pack.setMetadata(newMD);183 - return Response.ok(pack).build();184 - }169 + if (newMD != null) {170 + for (PackMetadata md : newMD) {171 + md.setPack(pack);172 + em.persist(md);173 + }174 + }175 + pack.setMetadata(newMD);176 + return Response.ok(pack).build();177 + }185 178 186 - /**187 - * Check if there is some pack with the same code188 - *189 - * @param code190 - * Pack code191 - * @param em192 - * DB session object193 - * @return <code>true</code> if code is already used, <code>false</code>194 - * otherwise195 - */196 - private boolean checkIfCodeExists(String code, EntityManager em) {197 - TypedQuery<Pack> query = em.createNamedQuery("pack-by-code", Pack.class);198 - query.setParameter("code", code);199 - int packs = query.getResultList().size();200 - return packs > 0;201 - }179 + /**180 + * Check if there is some pack with the same code181 + *182 + * @param code183 + * Pack code184 + * @param em185 + * DB session object186 + * @return <code>true</code> if code is already used, <code>false</code>187 + * otherwise188 + */189 + private boolean checkIfCodeExists(String code, EntityManager em) {190 + TypedQuery<Pack> query = em.createNamedQuery("pack-by-code", Pack.class);191 + query.setParameter("code", code);192 + int packs = query.getResultList().size();193 + return packs > 0;194 + }202 195 203 - /**204 - *205 - * @return The next available code suffix in pack for license code206 - * @throws SeCurisServiceException207 - */208 - @GET209 - @Path("/{packId}/next_license_code")210 - @Securable211 - @Produces({212 - MediaType.TEXT_PLAIN213 - })214 - public Response getCodeSuffix(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {215 - // EntityManager em = emProvider.get();196 + /**197 + *198 + * @return The next available code suffix in pack for license code199 + * @throws SeCurisServiceException200 + */201 + @GET202 + @Path("/{packId}/next_license_code")203 + @Securable204 + @Produces({ MediaType.TEXT_PLAIN })205 + public Response getCodeSuffix(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {206 + // EntityManager em = emProvider.get();216 207 217 - if (packId == null) {218 - throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is mandatory");219 - }220 - Integer codeSuffix = licenseHelper.getNextCodeSuffix(packId, em);221 - Pack pack = em.find(Pack.class, packId);222 - ;208 + if (packId == null) {209 + throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is mandatory");210 + }211 + Integer codeSuffix = licenseHelper.getNextCodeSuffix(packId, em);212 + Pack pack = em.find(Pack.class, packId);213 + ;223 214 224 - String licCode = LicUtils.getLicenseCode(pack.getCode(), codeSuffix);225 - return Response.ok(licCode).build();226 - }215 + String licCode = LicUtils.getLicenseCode(pack.getCode(), codeSuffix);216 + return Response.ok(licCode).build();217 + }227 218 228 - private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {229 - LicenseType lt = null;230 - if (licTypeId != null) {231 - lt = em.find(LicenseType.class, pack.getLicTypeId());232 - if (lt == null) {233 - LOG.error("Pack license type with id {} not found in DB", licTypeId);234 - throw new SeCurisException("Pack license type not found with ID: " + licTypeId);235 - }236 - }237 - pack.setLicenseType(lt);238 - }219 + private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {220 + LicenseType lt = null;221 + if (licTypeId != null) {222 + lt = em.find(LicenseType.class, pack.getLicTypeId());223 + if (lt == null) {224 + LOG.error("Pack license type with id {} not found in DB", licTypeId);225 + throw new SeCurisException("Pack license type not found with ID: " + licTypeId);226 + }227 + }228 + pack.setLicenseType(lt);229 + }239 230 240 - private Set<String> getMdKeys(Set<PackMetadata> mds) {241 - Set<String> ids = new HashSet<String>();242 - if (mds != null) {243 - for (PackMetadata md : mds) {244 - ids.add(md.getKey());245 - }246 - }247 - return ids;248 - }231 + private Set<String> getMdKeys(Set<PackMetadata> mds) {232 + Set<String> ids = new HashSet<String>();233 + if (mds != null) {234 + for (PackMetadata md : mds) {235 + ids.add(md.getKey());236 + }237 + }238 + return ids;239 + }249 240 250 - @PUT251 - @POST252 - @Path("/{packId}")253 - @EnsureTransaction254 - @Securable255 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)256 - @Consumes(MediaType.APPLICATION_JSON)257 - @Produces({258 - MediaType.APPLICATION_JSON259 - })260 - public Response modify(Pack pack, @PathParam("packId") Integer packId) {261 - LOG.info("Modifying pack with id: {}", packId);262 - // EntityManager em = emProvider.get();263 - Pack currentPack = em.find(Pack.class, packId);241 + @PUT242 + @POST243 + @Path("/{packId}")244 + @EnsureTransaction245 + @Securable246 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)247 + @Consumes(MediaType.APPLICATION_JSON)248 + @Produces({ MediaType.APPLICATION_JSON })249 + public Response modify(Pack pack, @PathParam("packId") Integer packId) {250 + LOG.info("Modifying pack with id: {}", packId);251 + // EntityManager em = emProvider.get();252 + Pack currentPack = em.find(Pack.class, packId);264 253 265 - try {266 - setPackOrganization(currentPack, pack.getOrgId(), em);267 - } catch (SeCurisException e) {268 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();269 - }254 + try {255 + setPackOrganization(currentPack, pack.getOrgId(), em);256 + } catch (SeCurisException e) {257 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();258 + }270 259 271 - try {272 - setPackLicenseType(currentPack, pack.getLicTypeId(), em);273 - } catch (SeCurisException e) {274 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();275 - }260 + try {261 + setPackLicenseType(currentPack, pack.getLicTypeId(), em);262 + } catch (SeCurisException e) {263 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();264 + }276 265 277 - currentPack.setLicensePreactivation(pack.isLicensePreactivation());278 - currentPack.setCode(pack.getCode());279 - currentPack.setComments(pack.getComments());280 - currentPack.setNumLicenses(pack.getNumLicenses());281 - currentPack.setPreactivationValidPeriod(pack.getPreactivationValidPeriod());282 - currentPack.setRenewValidPeriod(pack.getRenewValidPeriod());266 + currentPack.setLicensePreactivation(pack.isLicensePreactivation());267 + currentPack.setCode(pack.getCode());268 + currentPack.setComments(pack.getComments());269 + currentPack.setNumLicenses(pack.getNumLicenses());270 + currentPack.setPreactivationValidPeriod(pack.getPreactivationValidPeriod());271 + currentPack.setRenewValidPeriod(pack.getRenewValidPeriod());272 + currentPack.setInitValidDate(pack.getInitValidDate());273 + currentPack.setEndValidDate(pack.getEndValidDate());283 274 284 - Set<PackMetadata> newMD = pack.getMetadata();285 - Set<String> newMdKeys = getMdKeys(newMD);286 - for (PackMetadata currentMd : currentPack.getMetadata()) {287 - if (!newMdKeys.contains(currentMd.getKey())) {288 - em.remove(currentMd);289 - }290 - }275 + Set<PackMetadata> newMD = pack.getMetadata();276 + Set<String> newMdKeys = getMdKeys(newMD);277 + for (PackMetadata currentMd : currentPack.getMetadata()) {278 + if (!newMdKeys.contains(currentMd.getKey())) {279 + em.remove(currentMd);280 + }281 + }291 282 292 - if (newMD != null) {293 - Set<PackMetadata> oldMD = currentPack.getMetadata();294 - Set<String> oldMdKeys = getMdKeys(newMD);295 - for (PackMetadata md : newMD) {296 - if (oldMdKeys.contains(md.getKey())) {297 - em.merge(md);298 - } else {299 - md.setPack(currentPack);300 - em.persist(md);301 - }302 - }303 - }304 - currentPack.setMetadata(newMD);305 - em.merge(currentPack);283 + if (newMD != null) {284 + Set<String> oldMdKeys = getMdKeys(newMD);285 + for (PackMetadata md : newMD) {286 + if (oldMdKeys.contains(md.getKey())) {287 + em.merge(md);288 + } else {289 + md.setPack(currentPack);290 + em.persist(md);291 + }292 + }293 + }294 + currentPack.setMetadata(newMD);295 + em.merge(currentPack);306 296 307 - return Response.ok(currentPack).build();308 - }297 + return Response.ok(currentPack).build();298 + }309 299 310 - @POST311 - @Path("/{packId}/activate")312 - @EnsureTransaction313 - @Securable314 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)315 - @Consumes(MediaType.APPLICATION_JSON)316 - @Produces({317 - MediaType.APPLICATION_JSON318 - })319 - public Response activate(@PathParam("packId") Integer packId) throws SeCurisServiceException {320 - LOG.info("Activating pack with id: {}", packId);321 - // EntityManager em = emProvider.get();300 + @POST301 + @Path("/{packId}/activate")302 + @EnsureTransaction303 + @Securable304 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)305 + @Consumes(MediaType.APPLICATION_JSON)306 + @Produces({ MediaType.APPLICATION_JSON })307 + public Response activate(@PathParam("packId") Integer packId) throws SeCurisServiceException {308 + LOG.info("Activating pack with id: {}", packId);309 + // EntityManager em = emProvider.get();322 310 323 - Pack currentPack = em.find(Pack.class, packId);311 + Pack currentPack = em.find(Pack.class, packId);324 312 325 - if (!Pack.Status.isActionValid(Pack.Action.ACTIVATION, currentPack.getStatus())) {326 - LOG.error("Pack with id {} cannot be activaed from status {}", packId, currentPack.getStatus().name());327 - throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be activated in status: " + currentPack.getStatus().name());328 - }313 + if (!Pack.Status.isActionValid(Pack.Action.ACTIVATION, currentPack.getStatus())) {314 + LOG.error("Pack with id {} cannot be activaed from status {}", packId, currentPack.getStatus().name());315 + throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be activated in status: " + currentPack.getStatus().name());316 + }329 317 330 - currentPack.setStatus(PackStatus.ACTIVE);331 - em.persist(currentPack);318 + currentPack.setStatus(PackStatus.ACTIVE);319 + em.persist(currentPack);332 320 333 - return Response.ok(currentPack).build();334 - }321 + return Response.ok(currentPack).build();322 + }335 323 336 - @POST337 - @Path("/{packId}/putonhold")338 - @EnsureTransaction339 - @Securable340 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)341 - @Consumes(MediaType.APPLICATION_JSON)342 - @Produces({343 - MediaType.APPLICATION_JSON344 - })345 - public Response onhold(@PathParam("packId") Integer packId) throws SeCurisServiceException {346 - LOG.info("Putting On hold pack with id: {}", packId);347 - // EntityManager em = emProvider.get();324 + @POST325 + @Path("/{packId}/putonhold")326 + @EnsureTransaction327 + @Securable328 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)329 + @Consumes(MediaType.APPLICATION_JSON)330 + @Produces({ MediaType.APPLICATION_JSON })331 + public Response onhold(@PathParam("packId") Integer packId) throws SeCurisServiceException {332 + LOG.info("Putting On hold pack with id: {}", packId);333 + // EntityManager em = emProvider.get();348 334 349 - Pack currentPack = em.find(Pack.class, packId);335 + Pack currentPack = em.find(Pack.class, packId);350 336 351 - if (!Pack.Status.isActionValid(Pack.Action.PUT_ONHOLD, currentPack.getStatus())) {352 - LOG.error("Pack with id {} cannot be put on hold from status {}", packId, currentPack.getStatus().name());353 - throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be put on hold in status: " + currentPack.getStatus().name());354 - }337 + if (!Pack.Status.isActionValid(Pack.Action.PUT_ONHOLD, currentPack.getStatus())) {338 + LOG.error("Pack with id {} cannot be put on hold from status {}", packId, currentPack.getStatus().name());339 + throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be put on hold in status: " + currentPack.getStatus().name());340 + }355 341 356 - currentPack.setStatus(PackStatus.ON_HOLD);357 - em.persist(currentPack);342 + currentPack.setStatus(PackStatus.ON_HOLD);343 + em.persist(currentPack);358 344 359 - return Response.ok(currentPack).build();360 - }345 + return Response.ok(currentPack).build();346 + }361 347 362 - @POST363 - @Path("/{packId}/cancel")364 - @EnsureTransaction365 - @Securable366 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)367 - @Consumes(MediaType.APPLICATION_JSON)368 - @Produces({369 - MediaType.APPLICATION_JSON370 - })371 - public Response cancel(@PathParam("packId") Integer packId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc)372 - throws SeCurisServiceException {373 - LOG.info("Cancelling pack with id: {}", packId);374 - // EntityManager em = emProvider.get();348 + @POST349 + @Path("/{packId}/cancel")350 + @EnsureTransaction351 + @Securable352 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)353 + @Consumes(MediaType.APPLICATION_JSON)354 + @Produces({ MediaType.APPLICATION_JSON })355 + public Response cancel(@PathParam("packId") Integer packId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc) throws SeCurisServiceException {356 + LOG.info("Cancelling pack with id: {}", packId);357 + // EntityManager em = emProvider.get();375 358 376 - Pack currentPack = em.find(Pack.class, packId);359 + Pack currentPack = em.find(Pack.class, packId);377 360 378 - if (!Pack.Status.isActionValid(Pack.Action.CANCEL, currentPack.getStatus())) {379 - LOG.error("Pack with id {} cannot cancelled from status {}", packId, currentPack.getStatus().name());380 - throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be cancelled in status: " + currentPack.getStatus().name());381 - }361 + if (!Pack.Status.isActionValid(Pack.Action.CANCEL, currentPack.getStatus())) {362 + LOG.error("Pack with id {} cannot cancelled from status {}", packId, currentPack.getStatus().name());363 + throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be cancelled in status: " + currentPack.getStatus().name());364 + }382 365 383 - Set<License> licenses = currentPack.getLicenses();384 - for (License license : licenses) {385 - if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {386 - licenseHelper.cancelLicense(license, "Pack cancellation. " + reason, bsc, em);387 - }388 - }389 - currentPack.setStatus(PackStatus.CANCELLED);390 - em.persist(currentPack);366 + Set<License> licenses = currentPack.getLicenses();367 + for (License license : licenses) {368 + if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {369 + licenseHelper.cancelLicense(license, "Pack cancellation. " + reason, bsc, em);370 + }371 + }372 + currentPack.setStatus(PackStatus.CANCELLED);373 + em.persist(currentPack);391 374 392 - return Response.ok(currentPack).build();393 - }375 + return Response.ok(currentPack).build();376 + }394 377 395 - private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {396 - Organization org = null;397 - if (orgId != null) {398 - org = em.find(Organization.class, orgId);399 - if (org == null) {400 - LOG.error("Organization pack with id {} not found in DB", orgId);401 - throw new SeCurisException("Pack organization not found with ID: " + orgId);402 - }403 - }404 - currentPack.setOrganization(org);405 - }378 + private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {379 + Organization org = null;380 + if (orgId != null) {381 + org = em.find(Organization.class, orgId);382 + if (org == null) {383 + LOG.error("Organization pack with id {} not found in DB", orgId);384 + throw new SeCurisException("Pack organization not found with ID: " + orgId);385 + }386 + }387 + currentPack.setOrganization(org);388 + }406 389 407 - @DELETE408 - @Path("/{packId}")409 - @Securable410 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)411 - @EnsureTransaction412 - @Produces({413 - MediaType.APPLICATION_JSON414 - })415 - public Response delete(@PathParam("packId") String packId) throws SeCurisServiceException {416 - LOG.info("Deleting pack with id: {}", packId);417 - // EntityManager em = emProvider.get();418 - Pack pack = em.find(Pack.class, Integer.parseInt(packId));419 - if (pack == null) {420 - LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);421 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId)422 - .build();423 - }424 - // Pack metadata is removed in cascade automatically.390 + @DELETE391 + @Path("/{packId}")392 + @Securable393 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)394 + @EnsureTransaction395 + @Produces({ MediaType.APPLICATION_JSON })396 + public Response delete(@PathParam("packId") String packId) throws SeCurisServiceException {397 + LOG.info("Deleting pack with id: {}", packId);398 + // EntityManager em = emProvider.get();399 + Pack pack = em.find(Pack.class, Integer.parseInt(packId));400 + if (pack == null) {401 + LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);402 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId).build();403 + }404 + // Pack metadata is removed in cascade automatically.425 405 426 - Set<License> licenses = pack.getLicenses();427 - for (License license : licenses) {428 - if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {429 - throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "An active license cannot be deleted. License code: " + license.getCode());430 - }431 - em.remove(license);432 - }406 + Set<License> licenses = pack.getLicenses();407 + for (License license : licenses) {408 + if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {409 + throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "An active license cannot be deleted. License code: " + license.getCode());410 + }411 + em.remove(license);412 + }433 413 434 - em.remove(pack);435 - return Response.ok(Utils.createMap("success", true, "id", packId)).build();436 - }414 + em.remove(pack);415 + return Response.ok(Utils.createMap("success", true, "id", packId)).build();416 + }437 417 438 418 } securis/src/main/java/net/curisit/securis/services/UserResource.java
.. .. @@ -28,6 +28,9 @@ 28 28 import javax.ws.rs.core.Response; 29 29 import javax.ws.rs.core.Response.Status; 30 30 31 +import org.apache.logging.log4j.LogManager;32 +import org.apache.logging.log4j.Logger;33 +31 34 import net.curisit.integrity.commons.Utils; 32 35 import net.curisit.securis.DefaultExceptionHandler; 33 36 import net.curisit.securis.SeCurisException; .. .. @@ -38,10 +41,8 @@ 38 41 import net.curisit.securis.security.Securable; 39 42 import net.curisit.securis.services.exception.SeCurisServiceException; 40 43 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes; 44 +import net.curisit.securis.utils.CacheTTL;41 45 import net.curisit.securis.utils.TokenHelper; 42 -43 -import org.apache.logging.log4j.LogManager;44 -import org.apache.logging.log4j.Logger;45 46 46 47 /** 47 48 * User resource .. .. @@ -52,266 +53,258 @@ 52 53 @RequestScoped 53 54 public class UserResource { 54 55 55 - @Inject56 - TokenHelper tokenHelper;56 + @Inject57 + TokenHelper tokenHelper;57 58 58 - @Context59 - EntityManager em;59 + @Inject60 + private CacheTTL cache;60 61 61 - private static final Logger LOG = LogManager.getLogger(UserResource.class);62 + @Context63 + EntityManager em;62 64 63 - public UserResource() {64 - }65 + private static final Logger LOG = LogManager.getLogger(UserResource.class);65 66 66 - /**67 - *68 - * @return the server version in format majorVersion.minorVersion69 - */70 - @GET71 - @Path("/")72 - @Produces({73 - MediaType.APPLICATION_JSON74 - })75 - @Securable76 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)77 - public Response index() {78 - LOG.info("Getting users list ");67 + public UserResource() {68 + }79 69 80 - // EntityManager em = emProvider.get();81 - em.clear();82 - TypedQuery<User> q = em.createNamedQuery("list-users", User.class);70 + /**71 + *72 + * @return the server version in format majorVersion.minorVersion73 + */74 + @GET75 + @Path("/")76 + @Produces({ MediaType.APPLICATION_JSON })77 + @Securable78 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)79 + public Response index() {80 + LOG.info("Getting users list ");83 81 84 - List<User> list = q.getResultList();82 + // EntityManager em = emProvider.get();83 + em.clear();84 + TypedQuery<User> q = em.createNamedQuery("list-users", User.class);85 85 86 - return Response.ok(list).build();87 - }86 + List<User> list = q.getResultList();88 87 89 - /**90 - *91 - * @return The user92 - */93 - @GET94 - @Path("/{uid}")95 - @Produces({96 - MediaType.APPLICATION_JSON97 - })98 - @Securable99 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)100 - public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {101 - LOG.info("Getting user data for id: {}: ", uid);102 - if (uid == null || "".equals(uid)) {103 - LOG.error("User ID is mandatory");104 - return Response.status(Status.NOT_FOUND).build();105 - }88 + return Response.ok(list).build();89 + }106 90 107 - // EntityManager em = emProvider.get();108 - em.clear();109 - User lt = em.find(User.class, uid);110 - if (lt == null) {111 - LOG.error("User with id {} not found in DB", uid);112 - return Response.status(Status.NOT_FOUND).build();113 - }114 - return Response.ok(lt).build();115 - }91 + /**92 + *93 + * @return The user94 + */95 + @GET96 + @Path("/{uid}")97 + @Produces({ MediaType.APPLICATION_JSON })98 + @Securable99 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)100 + public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {101 + LOG.info("Getting user data for id: {}: ", uid);102 + if (uid == null || "".equals(uid)) {103 + LOG.error("User ID is mandatory");104 + return Response.status(Status.NOT_FOUND).build();105 + }116 106 117 - @POST118 - @Path("/")119 - @Consumes(MediaType.APPLICATION_JSON)120 - @Produces({121 - MediaType.APPLICATION_JSON122 - })123 - @EnsureTransaction124 - @Securable125 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)126 - public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {127 - LOG.info("Creating new user");128 - // EntityManager em = emProvider.get();129 - User currentUser = em.find(User.class, user.getUsername());130 - if (currentUser != null) {131 - LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());132 - return modify(user, user.getUsername(), token);133 - }107 + // EntityManager em = emProvider.get();108 + em.clear();109 + User lt = em.find(User.class, uid);110 + if (lt == null) {111 + LOG.error("User with id {} not found in DB", uid);112 + return Response.status(Status.NOT_FOUND).build();113 + }114 + return Response.ok(lt).build();115 + }134 116 135 - try {136 - this.setUserOrg(user, user.getOrgsIds(), em);137 - } catch (SeCurisException e) {138 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();139 - }140 - if (user.getPassword() != null && !"".equals(user.getPassword())) {141 - user.setPassword(Utils.sha256(user.getPassword()));142 - } else {143 - return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE)144 - .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "User password is mandatory").build();145 - }146 - user.setModificationTimestamp(new Date());147 - user.setLastLogin(null);148 - user.setCreationTimestamp(new Date());149 - em.persist(user);117 + @POST118 + @Path("/")119 + @Consumes(MediaType.APPLICATION_JSON)120 + @Produces({ MediaType.APPLICATION_JSON })121 + @EnsureTransaction122 + @Securable123 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)124 + public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {125 + LOG.info("Creating new user");126 + // EntityManager em = emProvider.get();127 + User currentUser = em.find(User.class, user.getUsername());128 + if (currentUser != null) {129 + LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());130 + return modify(user, user.getUsername(), token);131 + }150 132 151 - return Response.ok(user).build();152 - }133 + try {134 + this.setUserOrg(user, user.getOrgsIds(), em);135 + } catch (SeCurisException e) {136 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();137 + }138 + if (user.getPassword() != null && !"".equals(user.getPassword())) {139 + user.setPassword(Utils.sha256(user.getPassword()));140 + } else {141 + return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "User password is mandatory")142 + .build();143 + }144 + user.setModificationTimestamp(new Date());145 + user.setLastLogin(null);146 + user.setCreationTimestamp(new Date());147 + em.persist(user);153 148 154 - private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {155 - Set<Organization> orgs = null;156 - if (orgsIds != null && !orgsIds.isEmpty()) {157 - orgs = new HashSet<>();158 - for (Integer orgId : orgsIds) {159 - Organization o = em.find(Organization.class, orgId);160 - if (o == null) {161 - LOG.error("User organization with id {} not found in DB", orgId);162 - throw new SeCurisException("User's organization not found with ID: " + orgId);163 - }164 - orgs.add(o);165 - }166 - }149 + return Response.ok(user).build();150 + }167 151 168 - user.setOrganizations(orgs);152 + private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {153 + Set<Organization> orgs = null;154 + if (orgsIds != null && !orgsIds.isEmpty()) {155 + orgs = new HashSet<>();156 + for (Integer orgId : orgsIds) {157 + Organization o = em.find(Organization.class, orgId);158 + if (o == null) {159 + LOG.error("User organization with id {} not found in DB", orgId);160 + throw new SeCurisException("User's organization not found with ID: " + orgId);161 + }162 + orgs.add(o);163 + }164 + }169 165 170 - }166 + user.setOrganizations(orgs);171 167 172 - @PUT173 - @POST174 - @Path("/{uid}")175 - @EnsureTransaction176 - @Consumes(MediaType.APPLICATION_JSON)177 - @Produces({178 - MediaType.APPLICATION_JSON179 - })180 - @Securable181 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)182 - public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {183 - LOG.info("Modifying user with id: {}", uid);184 - // EntityManager em = emProvider.get();185 - User currentUser = em.find(User.class, uid);186 - if (currentUser == null) {187 - LOG.info("User with id {} not found in DB, we'll try to create it", uid);188 - return create(user, token);189 - }168 + }190 169 191 - try {192 - this.setUserOrg(currentUser, user.getOrgsIds(), em);193 - } catch (SeCurisException e) {194 - return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();195 - }196 - currentUser.setFirstName(user.getFirstName());197 - currentUser.setLastName(user.getLastName());198 - currentUser.setRoles(user.getRoles());199 - currentUser.setLang(user.getLang());200 - currentUser.setModificationTimestamp(new Date());201 - if (user.getPassword() != null && !"".equals(user.getPassword())) {202 - currentUser.setPassword(Utils.sha256(user.getPassword()));203 - } else {204 - // Password has not been modified205 - // return206 - // Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,207 - // "User password is mandatory").build();208 - }170 + @PUT171 + @POST172 + @Path("/{uid}")173 + @EnsureTransaction174 + @Consumes(MediaType.APPLICATION_JSON)175 + @Produces({ MediaType.APPLICATION_JSON })176 + @Securable177 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)178 + public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {179 + LOG.info("Modifying user with id: {}", uid);180 + // EntityManager em = emProvider.get();181 + User currentUser = em.find(User.class, uid);182 + if (currentUser == null) {183 + LOG.info("User with id {} not found in DB, we'll try to create it", uid);184 + return create(user, token);185 + }209 186 210 - currentUser.setLastLogin(user.getLastLogin());187 + try {188 + this.setUserOrg(currentUser, user.getOrgsIds(), em);189 + } catch (SeCurisException e) {190 + return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();191 + }192 + currentUser.setFirstName(user.getFirstName());193 + currentUser.setLastName(user.getLastName());194 + currentUser.setRoles(user.getRoles());195 + currentUser.setLang(user.getLang());196 + currentUser.setModificationTimestamp(new Date());197 + if (user.getPassword() != null && !"".equals(user.getPassword())) {198 + currentUser.setPassword(Utils.sha256(user.getPassword()));199 + } else {200 + // Password has not been modified201 + // return202 + // Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,203 + // "User password is mandatory").build();204 + }211 205 212 - em.persist(currentUser);206 + currentUser.setLastLogin(user.getLastLogin());213 207 214 - return Response.ok(currentUser).build();215 - }208 + em.persist(currentUser);209 + clearUserCache(currentUser.getUsername());216 210 217 - @DELETE218 - @Path("/{uid}")219 - @EnsureTransaction220 - @Produces({221 - MediaType.APPLICATION_JSON222 - })223 - @Securable224 - @RolesAllowed(BasicSecurityContext.ROL_ADMIN)225 - public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {226 - LOG.info("Deleting app with id: {}", uid);227 - // EntityManager em = emProvider.get();228 - User app = em.find(User.class, uid);229 - if (app == null) {230 - LOG.error("User with id {} can not be deleted, It was not found in DB", uid);231 - return Response.status(Status.NOT_FOUND).build();232 - }211 + return Response.ok(currentUser).build();212 + }233 213 234 - em.remove(app);235 - return Response.ok(Utils.createMap("success", true, "id", uid)).build();236 - }214 + @DELETE215 + @Path("/{uid}")216 + @EnsureTransaction217 + @Produces({ MediaType.APPLICATION_JSON })218 + @Securable219 + @RolesAllowed(BasicSecurityContext.ROL_ADMIN)220 + public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {221 + LOG.info("Deleting app with id: {}", uid);222 + // EntityManager em = emProvider.get();223 + User user = em.find(User.class, uid);224 + if (user == null) {225 + LOG.error("User with id {} can not be deleted, It was not found in DB", uid);226 + return Response.status(Status.NOT_FOUND).build();227 + }237 228 238 - @POST239 - @Path("/login")240 - @Produces({241 - MediaType.APPLICATION_JSON242 - })243 - public Response login(@FormParam("username") String username, @FormParam("password") String password, @Context HttpServletRequest request)244 - throws SeCurisServiceException {245 - LOG.info("index session: " + request.getSession());246 - LOG.info("user: {}, pass: {}", username, password);247 - LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));248 - LOG.info("is user in role: {} == {} ? ", "admin", request.isUserInRole("admin"));229 + em.remove(user);230 + clearUserCache(user.getUsername());231 + return Response.ok(Utils.createMap("success", true, "id", uid)).build();232 + }249 233 250 - // EntityManager em = emProvider.get();251 - User user = em.find(User.class, username);252 - if (user == null) {253 - LOG.error("Inknown username {} used in login service", username);254 - throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");255 - }256 - String securedPassword = Utils.sha256(password);234 + private void clearUserCache(String username) {235 + cache.remove("roles_" + username);236 + cache.remove("orgs_" + username);237 + }257 238 258 - if (securedPassword == null || !securedPassword.equals(user.getPassword())) {259 - throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");260 - }261 - user.setLastLogin(new Date());262 - em.getTransaction().begin();263 - try {264 - em.persist(user);265 - em.getTransaction().commit();266 - } catch (PersistenceException ex) {267 - LOG.error("Error updating last login date for user: {}", username);268 - LOG.error(ex);269 - em.getTransaction().rollback();270 - }271 - String tokenAuth = tokenHelper.generateToken(username);272 - return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();273 - }239 + @POST240 + @Path("/login")241 + @Produces({ MediaType.APPLICATION_JSON })242 + public Response login(@FormParam("username") String username, @FormParam("password") String password, @Context HttpServletRequest request) throws SeCurisServiceException {243 + LOG.info("index session: " + request.getSession());274 244 275 - /**276 - * Check if current token is valid277 - *278 - * @param user279 - * @param password280 - * @param request281 - * @return282 - */283 - @POST284 - @Path("/check")285 - @Produces({286 - MediaType.APPLICATION_JSON287 - })288 - public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {289 - if (token == null) {290 - token = token2;291 - }292 - if (token == null) {293 - return Response.status(Status.FORBIDDEN).build();294 - }245 + // EntityManager em = emProvider.get();246 + User user = em.find(User.class, username);247 + if (user == null) {248 + LOG.error("Unknown username {} used in login service", username);249 + throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");250 + }251 + String securedPassword = Utils.sha256(password);295 252 296 - LOG.info("Token : " + token);297 - String user = tokenHelper.extractUserFromToken(token);298 - LOG.info("Token user: " + user);299 - Date date = tokenHelper.extractDateCreationFromToken(token);300 - LOG.info("Token date: " + date);301 - boolean valid = tokenHelper.isTokenValid(token);253 + if (securedPassword == null || !securedPassword.equals(user.getPassword())) {254 + throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");255 + }256 + user.setLastLogin(new Date());257 + em.getTransaction().begin();258 + try {259 + em.persist(user);260 + em.getTransaction().commit();261 + } catch (PersistenceException ex) {262 + LOG.error("Error updating last login date for user: {}", username);263 + LOG.error(ex);264 + em.getTransaction().rollback();265 + }266 + clearUserCache(username);302 267 303 - LOG.info("Is Token valid: " + valid);268 + String tokenAuth = tokenHelper.generateToken(username);269 + return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();270 + }304 271 305 - return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();306 - }272 + /**273 + * Check if current token is valid274 + *275 + * @param user276 + * @param password277 + * @param request278 + * @return279 + */280 + @POST281 + @Path("/check")282 + @Produces({ MediaType.APPLICATION_JSON })283 + public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {284 + if (token == null) {285 + token = token2;286 + }287 + if (token == null) {288 + return Response.status(Status.FORBIDDEN).build();289 + }307 290 308 - @GET309 - @Path("/logout")310 - @Produces({311 - MediaType.APPLICATION_JSON312 - })313 - public Response logout(@Context HttpServletRequest request) {314 - request.getSession().invalidate();315 - return Response.ok().build();316 - }291 + LOG.info("Token : " + token);292 + String user = tokenHelper.extractUserFromToken(token);293 + LOG.info("Token user: " + user);294 + Date date = tokenHelper.extractDateCreationFromToken(token);295 + LOG.info("Token date: " + date);296 + boolean valid = tokenHelper.isTokenValid(token);297 +298 + LOG.info("Is Token valid: " + valid);299 +300 + return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();301 + }302 +303 + @GET304 + @Path("/logout")305 + @Produces({ MediaType.APPLICATION_JSON })306 + public Response logout(@Context HttpServletRequest request) {307 + request.getSession().invalidate();308 + return Response.ok().build();309 + }317 310 }