[DEV] updat to the new model (READY)

This commit is contained in:
Edouard DUPIN 2024-01-18 23:34:43 +01:00
parent 3ea26e3f78
commit 7ce71f91d5
10 changed files with 128 additions and 128 deletions

View File

@ -24,7 +24,7 @@ public class WebLauncherLocal extends WebLauncher {
if (true) { if (true) {
// for local test: // for local test:
ConfigBaseVariable.apiAdress = "http://0.0.0.0:15080/karso/api/"; ConfigBaseVariable.apiAdress = "http://0.0.0.0:15080/karso/api/";
ConfigBaseVariable.dbPort = "3307"; ConfigBaseVariable.dbPort = "3906";
// create a unique key for test ==> not retrieve the token every load... // create a unique key for test ==> not retrieve the token every load...
ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf88QJSDMLQKSndmLQKZNERMAL"; ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf88QJSDMLQKSndmLQKZNERMAL";
//ConfigBaseVariable.dbType = "sqlite"; //ConfigBaseVariable.dbType = "sqlite";

View File

@ -25,8 +25,8 @@ import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST; import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path; import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam; import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces; import jakarta.ws.rs.Produces;
@ -40,9 +40,9 @@ import jakarta.ws.rs.core.SecurityContext;
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public class ApplicationResource { public class ApplicationResource {
final Logger logger = LoggerFactory.getLogger(ApplicationResource.class); final Logger logger = LoggerFactory.getLogger(ApplicationResource.class);
public ApplicationResource() {} public ApplicationResource() {}
public List<Long> getUserListOfApplication(final Long userId) { public List<Long> getUserListOfApplication(final Long userId) {
final List<Long> out = new ArrayList<>(); final List<Long> out = new ArrayList<>();
List<UserLinkApplication> links = null; List<UserLinkApplication> links = null;
@ -60,7 +60,7 @@ public class ApplicationResource {
} }
return out; return out;
} }
public List<Long> getListOfUsers(final Long applicationId) { public List<Long> getListOfUsers(final Long applicationId) {
final List<Long> out = new ArrayList<>(); final List<Long> out = new ArrayList<>();
List<UserLinkApplication> links = null; List<UserLinkApplication> links = null;
@ -83,7 +83,7 @@ public class ApplicationResource {
// Generic /application/ // Generic /application/
// //
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
@GET @GET
@RolesAllowed(value = { "USER", "ADMIN" }) @RolesAllowed(value = { "USER", "ADMIN" })
public List<Application> getApplications(@Context final SecurityContext sc) throws Exception { public List<Application> getApplications(@Context final SecurityContext sc) throws Exception {
@ -103,7 +103,7 @@ public class ApplicationResource {
} }
return out; return out;
} }
@POST @POST
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public Application create(final Application application) throws Exception { public Application create(final Application application) throws Exception {
@ -121,21 +121,21 @@ public class ApplicationResource {
application.updatedAt = null; application.updatedAt = null;
return DataAccess.insert(application); return DataAccess.insert(application);
} }
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
// //
// Generic /application/{id} // Generic /application/{id}
// //
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
@GET @GET
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public Application get(@PathParam("id") final Long id) throws Exception { public Application get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Application.class, id); return DataAccess.get(Application.class, id);
} }
@PUT @PATCH
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -143,7 +143,7 @@ public class ApplicationResource {
DataAccess.updateWithJson(Application.class, id, jsonRequest); DataAccess.updateWithJson(Application.class, id, jsonRequest);
return DataAccess.get(Application.class, id); return DataAccess.get(Application.class, id);
} }
@DELETE @DELETE
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -151,29 +151,29 @@ public class ApplicationResource {
public void remove(@Context final SecurityContext sc, @PathParam("id") final long applicationId) throws Exception { public void remove(@Context final SecurityContext sc, @PathParam("id") final long applicationId) throws Exception {
DataAccess.delete(Application.class, applicationId); DataAccess.delete(Application.class, applicationId);
} }
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
// //
// Generic /{id}/* // Generic /{id}/*
// //
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
@GET @GET
@Path("{id}/users") @Path("{id}/users")
@RolesAllowed(value = { "ADMIN" }) @RolesAllowed(value = { "ADMIN" })
public List<Long> getApplicationUsers(@PathParam("id") final Long applicationId) throws Exception { public List<Long> getApplicationUsers(@PathParam("id") final Long applicationId) throws Exception {
// special case for SSO: (all user have access on the SSO...). // special case for SSO: (all user have access on the SSO...).
this.logger.debug("Request list of user for an applciation: {}", applicationId); this.logger.debug("Request list of user for an applciation: {}", applicationId);
return getListOfUsers(applicationId); return getListOfUsers(applicationId);
} }
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
// //
// Generic /application/* // Generic /application/*
// //
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
@GET @GET
@Path("small") @Path("small")
@RolesAllowed(value = { "USER", "ADMIN" }) @RolesAllowed(value = { "USER", "ADMIN" })
@ -190,10 +190,10 @@ public class ApplicationResource {
} }
return out; return out;
} }
public record AddUserData( public record AddUserData(
long userId) {}; long userId) {}
// TODO : review the function to correct admin only access... // TODO : review the function to correct admin only access...
@POST @POST
@Path("{id}/users") @Path("{id}/users")
@ -203,7 +203,7 @@ public class ApplicationResource {
AddOnManyToMany.addLink(UserAuth.class, data.userId, "application", applicationId); AddOnManyToMany.addLink(UserAuth.class, data.userId, "application", applicationId);
return true; return true;
} }
// TODO : review the function to correct admin only access... // TODO : review the function to correct admin only access...
@DELETE @DELETE
@Path("{id}/users") @Path("{id}/users")
@ -213,7 +213,7 @@ public class ApplicationResource {
AddOnManyToMany.removeLink(UserAuth.class, data.userId, "application", applicationId); AddOnManyToMany.removeLink(UserAuth.class, data.userId, "application", applicationId);
return true; return true;
} }
// TODO : review the function to correct admin only access... // TODO : review the function to correct admin only access...
@GET @GET
@Path("{id}/rights") @Path("{id}/rights")
@ -222,7 +222,7 @@ public class ApplicationResource {
this.logger.debug("getApplications rights"); this.logger.debug("getApplications rights");
return DataAccess.getsWhere(RightDescription.class, new Condition(new QueryCondition("applicationId", "=", applicationId))); return DataAccess.getsWhere(RightDescription.class, new Condition(new QueryCondition("applicationId", "=", applicationId)));
} }
@GET @GET
@Path("get_token") @Path("get_token")
@RolesAllowed(value = { "USER", "ADMIN" }) @RolesAllowed(value = { "USER", "ADMIN" })
@ -230,7 +230,7 @@ public class ApplicationResource {
final GenericContext gc = (GenericContext) sc.getUserPrincipal(); final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.info("get application TOKEN application name='{}'", application); this.logger.info("get application TOKEN application name='{}'", application);
this.logger.debug("== USER ? {}", gc.userByToken.name); this.logger.debug("== USER ? {}", gc.userByToken.name);
if (application == null) { if (application == null) {
final String result = "Input error missing parameter: 'application'"; final String result = "Input error missing parameter: 'application'";
this.logger.debug(" result: {}", result); this.logger.debug(" result: {}", result);
@ -243,7 +243,7 @@ public class ApplicationResource {
isDev = true; isDev = true;
} }
this.logger.debug("Search for '{}' base of '{}'", applicationName, application); this.logger.debug("Search for '{}' base of '{}'", applicationName, application);
Application appl = null; Application appl = null;
try { try {
appl = DataAccess.getWhere(Application.class, new Condition(new QueryCondition("name", "=", applicationName))); appl = DataAccess.getWhere(Application.class, new Condition(new QueryCondition("name", "=", applicationName)));
@ -254,7 +254,7 @@ public class ApplicationResource {
this.logger.debug(" result: {}", result); this.logger.debug(" result: {}", result);
return Response.status(500).entity(result).build(); return Response.status(500).entity(result).build();
} }
if (appl == null) { if (appl == null) {
final String result = "Authentiocate-wrong email/login '" + applicationName + "')"; final String result = "Authentiocate-wrong email/login '" + applicationName + "')";
this.logger.error(" result: {}", result); this.logger.error(" result: {}", result);
@ -295,7 +295,7 @@ public class ApplicationResource {
} }
return Response.status(201).entity("{ \"url\":\"" + returnAdress + "\", \"jwt\":\"" + ret + "\"}").build(); return Response.status(201).entity("{ \"url\":\"" + returnAdress + "\", \"jwt\":\"" + ret + "\"}").build();
} }
@GET @GET
@Path("return") @Path("return")
@RolesAllowed(value = { "USER", "ADMIN" }) @RolesAllowed(value = { "USER", "ADMIN" })
@ -305,7 +305,7 @@ public class ApplicationResource {
this.logger.debug("====================================="); this.logger.debug("=====================================");
final GenericContext gc = (GenericContext) sc.getUserPrincipal(); final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("== USER ? {}", gc.userByToken); this.logger.debug("== USER ? {}", gc.userByToken);
if (application == null) { if (application == null) {
final String result = "Input error missing parameter: 'application'"; final String result = "Input error missing parameter: 'application'";
this.logger.error(" result: {}", result); this.logger.error(" result: {}", result);
@ -318,7 +318,7 @@ public class ApplicationResource {
isDev = true; isDev = true;
} }
this.logger.debug("Search for '{}' base of '{}'", applicationName, application); this.logger.debug("Search for '{}' base of '{}'", applicationName, application);
Application appl = null; Application appl = null;
try { try {
appl = DataAccess.getWhere(Application.class, new Condition(new QueryCondition("name", "=", applicationName))); appl = DataAccess.getWhere(Application.class, new Condition(new QueryCondition("name", "=", applicationName)));
@ -329,7 +329,7 @@ public class ApplicationResource {
this.logger.error(" result: {}", result); this.logger.error(" result: {}", result);
return Response.status(500).entity(result).build(); return Response.status(500).entity(result).build();
} }
if (appl == null) { if (appl == null) {
final String result = "Authentiocate-wrong email/login '" + applicationName + "')"; final String result = "Authentiocate-wrong email/login '" + applicationName + "')";
this.logger.error(" result: {}", result); this.logger.error(" result: {}", result);
@ -341,5 +341,5 @@ public class ApplicationResource {
} }
return Response.status(201).entity("{ \"url\":\"" + returnAdress + "\"}").build(); return Response.status(201).entity("{ \"url\":\"" + returnAdress + "\"}").build();
} }
} }

View File

@ -18,8 +18,8 @@ import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST; import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path; import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam; import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces; import jakarta.ws.rs.Produces;
@ -30,15 +30,15 @@ import jakarta.ws.rs.core.Response;
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public class RightResource { public class RightResource {
final static Logger logger = LoggerFactory.getLogger(RightResource.class); final static Logger logger = LoggerFactory.getLogger(RightResource.class);
public static List<RightDescription> getApplicationRightDecription(final long applicationId) throws Exception { public static List<RightDescription> getApplicationRightDecription(final long applicationId) throws Exception {
return DataAccess.getsWhere(RightDescription.class, new Condition(new QueryCondition("applicationId", "=", applicationId))); return DataAccess.getsWhere(RightDescription.class, new Condition(new QueryCondition("applicationId", "=", applicationId)));
} }
public static List<Right> getRawUserRight(final long userId, final long applicationId) throws Exception { public static List<Right> getRawUserRight(final long userId, final long applicationId) throws Exception {
return DataAccess.getsWhere(Right.class, new Condition(new QueryAnd(new QueryCondition("applicationId", "=", applicationId), new QueryCondition("userId", "=", userId)))); return DataAccess.getsWhere(Right.class, new Condition(new QueryAnd(new QueryCondition("applicationId", "=", applicationId), new QueryCondition("userId", "=", userId))));
} }
public static Map<String, Object> getUserRight(final long userId, final long applicationId) throws Exception { public static Map<String, Object> getUserRight(final long userId, final long applicationId) throws Exception {
final Map<String, Object> out = new HashMap<>(); final Map<String, Object> out = new HashMap<>();
final List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId); final List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId);
@ -55,7 +55,7 @@ public class RightResource {
logger.debug(" - id={} key={} type={} default={}", elem.id, elem.key, elem.type, elem.defaultValue); logger.debug(" - id={} key={} type={} default={}", elem.id, elem.key, elem.type, elem.defaultValue);
} }
for (final RightDescription description : rightsDescriptions) { for (final RightDescription description : rightsDescriptions) {
if (description == null) { if (description == null) {
// TODO: this is a really strange case to manage later... // TODO: this is a really strange case to manage later...
continue; continue;
@ -75,7 +75,7 @@ public class RightResource {
} }
return out; return out;
} }
public static void updateUserRight(final long userId, final long applicationId, final Map<String, Object> delta) throws Exception { public static void updateUserRight(final long userId, final long applicationId, final Map<String, Object> delta) throws Exception {
final List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId); final List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId);
logger.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId); logger.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
@ -116,28 +116,28 @@ public class RightResource {
} }
} }
} }
@GET @GET
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public List<Right> get() throws Exception { public List<Right> get() throws Exception {
return DataAccess.gets(Right.class); return DataAccess.gets(Right.class);
} }
@POST @POST
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public Right post(final String jsonRequest) throws Exception { public Right post(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Right.class, jsonRequest); return DataAccess.insertWithJson(Right.class, jsonRequest);
} }
@GET @GET
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public static Right getWithId(@PathParam("id") final Long id) throws Exception { public static Right getWithId(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Right.class, id); return DataAccess.get(Right.class, id);
} }
@PUT @PATCH
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -145,7 +145,7 @@ public class RightResource {
DataAccess.updateWithJson(Right.class, id, jsonRequest); DataAccess.updateWithJson(Right.class, id, jsonRequest);
return DataAccess.get(Right.class, id); return DataAccess.get(Right.class, id);
} }
@DELETE @DELETE
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -153,5 +153,5 @@ public class RightResource {
DataAccess.delete(Right.class, id); DataAccess.delete(Right.class, id);
return Response.ok().build(); return Response.ok().build();
} }
} }

View File

@ -17,7 +17,7 @@ import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed; import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT; import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.Path; import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam; import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces; import jakarta.ws.rs.Produces;
@ -30,21 +30,21 @@ import jakarta.ws.rs.core.SecurityContext;
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public class SystemConfigResource { public class SystemConfigResource {
final Logger logger = LoggerFactory.getLogger(SystemConfigResource.class); final Logger logger = LoggerFactory.getLogger(SystemConfigResource.class);
public static class GetSignUpAvaillable { public static class GetSignUpAvaillable {
public boolean signup; public boolean signup;
public GetSignUpAvaillable(final boolean availlable) { public GetSignUpAvaillable(final boolean availlable) {
this.signup = availlable; this.signup = availlable;
} }
public GetSignUpAvaillable() { public GetSignUpAvaillable() {
this.signup = false; this.signup = false;
} }
} }
public SystemConfigResource() {} public SystemConfigResource() {}
@GET @GET
@Path("is_sign_up_availlable") @Path("is_sign_up_availlable")
@PermitAll @PermitAll
@ -58,7 +58,7 @@ public class SystemConfigResource {
this.logger.debug("mlkmlk {}", tmp.signup); this.logger.debug("mlkmlk {}", tmp.signup);
return tmp; return tmp;
} }
@GET @GET
@Path("key/{key}") @Path("key/{key}")
@RolesAllowed(value = { "USER", "ADMIN" }) @RolesAllowed(value = { "USER", "ADMIN" })
@ -67,18 +67,18 @@ public class SystemConfigResource {
if (set == null) { if (set == null) {
throw new NotFoundException("Value does not exist"); throw new NotFoundException("Value does not exist");
} }
if (set.type.equals("BOOLEAN")) { if ("BOOLEAN".equals(set.type)) {
final boolean availlable = "true".equalsIgnoreCase(set.value); final boolean availlable = "true".equalsIgnoreCase(set.value);
return Response.status(200).entity("{ \"value\":" + availlable + "}").build(); return Response.status(200).entity("{ \"value\":" + availlable + "}").build();
} }
if (set.type.equals("NUMBER")) { if ("NUMBER".equals(set.type)) {
final double value = Double.parseDouble(set.value); final double value = Double.parseDouble(set.value);
return Response.status(200).entity("{ \"value\":" + value + "}").build(); return Response.status(200).entity("{ \"value\":" + value + "}").build();
} }
return Response.status(200).entity("{ \"value\":\"" + set.value + "\"}").build(); return Response.status(200).entity("{ \"value\":\"" + set.value + "\"}").build();
} }
@PUT @PATCH
@Path("key/{key}") @Path("key/{key}")
@RolesAllowed(value = { "ADMIN" }) @RolesAllowed(value = { "ADMIN" })
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -96,11 +96,11 @@ public class SystemConfigResource {
// Read the tree to filter injection of data: // Read the tree to filter injection of data:
final JsonNode root = mapper.readTree(jsonRequest); final JsonNode root = mapper.readTree(jsonRequest);
final JsonNode value = root.findPath("value"); final JsonNode value = root.findPath("value");
res.value = value.asText(); res.value = value.asText();
this.logger.debug("Update value : {}", res.value); this.logger.debug("Update value : {}", res.value);
DataAccess.update(res, res.id, List.of("value")); DataAccess.update(res, res.id, List.of("value"));
return Response.status(201).entity("{ \"value\":\"" + res.value + "\"}").build(); return Response.status(201).entity("{ \"value\":\"" + res.value + "\"}").build();
} }
} }

View File

@ -36,8 +36,8 @@ import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST; import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path; import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam; import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces; import jakarta.ws.rs.Produces;
@ -51,26 +51,26 @@ import jakarta.ws.rs.core.SecurityContext;
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public class UserResource { public class UserResource {
final Logger logger = LoggerFactory.getLogger(UserResource.class); final Logger logger = LoggerFactory.getLogger(UserResource.class);
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class UserOut { public class UserOut {
public long id; public long id;
public String login; public String login;
public UserOut(final long id, final String login) { public UserOut(final long id, final String login) {
this.id = id; this.id = id;
this.login = login; this.login = login;
} }
} }
public UserResource() {} public UserResource() {}
@GET @GET
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public List<UserAuthGet> getUsers() throws Exception { public List<UserAuthGet> getUsers() throws Exception {
return DataAccess.gets(UserAuthGet.class); return DataAccess.gets(UserAuthGet.class);
} }
@GET @GET
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -78,7 +78,7 @@ public class UserResource {
//GenericContext gc = (GenericContext) sc.getUserPrincipal(); //GenericContext gc = (GenericContext) sc.getUserPrincipal();
return DataAccess.get(UserAuthGet.class, userId); return DataAccess.get(UserAuthGet.class, userId);
} }
@POST @POST
@Path("{userId}/application/{applicationId}/link") @Path("{userId}/application/{applicationId}/link")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -92,15 +92,15 @@ public class UserResource {
} }
return DataAccess.get(UserAuth.class, userId); return DataAccess.get(UserAuth.class, userId);
} }
@GET @GET
@Path("{userId}/application/{applicationId}/rights") @Path("{userId}/application/{applicationId}/rights")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public Map<String, Object> getApplicationRight(@Context final SecurityContext sc, @PathParam("userId") final long userId, @PathParam("applicationId") final long applicationId) throws Exception { public Map<String, Object> getApplicationRight(@Context final SecurityContext sc, @PathParam("userId") final long userId, @PathParam("applicationId") final long applicationId) throws Exception {
return RightResource.getUserRight(userId, applicationId); return RightResource.getUserRight(userId, applicationId);
} }
@PUT @PATCH
@Path("{userId}/application/{applicationId}/rights") @Path("{userId}/application/{applicationId}/rights")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public Map<String, Object> patchApplicationRight(@Context final SecurityContext sc, @PathParam("userId") final long userId, @PathParam("applicationId") final long applicationId, public Map<String, Object> patchApplicationRight(@Context final SecurityContext sc, @PathParam("userId") final long userId, @PathParam("applicationId") final long applicationId,
@ -109,7 +109,7 @@ public class UserResource {
RightResource.updateUserRight(userId, applicationId, data); RightResource.updateUserRight(userId, applicationId, data);
return RightResource.getUserRight(userId, applicationId); return RightResource.getUserRight(userId, applicationId);
} }
// TODO: check this it might be deprecated ... // TODO: check this it might be deprecated ...
@POST @POST
@Path("{id}/set_admin") @Path("{id}/set_admin")
@ -123,7 +123,7 @@ public class UserResource {
} }
return Response.ok("{}").build(); return Response.ok("{}").build();
} }
@POST @POST
@Path("{id}/set_blocked") @Path("{id}/set_blocked")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -136,7 +136,7 @@ public class UserResource {
} }
return Response.ok("{}").build(); return Response.ok("{}").build();
} }
@POST @POST
@Path("create_new_user") @Path("create_new_user")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -147,17 +147,17 @@ public class UserResource {
throw new InputException("login", "Authentiocate-method-error (login too small: '" + user.login + "')"); throw new InputException("login", "Authentiocate-method-error (login too small: '" + user.login + "')");
} }
// TODO: check login format // TODO: check login format
if (user.email == null || user.email.length() < 6) { if (user.email == null || user.email.length() < 6) {
throw new InputException("email", "Authentiocate-method-error (email too small: '" + user.email + "')"); throw new InputException("email", "Authentiocate-method-error (email too small: '" + user.email + "')");
} }
// TODO: check email format // TODO: check email format
if (user.password == null || user.password.length() != 128) { if (user.password == null || user.password.length() != 128) {
throw new InputException("password", "null password, or wrong hash size"); throw new InputException("password", "null password, or wrong hash size");
} }
// TODO: verify if the data are a hash ... // TODO: verify if the data are a hash ...
// Check login does not exist // Check login does not exist
List<UserAuth> out = DataAccess.getsWhere(UserAuth.class, new Condition(new QueryCondition("login", "=", user.login))); List<UserAuth> out = DataAccess.getsWhere(UserAuth.class, new Condition(new QueryCondition("login", "=", user.login)));
if (out.size() >= 1) { if (out.size() >= 1) {
@ -168,7 +168,7 @@ public class UserResource {
if (out.size() >= 1) { if (out.size() >= 1) {
throw new FailException(Response.Status.BAD_REQUEST, "e-mail already used !!!"); throw new FailException(Response.Status.BAD_REQUEST, "e-mail already used !!!");
} }
// Add new user and return formated dat. // Add new user and return formated dat.
final UserAuth newUser = new UserAuth(); final UserAuth newUser = new UserAuth();
newUser.admin = false; newUser.admin = false;
@ -183,7 +183,7 @@ public class UserResource {
this.logger.debug("create new user done with id=={}", tmp.id); this.logger.debug("create new user done with id=={}", tmp.id);
return DataAccess.get(UserAuthGet.class, tmp.id); return DataAccess.get(UserAuthGet.class, tmp.id);
} }
@GET @GET
@Path("me") @Path("me")
@RolesAllowed("USER") @RolesAllowed("USER")
@ -193,7 +193,7 @@ public class UserResource {
this.logger.debug("== USER ? {}", gc.userByToken); this.logger.debug("== USER ? {}", gc.userByToken);
return new UserOut(gc.userByToken.id, gc.userByToken.name); return new UserOut(gc.userByToken.id, gc.userByToken.name);
} }
@POST @POST
@Path("password") @Path("password")
@RolesAllowed("USER") @RolesAllowed("USER")
@ -201,7 +201,7 @@ public class UserResource {
this.logger.debug("ChangePassword()"); this.logger.debug("ChangePassword()");
final GenericContext gc = (GenericContext) sc.getUserPrincipal(); final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("== USER ? {}", gc.userByToken); this.logger.debug("== USER ? {}", gc.userByToken);
if (data == null) { if (data == null) {
throw new InputException("data", "No data set..."); throw new InputException("data", "No data set...");
} }
@ -217,24 +217,24 @@ public class UserResource {
DataAccess.update(user, user.id, List.of("password")); DataAccess.update(user, user.id, List.of("password"));
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} }
/* /*
@GET @GET
@Path("validipass") @Path("validipass")
@PermitAll @PermitAll
public Response validatePasswordFromEMail(@QueryParam("uuid") String uuid, @QueryParam("securityId") String securityId) { public Response validatePasswordFromEMail(@QueryParam("uuid") String uuid, @QueryParam("securityId") String securityId) {
// Validate new password if OK // Validate new password if OK
// clear the passwordChange, passwordValidation fields // clear the passwordChange, passwordValidation fields
// send an e-mail to confirm the new password has been set. // send an e-mail to confirm the new password has been set.
return Response.status(500).build(); return Response.status(500).build();
} }
*/ */
@GET @GET
@Path("/check_login") @Path("/check_login")
@PermitAll @PermitAll
@ -246,7 +246,7 @@ public class UserResource {
} }
throw new NotFoundException("User does not exist: '" + login + "'"); throw new NotFoundException("User does not exist: '" + login + "'");
} }
// TODO: add an application TOKEN and permit only 50 requested (maybe add an option to disable it). // TODO: add an application TOKEN and permit only 50 requested (maybe add an option to disable it).
@GET @GET
@Path("/check_email") @Path("/check_email")
@ -259,7 +259,7 @@ public class UserResource {
} }
throw new NotFoundException("emain does not exist: '" + email + "'"); throw new NotFoundException("emain does not exist: '" + email + "'");
} }
private UserAuth checkAuthUser(final String method, final String login, final String time, final String password) throws Exception { private UserAuth checkAuthUser(final String method, final String login, final String time, final String password) throws Exception {
// check good version: // check good version:
if (!"v1".contentEquals(method)) { if (!"v1".contentEquals(method)) {
@ -278,7 +278,7 @@ public class UserResource {
query = "email"; query = "email";
} }
final UserAuth user = DataAccess.getWhere(UserAuth.class, new Condition(new QueryCondition(query, "=", login))); final UserAuth user = DataAccess.getWhere(UserAuth.class, new Condition(new QueryCondition(query, "=", login)));
if (user == null) { if (user == null) {
throw new FailException(Response.Status.PRECONDITION_FAILED, "FAIL Authentiocate-wrong email/login '" + login + "')"); throw new FailException(Response.Status.PRECONDITION_FAILED, "FAIL Authentiocate-wrong email/login '" + login + "')");
} }
@ -293,7 +293,7 @@ public class UserResource {
} }
return user; return user;
} }
@POST @POST
@Path("/get_token") @Path("/get_token")
@PermitAll @PermitAll
@ -304,7 +304,7 @@ public class UserResource {
// at the point the user has been not deleted and not blocked. // at the point the user has been not deleted and not blocked.
// this authentication is valid only for Karso ==> not for the application // this authentication is valid only for Karso ==> not for the application
final int expirationTimeInMinutes = ConfigVariable.getAuthExpirationTime(); final int expirationTimeInMinutes = ConfigVariable.getAuthExpirationTime();
// Get the USER Right (Note: by construction KARSO have application ID = KARSO_INITIALISATION_ID // Get the USER Right (Note: by construction KARSO have application ID = KARSO_INITIALISATION_ID
final Map<String, Object> ssoRight = RightResource.getUserRight(user.id, Initialization.KARSO_INITIALISATION_ID); final Map<String, Object> ssoRight = RightResource.getUserRight(user.id, Initialization.KARSO_INITIALISATION_ID);
if (!ssoRight.containsKey("USER")) { if (!ssoRight.containsKey("USER")) {
@ -318,16 +318,16 @@ public class UserResource {
outRight.put(applicationName, ssoRight); outRight.put(applicationName, ssoRight);
// TODO: maybe correct this get of TTL... // TODO: maybe correct this get of TTL...
final String ret = JWTWrapper.generateJWToken(user.id, user.login, "KarAuth", applicationName, outRight, expirationTimeInMinutes); final String ret = JWTWrapper.generateJWToken(user.id, user.login, "KarAuth", applicationName, outRight, expirationTimeInMinutes);
// Update last connection: // Update last connection:
final UserAuth newUser = new UserAuth(); final UserAuth newUser = new UserAuth();
newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now()); newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now());
DataAccess.update(newUser, user.id, List.of("lastConnection")); DataAccess.update(newUser, user.id, List.of("lastConnection"));
//logger.debug(" ==> generate token: {}", ret); //logger.debug(" ==> generate token: {}", ret);
return new GetToken(ret); return new GetToken(ret);
} }
public static String bytesToHex(final byte[] bytes) { public static String bytesToHex(final byte[] bytes) {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (final byte b : bytes) { for (final byte b : bytes) {
@ -335,7 +335,7 @@ public class UserResource {
} }
return sb.toString(); return sb.toString();
} }
public String getSHA512(final String passwordToHash) { public String getSHA512(final String passwordToHash) {
try { try {
final MessageDigest md = MessageDigest.getInstance("SHA-512"); final MessageDigest md = MessageDigest.getInstance("SHA-512");
@ -346,5 +346,5 @@ public class UserResource {
} }
return null; return null;
} }
} }

View File

@ -21,10 +21,10 @@ import org.slf4j.LoggerFactory;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestUnAuthorizedAPI { public class TestUnAuthorizedAPI {
private final static Logger LOGGER = LoggerFactory.getLogger(TestUnAuthorizedAPI.class); private final static Logger LOGGER = LoggerFactory.getLogger(TestUnAuthorizedAPI.class);
static WebLauncherTest webInterface = null; static WebLauncherTest webInterface = null;
static RESTApi api = null; static RESTApi api = null;
public void login(final String login, final String password) { public void login(final String login, final String password) {
try { try {
final GetToken token = api.post(GetToken.class, "users/get_token", DataGetToken.generate(login, "v1", "202515252", password)); final GetToken token = api.post(GetToken.class, "users/get_token", DataGetToken.generate(login, "v1", "202515252", password));
@ -33,11 +33,11 @@ public class TestUnAuthorizedAPI {
Assertions.fail("Can not get Authentication for '" + login + "' ==> " + ex.getMessage()); Assertions.fail("Can not get Authentication for '" + login + "' ==> " + ex.getMessage());
} }
} }
public void loginAdmin() { public void loginAdmin() {
login("karadmin", "adminA@666"); login("karadmin", "adminA@666");
} }
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
LOGGER.info("configure server ..."); LOGGER.info("configure server ...");
@ -54,7 +54,7 @@ public class TestUnAuthorizedAPI {
LOGGER.info("Start REST (DONE)"); LOGGER.info("Start REST (DONE)");
api = new RESTApi(ConfigBaseVariable.apiAdress); api = new RESTApi(ConfigBaseVariable.apiAdress);
} }
@AfterAll @AfterAll
public static void stopWebServer() throws InterruptedException, IOException { public static void stopWebServer() throws InterruptedException, IOException {
LOGGER.info("Kill the web server"); LOGGER.info("Kill the web server");
@ -65,11 +65,11 @@ public class TestUnAuthorizedAPI {
ConfigBaseVariable.clearAllValue(); ConfigBaseVariable.clearAllValue();
Thread.sleep(1000); Thread.sleep(1000);
} }
public void checkFail(final String type, final String urlOffset, final int errorStatus) { public void checkFail(final String type, final String urlOffset, final int errorStatus) {
checkFail(type, urlOffset, errorStatus, null); checkFail(type, urlOffset, errorStatus, null);
} }
public void checkFail(final String type, final String urlOffset, final int errorStatus, final String data) { public void checkFail(final String type, final String urlOffset, final int errorStatus, final String data) {
LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset); LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset);
try { try {
@ -77,8 +77,8 @@ public class TestUnAuthorizedAPI {
api.get(String.class, urlOffset); api.get(String.class, urlOffset);
} else if ("POST".equals(type)) { } else if ("POST".equals(type)) {
api.post(String.class, urlOffset, data); api.post(String.class, urlOffset, data);
} else if ("PUT".equals(type)) { } else if ("PATCH".equals(type)) {
api.put(String.class, urlOffset, data); api.patch(String.class, urlOffset, data);
} else if ("DELETE".equals(type)) { } else if ("DELETE".equals(type)) {
api.delete(String.class, urlOffset); api.delete(String.class, urlOffset);
} }
@ -92,13 +92,13 @@ public class TestUnAuthorizedAPI {
LOGGER.error("Unexpected throw error: {}", ex); LOGGER.error("Unexpected throw error: {}", ex);
Assertions.fail("Unexpected throws..."); Assertions.fail("Unexpected throws...");
} }
} }
public void checkWork(final String type, final String urlOffset) { public void checkWork(final String type, final String urlOffset) {
checkWork(type, urlOffset, null); checkWork(type, urlOffset, null);
} }
public void checkWork(final String type, final String urlOffset, final String data) { public void checkWork(final String type, final String urlOffset, final String data) {
LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset); LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset);
try { try {
@ -106,8 +106,8 @@ public class TestUnAuthorizedAPI {
api.get(String.class, urlOffset); api.get(String.class, urlOffset);
} else if ("POST".equals(type)) { } else if ("POST".equals(type)) {
api.post(String.class, urlOffset, data); api.post(String.class, urlOffset, data);
} else if ("PUT".equals(type)) { } else if ("PATCH".equals(type)) {
api.put(String.class, urlOffset, data); api.patch(String.class, urlOffset, data);
} else if ("DELETE".equals(type)) { } else if ("DELETE".equals(type)) {
api.delete(String.class, urlOffset); api.delete(String.class, urlOffset);
} }
@ -118,20 +118,20 @@ public class TestUnAuthorizedAPI {
LOGGER.error("Unexpected throw error: {}", ex); LOGGER.error("Unexpected throw error: {}", ex);
Assertions.fail("Unexpected throws..."); Assertions.fail("Unexpected throws...");
} }
} }
@Order(1) @Order(1)
@Test @Test
public void checkUnAuthorizedAPI() throws Exception { public void checkUnAuthorizedAPI() throws Exception {
// /application/ // /application/
checkFail("GET", "application/", 401); checkFail("GET", "application/", 401);
checkFail("POST", "application/", 401, "{}"); checkFail("POST", "application/", 401, "{}");
checkFail("PUT", "application/", 405, "{}"); // does not exist checkFail("PATCH", "application/", 405, "{}"); // does not exist
checkFail("DELETE", "application/", 405); // does not exist checkFail("DELETE", "application/", 405); // does not exist
// /application/{id} // /application/{id}
checkFail("GET", "application/0", 401); checkFail("GET", "application/0", 401);
checkFail("PUT", "application/0", 401, "{}"); checkFail("PATCH", "application/0", 401, "{}");
checkFail("POST", "application/0", 405, "{}"); checkFail("POST", "application/0", 405, "{}");
checkFail("DELETE", "application/0", 401); checkFail("DELETE", "application/0", 401);
// /application/{id}/* // /application/{id}/*
@ -140,33 +140,33 @@ public class TestUnAuthorizedAPI {
checkFail("GET", "application/small", 401); checkFail("GET", "application/small", 401);
checkFail("GET", "application/get_token", 401); checkFail("GET", "application/get_token", 401);
checkFail("GET", "application/return", 401); checkFail("GET", "application/return", 401);
// /application_token/ section: // /application_token/ section:
checkFail("GET", "application_token/0", 401); checkFail("GET", "application_token/0", 401);
checkFail("DELETE", "application_token/0/5", 401); checkFail("DELETE", "application_token/0/5", 401);
checkFail("DELETE", "application_token/0/create", 401); checkFail("DELETE", "application_token/0/create", 401);
// /front/* // /front/*
checkFail("GET", "front", 404); // no index in test section checkFail("GET", "front", 404); // no index in test section
// health check // health check
checkWork("GET", "health_check"); checkWork("GET", "health_check");
// public_key (only application) // public_key (only application)
checkFail("GET", "public_key", 401); checkFail("GET", "public_key", 401);
checkFail("GET", "public_key/pem", 401); checkFail("GET", "public_key/pem", 401);
// /right // /right
checkFail("GET", "right", 401); checkFail("GET", "right", 401);
checkFail("POST", "right", 401, "{}"); checkFail("POST", "right", 401, "{}");
checkFail("GET", "right/0", 401); checkFail("GET", "right/0", 401);
checkFail("PUT", "right/0", 401, "{}"); checkFail("PATCH", "right/0", 401, "{}");
checkFail("DELETE", "right/0", 401); checkFail("DELETE", "right/0", 401);
// /system_config // /system_config
checkWork("GET", "system_config/is_sign_up_availlable"); checkWork("GET", "system_config/is_sign_up_availlable");
checkFail("GET", "system_config/key/skjdfhkjsdhfkjsh", 401); checkFail("GET", "system_config/key/skjdfhkjsdhfkjsh", 401);
checkFail("PUT", "system_config/key/skjdfhkjsdhfkjsh", 401, "{}"); checkFail("PATCH", "system_config/key/skjdfhkjsdhfkjsh", 401, "{}");
// /users // /users
checkFail("GET", "users", 401); checkFail("GET", "users", 401);
checkFail("GET", "users/0", 401); checkFail("GET", "users/0", 401);
@ -181,7 +181,7 @@ public class TestUnAuthorizedAPI {
checkWork("GET", "users/check_email?email=admin@admin.ZZZ"); checkWork("GET", "users/check_email?email=admin@admin.ZZZ");
checkFail("GET", "users/check_email?email=ksjhdkjfhskjdh", 404); checkFail("GET", "users/check_email?email=ksjhdkjfhskjdh", 404);
// not testable : get_token // not testable : get_token
} }
} }

View File

@ -382,7 +382,7 @@ export class AdminUserService {
.requestJson({ .requestJson({
server: 'karso', server: 'karso',
endPoint: `users/${userId}/application/${applicationId}/rights`, endPoint: `users/${userId}/application/${applicationId}/rights`,
requestType: HTTPRequestModel.PUT, requestType: HTTPRequestModel.PATCH,
accept: HTTPMimeType.JSON, accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON, contentType: HTTPMimeType.JSON,
body: dataUpdate body: dataUpdate

View File

@ -286,7 +286,7 @@ export class ApplicationService {
.requestJson({ .requestJson({
server: 'karso', server: 'karso',
endPoint: `application/${id}`, endPoint: `application/${id}`,
requestType: HTTPRequestModel.PUT, requestType: HTTPRequestModel.PATCH,
accept: HTTPMimeType.JSON, accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON, contentType: HTTPMimeType.JSON,
body: updateState, body: updateState,

View File

@ -13,7 +13,7 @@ class MultipleRequest {
failResponse = undefined; failResponse = undefined;
data = {}; data = {};
constructor(private resolve: any, private reject: any, private countRequest: number) {} constructor(private resolve: any, private reject: any, private countRequest: number) { }
add(key: string, value: any): void { add(key: string, value: any): void {
this.requestDone += 1; this.requestDone += 1;
this.data[key] = value; this.data[key] = value;
@ -44,7 +44,7 @@ class MultipleRequest {
@Injectable() @Injectable()
export class SettingsService { export class SettingsService {
constructor(private http: HttpWrapperService) {} constructor(private http: HttpWrapperService) { }
/** /**
* Get a generic setting (Key value) * Get a generic setting (Key value)
* @returns a promise of the data value * @returns a promise of the data value
@ -76,7 +76,7 @@ export class SettingsService {
this.http this.http
.requestJson({ .requestJson({
endPoint: `system_config/key/${key}`, endPoint: `system_config/key/${key}`,
requestType: HTTPRequestModel.PUT, requestType: HTTPRequestModel.PATCH,
accept: HTTPMimeType.JSON, accept: HTTPMimeType.JSON,
contentType: HTTPMimeType.JSON, contentType: HTTPMimeType.JSON,
body: { body: {

@ -1 +1 @@
Subproject commit 9fc25b4feaeba509ff39f70b24d97be47f4b30e1 Subproject commit 0496753211a09aacb11436567d513b3586bbaabb