[FIX] many correction:

- missing some @Produces
  - update logger in static
  - some coding style
  - Some error in code
This commit is contained in:
Edouard DUPIN 2024-05-09 00:20:18 +02:00
parent 7a4c5c2625
commit faf60ed89b
34 changed files with 404 additions and 350 deletions

View File

@ -49,7 +49,7 @@ import org.slf4j.LoggerFactory;
import jakarta.ws.rs.core.UriBuilder;
public class WebLauncher {
final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class);
private static final Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class);
public static DBConfig dbConfig;
protected UpdateJwtPublicKey keyUpdater = null;
protected HttpServer server = null;

View File

@ -7,10 +7,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebLauncherEdgeLocal {
final Logger logger = LoggerFactory.getLogger(WebLauncherEdgeLocal.class);
private static final Logger LOGGER = LoggerFactory.getLogger(WebLauncherEdgeLocal.class);
private WebLauncherEdgeLocal() {}
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
if (true) {
// for local test:
ConfigBaseVariable.apiAdress = "http://0.0.0.0:15080/karso/api/";

View File

@ -15,8 +15,10 @@ import org.kar.archidata.exception.InputException;
import org.kar.archidata.exception.SystemException;
import org.kar.archidata.filter.GenericContext;
import org.kar.archidata.tools.JWTWrapper;
import org.kar.karso.model.AddUserData;
import org.kar.karso.model.Application;
import org.kar.karso.model.ApplicationSmall;
import org.kar.karso.model.ClientToken;
import org.kar.karso.model.RightDescription;
import org.kar.karso.model.UserAuth;
import org.kar.karso.model.UserLinkApplication;
@ -40,7 +42,7 @@ import jakarta.ws.rs.core.SecurityContext;
@Path("/application")
@Produces(MediaType.APPLICATION_JSON)
public class ApplicationResource {
final Logger logger = LoggerFactory.getLogger(ApplicationResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationResource.class);
public ApplicationResource() {}
@ -54,7 +56,7 @@ public class ApplicationResource {
// TODO Auto-generated catch block
e.printStackTrace();
final String result = "SERVER Internal error";
this.logger.error(" result: {}", result);
LOGGER.error(" result: {}", result);
return out;
}
for (final UserLinkApplication app : links) {
@ -72,10 +74,10 @@ public class ApplicationResource {
} catch (final Exception e) {
e.printStackTrace();
final String result = "SERVER Internal error";
this.logger.error(" result: {}", result);
LOGGER.error(" result: {}", result);
return out;
}
this.logger.debug("Find list of user for an application: {}", links);
LOGGER.debug("Find list of user for an application: {}", links);
for (final UserLinkApplication app : links) {
out.add(app.userId);
}
@ -91,7 +93,7 @@ public class ApplicationResource {
@RolesAllowed(value = { "USER", "ADMIN" })
public List<Application> gets(@Context final SecurityContext sc) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("getApplications");
LOGGER.debug("getApplications");
// TODO filter with the list of element available in his authorizations ...
final List<Application> tmp = DataAccess.gets(Application.class);
if (gc.userByToken.hasRight("ADMIN", true)) {
@ -109,8 +111,9 @@ public class ApplicationResource {
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Application create(final Application application) throws Exception {
this.logger.debug("create new application {}", application);
LOGGER.debug("create new application {}", application);
// verify login or email is correct:
if (application.name == null || application.name.length() < 5) {
throw new InputException("name", "create application (name too small: '" + application.name + "')");
@ -169,7 +172,7 @@ public class ApplicationResource {
public List<Long> getApplicationUsers(@PathParam("id") final Long applicationId) throws Exception {
// special case for SSO: (all user have access on the SSO...).
this.logger.debug("Request list of user for an applciation: {}", applicationId);
LOGGER.debug("Request list of user for an applciation: {}", applicationId);
return getListOfUsers(applicationId);
}
@ -184,7 +187,7 @@ public class ApplicationResource {
@RolesAllowed(value = { "USER", "ADMIN" })
public List<ApplicationSmall> getApplicationsSmall(@Context final SecurityContext sc) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("getApplications");
LOGGER.debug("getApplications");
final List<Application> tmp = DataAccess.gets(Application.class);
final List<Long> regular = getUserListOfApplication(gc.userByToken.id);
final List<ApplicationSmall> out = new ArrayList<>();
@ -196,20 +199,12 @@ public class ApplicationResource {
return out;
}
public class AddUserData {
public long userId;
public AddUserData(final long userId) {
this.userId = userId;
}
}
@POST
@Path("{id}/users")
@RolesAllowed(value = { "ADMIN" })
@Consumes(MediaType.APPLICATION_JSON)
public void addUser(@PathParam("id") final Long applicationId, final AddUserData data) throws Exception {
this.logger.debug("getApplications");
LOGGER.debug("getApplications");
AddOnManyToMany.addLink(UserAuth.class, data.userId, "application", applicationId);
}
@ -218,7 +213,7 @@ public class ApplicationResource {
@RolesAllowed(value = { "ADMIN" })
public void removeUser(@PathParam("id") final Long applicationId, @PathParam("userId") final Long userId)
throws Exception {
this.logger.debug("getApplications");
LOGGER.debug("getApplications");
AddOnManyToMany.removeLink(UserAuth.class, userId, "application", applicationId);
}
@ -226,22 +221,11 @@ public class ApplicationResource {
@Path("{id}/rights")
@RolesAllowed(value = { "ADMIN" })
public List<RightDescription> getRightsDescription(@PathParam("id") final Long applicationId) throws Exception {
this.logger.debug("getApplications rights");
LOGGER.debug("getApplications rights");
return DataAccess.getsWhere(RightDescription.class,
new Condition(new QueryCondition("applicationId", "=", applicationId)));
}
public class ClientToken {
public String url;
public String jwt;
public ClientToken(final String url, final String jwt) {
this.url = url;
this.jwt = jwt;
}
}
@GET
@Path("get_token")
@RolesAllowed(value = { "USER", "ADMIN" })
@ -249,8 +233,8 @@ public class ApplicationResource {
@Context final SecurityContext sc,
@QueryParam("application") final String application) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.info("get application TOKEN application name='{}'", application);
this.logger.debug("== USER ? {}", gc.userByToken.name);
LOGGER.info("get application TOKEN application name='{}'", application);
LOGGER.debug("== USER ? {}", gc.userByToken.name);
if (application == null) {
throw new InputException("application", "Input error missing parameter");
@ -261,7 +245,7 @@ public class ApplicationResource {
applicationName = applicationName.substring(0, applicationName.length() - 4);
isDev = true;
}
this.logger.debug("Search for '{}' base of '{}'", applicationName, application);
LOGGER.debug("Search for '{}' base of '{}'", applicationName, application);
Application appl = null;
try {
@ -271,13 +255,13 @@ public class ApplicationResource {
// TODO Auto-generated catch block
e.printStackTrace();
final String result = "SERVER Internal error";
this.logger.debug(" result: {}", result);
LOGGER.debug(" result: {}", result);
throw new SystemException("Internal fail request");
}
if (appl == null) {
final String result = "Authentiocate-wrong email/login '" + applicationName + "')";
this.logger.error(" result: {}", result);
LOGGER.error(" result: {}", result);
throw new InputException("email/login", "Authentiocate-wrong email/login '" + applicationName + "'");
}
UserLinkApplication links = null;
@ -319,11 +303,11 @@ public class ApplicationResource {
@RolesAllowed(value = { "USER", "ADMIN" })
public String logOut(@Context final SecurityContext sc, @QueryParam("application") final String application)
throws SystemException, InputException {
this.logger.debug("=====================================");
this.logger.debug("Get log_out()");
this.logger.debug("=====================================");
LOGGER.debug("=====================================");
LOGGER.debug("Get log_out()");
LOGGER.debug("=====================================");
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("== USER ? {}", gc.userByToken);
LOGGER.debug("== USER ? {}", gc.userByToken);
if (application == null) {
throw new InputException("application", "Input error missing parameter");
@ -334,7 +318,7 @@ public class ApplicationResource {
applicationName = applicationName.substring(0, applicationName.length() - 4);
isDev = true;
}
this.logger.debug("Search for '{}' base of '{}'", applicationName, application);
LOGGER.debug("Search for '{}' base of '{}'", applicationName, application);
Application appl = null;
try {

View File

@ -12,10 +12,12 @@ import org.kar.archidata.dataAccess.options.Condition;
import org.kar.archidata.exception.DataAccessException;
import org.kar.archidata.exception.InputException;
import org.kar.karso.model.ApplicationToken;
import org.kar.karso.model.CreateTokenRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
@ -29,7 +31,7 @@ import jakarta.ws.rs.core.SecurityContext;
@Path("/application_token")
@Produces(MediaType.APPLICATION_JSON)
public class ApplicationTokenResource {
final Logger logger = LoggerFactory.getLogger(ApplicationTokenResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationTokenResource.class);
public ApplicationTokenResource() {}
@ -97,28 +99,19 @@ public class ApplicationTokenResource {
return out.toString();
}
public class CreateRequest {
public CreateRequest(final String name, final Integer validity) {
this.name = name;
this.validity = validity;
}
public String name;
public Integer validity;
};
@POST
@Path("/{applicationId}/create")
@Path("{applicationId}/create")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public ApplicationToken create(
@Context final SecurityContext sc,
@PathParam("applicationId") final Long applicationId,
final CreateRequest request) throws Exception {
this.logger.info("get user application TOKEN: app='{}' user='???'", applicationId);
final CreateTokenRequest request) throws Exception {
LOGGER.info("get user application TOKEN: app='{}' user='???'", applicationId);
// correct input string stream :
final String name = multipartCorrection(request.name);
//validity = multipartCorrection(validity);
this.logger.debug("create a new token...");
LOGGER.debug("create a new token...");
if (applicationId == null) {
throw new InputException("applicationId", "can not be null");
}
@ -127,7 +120,7 @@ public class ApplicationTokenResource {
if (validity == null || validity < 0 || validity > maximum) {
validity = maximum;
}
this.logger.warn("validity= {}", validity);
LOGGER.warn("validity= {}", validity);
// todo: set validity timestamp ...
// TODO: check if application exist ...
ApplicationToken token = new ApplicationToken();
@ -135,9 +128,9 @@ public class ApplicationTokenResource {
token.name = multipartCorrection(name);
token.parentId = applicationId;
final OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
this.logger.warn("Check Timestamp now = {}", now);
LOGGER.warn("Check Timestamp now = {}", now);
token.endValidityTime = Timestamp.from(now.plusDays(validity).toInstant());
this.logger.warn("token.endValidityTime = {}", token.endValidityTime);
LOGGER.warn("token.endValidityTime = {}", token.endValidityTime);
// insert in the BDD
token = DataAccess.insert(token);

View File

@ -1,15 +1,16 @@
package org.kar.karso.api;
import jakarta.ws.rs.*;
import org.kar.archidata.api.FrontGeneric;
import org.kar.karso.util.ConfigVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.Path;
@Path("/front")
public class Front extends FrontGeneric {
final Logger logger = LoggerFactory.getLogger(FrontGeneric.class);
private static final Logger LOGGER = LoggerFactory.getLogger(FrontGeneric.class);
public Front() {
this.baseFrontFolder = ConfigVariable.getFrontFolder();
}

View File

@ -16,7 +16,7 @@ import jakarta.ws.rs.core.Response;
@Path("/health_check")
@Produces(MediaType.APPLICATION_JSON)
public class HealthCheck {
final static Logger LOGGER = LoggerFactory.getLogger(HealthCheck.class);
private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheck.class);
public record HealthResult(
String value) {};

View File

@ -19,7 +19,7 @@ import jakarta.ws.rs.core.MediaType;
@Path("/public_key")
@Produces(MediaType.APPLICATION_JSON)
public class PublicKeyResource {
final Logger logger = LoggerFactory.getLogger(PublicKeyResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(PublicKeyResource.class);
public PublicKeyResource() {

View File

@ -29,7 +29,7 @@ import jakarta.ws.rs.core.MediaType;
@Path("/right")
@Produces({ MediaType.APPLICATION_JSON })
public class RightResource {
final static Logger logger = LoggerFactory.getLogger(RightResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(RightResource.class);
public static List<RightDescription> getApplicationRightDecription(final long applicationId) throws Exception {
return DataAccess.getsWhere(RightDescription.class,
@ -47,22 +47,22 @@ public class RightResource {
public static Map<String, Object> getUserRight(final long userId, final long applicationId) throws Exception {
final Map<String, Object> out = new HashMap<>();
final List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId);
logger.trace("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
LOGGER.trace("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
if (rightsDescriptions != null && rightsDescriptions.size() != 0) {
final List<Right> rights = getRawUserRight(userId, applicationId);
logger.trace("Get some user right: count={} userID={} applicationId={}", rights.size(), userId,
LOGGER.trace("Get some user right: count={} userID={} applicationId={}", rights.size(), userId,
applicationId);
logger.trace("Rights:");
LOGGER.trace("Rights:");
for (final Right elem : rights) {
logger.trace(" - applId={} rightDescriptionId={} value={}", elem.applicationId,
LOGGER.trace(" - applId={} rightDescriptionId={} value={}", elem.applicationId,
elem.rightDescriptionId, elem.value);
}
logger.trace("RightDescription:");
LOGGER.trace("RightDescription:");
for (final RightDescription description : rightsDescriptions) {
if (description == null) {
continue;
}
logger.trace(" - id={} key={} type={} default={}", description.id, description.key, description.type,
LOGGER.trace(" - id={} key={} type={} default={}", description.id, description.key, description.type,
description.defaultValue);
}
for (final RightDescription description : rightsDescriptions) {
@ -81,7 +81,7 @@ public class RightResource {
}
} else {
// the application does not manage right with Karso (normal use-case)
logger.debug("Does not manage Karso right...");
LOGGER.debug("Does not manage Karso right...");
}
return out;
}
@ -89,12 +89,12 @@ public class RightResource {
public static void updateUserRight(final long userId, final long applicationId, final Map<String, Object> delta)
throws Exception {
final List<RightDescription> rightsDescriptions = getApplicationRightDecription(applicationId);
logger.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
LOGGER.debug("Get some descriptions: {} applicationId={}", rightsDescriptions.size(), applicationId);
if (rightsDescriptions == null || rightsDescriptions.size() == 0) {
throw new IllegalArgumentException("Request change right on an application that does not manage any right");
}
final List<Right> rights = getRawUserRight(userId, applicationId);
logger.debug("Get some user right: count={} userID={}", rights.size(), userId);
LOGGER.debug("Get some user right: count={} userID={}", rights.size(), userId);
for (final RightDescription description : rightsDescriptions) {
if (description == null) {
// TODO: this is a really strange case to manage later...
@ -114,19 +114,19 @@ public class RightResource {
if (allRights.size() > 1) {
// special case of error somewhere else ... ==> remove all elements (except the first)
for (int iii = 1; iii < allRights.size(); iii++) {
logger.error("Remove starnge element in Right id={} ", allRights.get(iii).id);
LOGGER.error("Remove starnge element in Right id={} ", allRights.get(iii).id);
DataAccess.delete(Right.class, allRights.get(iii).id);
}
}
if (allRights.size() == 1) {
final Right right = allRights.get(0);
// The value exist, we need to update it
logger.debug("Request update a knonwn parameter: {} with {}", description.key, newValue);
LOGGER.debug("Request update a knonwn parameter: {} with {}", description.key, newValue);
right.value = convertedValue;
DataAccess.update(right, right.id, List.of("value"));
} else {
// we need to create it
logger.debug("Request create parameter: {} with {}", description.key, newValue);
LOGGER.debug("Request create parameter: {} with {}", description.key, newValue);
final Right right = new Right();
right.applicationId = applicationId;
right.userId = userId;

View File

@ -30,7 +30,7 @@ import jakarta.ws.rs.core.SecurityContext;
@Path("/system_config")
@Produces(MediaType.APPLICATION_JSON)
public class SystemConfigResource {
final Logger logger = LoggerFactory.getLogger(SystemConfigResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(SystemConfigResource.class);
public static class GetSignUpAvailable {
public boolean signup;
@ -57,7 +57,7 @@ public class SystemConfigResource {
}
final boolean availlable = "true".equalsIgnoreCase(set.value);
final GetSignUpAvailable tmp = new GetSignUpAvailable(availlable);
this.logger.debug("mlkmlk {}", tmp.signup);
LOGGER.debug("mlkmlk {}", tmp.signup);
return tmp;
}
@ -104,7 +104,7 @@ public class SystemConfigResource {
final JsonNode value = root.findPath("value");
res.value = value.asText();
this.logger.debug("Update value : {}", res.value);
LOGGER.debug("Update value : {}", res.value);
DataAccess.update(res, res.id, List.of("value"));
}

View File

@ -49,7 +49,7 @@ import jakarta.ws.rs.core.SecurityContext;
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
final Logger logger = LoggerFactory.getLogger(UserResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserOut {
@ -86,7 +86,7 @@ public class UserResource {
@PathParam("userId") final long userId,
@PathParam("applicationId") final long applicationId,
final boolean data) throws Exception {
this.logger.debug("Find typeNode");
LOGGER.debug("Find typeNode");
if (data) {
AddOnManyToMany.addLink(UserAuth.class, userId, "application", applicationId);
} else {
@ -114,7 +114,7 @@ public class UserResource {
@PathParam("userId") final long userId,
@PathParam("applicationId") final long applicationId,
final Map<String, Object> data) throws Exception {
this.logger.info("Patch data from FRONT: {}", data);
this.LOGGER.info("Patch data from FRONT: {}", data);
RightResource.updateUserRight(userId, applicationId, data);
return RightResource.getUserRight(userId, applicationId);
}
@ -152,7 +152,7 @@ public class UserResource {
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public UserAuthGet create(final UserCreate user) throws Exception {
this.logger.debug("create new User email={} login={}", user.email, user.login);
LOGGER.debug("create new User email={} login={}", user.email, user.login);
// verify login or email is correct:
if (user.login == null || user.login.length() < 6) {
throw new InputException("login", "Authentiocate-method-error (login too small: '" + user.login + "')");
@ -192,7 +192,7 @@ public class UserResource {
newUser.email = user.email;
newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now());
final UserAuth tmp = DataAccess.insert(newUser);
this.logger.debug("create new user done with id=={}", tmp.id);
LOGGER.debug("create new user done with id=={}", tmp.id);
return DataAccess.get(UserAuthGet.class, tmp.id);
}
@ -200,9 +200,9 @@ public class UserResource {
@Path("me")
@RolesAllowed("USER")
public UserOut getMe(@Context final SecurityContext sc) {
this.logger.debug("getMe()");
LOGGER.debug("getMe()");
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("== USER ? {}", gc.userByToken);
LOGGER.debug("== USER ? {}", gc.userByToken);
return new UserOut(gc.userByToken.id, gc.userByToken.name);
}
@ -211,9 +211,9 @@ public class UserResource {
@RolesAllowed("USER")
@Consumes(MediaType.APPLICATION_JSON)
public void changePassword(@Context final SecurityContext sc, final ChangePassword data) throws Exception {
this.logger.debug("ChangePassword()");
LOGGER.debug("ChangePassword()");
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("== USER ? {}", gc.userByToken);
LOGGER.debug("== USER ? {}", gc.userByToken);
if (data == null) {
throw new InputException("data", "No data set...");
@ -234,7 +234,7 @@ public class UserResource {
@Path("is_login_exist")
@PermitAll
public Boolean isLoginExist(@QueryParam("login") final String login) throws Exception {
this.logger.debug("checkLogin: '{}'", login);
LOGGER.debug("checkLogin: '{}'", login);
final List<UserAuth> out = DataAccess.getsWhere(UserAuth.class,
new Condition(new QueryCondition("login", "=", login)));
return out.size() >= 1;
@ -245,7 +245,7 @@ public class UserResource {
@Path("is_email_exist")
@PermitAll
public Boolean isEmailExist(@QueryParam("email") final String email) throws Exception {
this.logger.debug("checkEmail: {}", email);
LOGGER.debug("checkEmail: {}", email);
final List<UserAuth> out = DataAccess.getsWhere(UserAuth.class,
new Condition(new QueryCondition("email", "=", email)));
return out.size() >= 1;
@ -280,7 +280,7 @@ public class UserResource {
if (!passwodCheck.contentEquals(password)) {
throw new FailException(Response.Status.PRECONDITION_FAILED, "Password error ...");
}
this.logger.debug(" ==> pass nearly all test : admin={} blocked={} removed={}", user.admin, user.blocked,
LOGGER.debug(" ==> pass nearly all test : admin={} blocked={} removed={}", user.admin, user.blocked,
user.removed);
if (user.blocked || user.removed) {
throw new FailException(Response.Status.UNAUTHORIZED, "FAIL Authentiocate");
@ -293,7 +293,7 @@ public class UserResource {
@PermitAll
@Consumes(MediaType.APPLICATION_JSON)
public GetToken getToken(final DataGetToken data) throws Exception {
this.logger.info("User Authenticate: {}", data.login());
LOGGER.info("User Authenticate: {}", data.login());
final UserAuth user = checkAuthUser(data.method(), data.login(), data.time(), data.password());
// at the point the user has been not deleted and not blocked.
// this authentication is valid only for Karso ==> not for the application
@ -306,7 +306,7 @@ public class UserResource {
// If the USER is not override, the system add by default USER
ssoRight.put("USER", true);
}
this.logger.debug("Get new token with right: {}", ssoRight);
LOGGER.debug("Get new token with right: {}", ssoRight);
final Map<String, Object> outRight = new HashMap<>();
final String applicationName = "karso";
// we set the right in the under map to manage multiple application group right. and in some application user can see other user or all user of the application
@ -322,7 +322,7 @@ public class UserResource {
newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now());
DataAccess.update(newUser, user.id, List.of("lastConnection"));
//logger.debug(" ==> generate token: {}", ret);
//LOGGER.debug(" ==> generate token: {}", ret);
return new GetToken(ret);
}

View File

@ -18,7 +18,7 @@ import jakarta.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class KarsoAuthenticationFilter extends AuthenticationFilter {
final Logger logger = LoggerFactory.getLogger(KarsoAuthenticationFilter.class);
private static final Logger LOGGER = LoggerFactory.getLogger(KarsoAuthenticationFilter.class);
//curl http://0.0.0.0:15080/karso/api/public_key/pem --output plop.txt -H "Authorization: Zota 1:U0sJM1m@-STSdfg4365fJOFUGbR4kFycBu1qGZPwf7gW6k2WWRBzTPUH7QutCgPw-SDss45_563sSDFdfg@dsf@456" --verbose
@ -51,7 +51,8 @@ public class KarsoAuthenticationFilter extends AuthenticationFilter {
}
// TODO: check UTC !!!
if (!value.endValidityTime.after(Timestamp.from(Instant.now()))) {
System.out.println("Application authentication Time-out '" + authorization + "' " + value.endValidityTime + " > " + Timestamp.from(Instant.now()));
System.out.println("Application authentication Time-out '" + authorization + "' " + value.endValidityTime
+ " > " + Timestamp.from(Instant.now()));
return null;
}
// ----------------------------------

View File

@ -14,7 +14,8 @@ public class Initialization extends MigrationSqlStep {
public static final int KARSO_INITIALISATION_ID = 1;
public static final List<Class<?>> CLASSES_BASE = List.of(Settings.class, UserAuth.class,Application.class,ApplicationToken.class,RightDescription.class,Right.class);
public static final List<Class<?>> CLASSES_BASE = List.of(Settings.class, UserAuth.class, Application.class,
ApplicationToken.class, RightDescription.class, Right.class);
@Override
public String getName() {
@ -31,12 +32,14 @@ public class Initialization extends MigrationSqlStep {
addClass(clazz);
}
addAction("""
addAction(
"""
INSERT INTO `application` (`id`, `name`, `description`, `redirect`, `redirectDev`, `notification`, `ttl`) VALUES
(1, 'karso', 'Root SSO interface', 'http://atria-soft/karso', '', '', 666);
""");
// default admin: "karadmin" password: "adminA@666"
addAction("""
addAction(
"""
INSERT INTO `user` (`id`, `login`, `password`, `email`, `admin`) VALUES
(1, 'karadmin', '0ddcac5ede3f1300a1ce5948ab15112f2810130531d578ab8bc4dc131652d7cf7a3ff6e827eb957bff43bc2c65a6a1d46722e5b3a2343ac3176a33ea7250080b',
'admin@admin.ZZZ', 1);
@ -52,7 +55,8 @@ public class Initialization extends MigrationSqlStep {
('SIGN_UP_FILTER', 'rw----', 'STRING', '.*'),
('EMAIL_VALIDATION_REQUIRED', 'rwr-r-', 'BOOLEAN', 'false');
""");
addAction("""
addAction(
"""
INSERT INTO `rightDescription` (`id`, `applicationId`, `key`, `title`, `description`, `type`, `defaultValue`) VALUES
(1, 1, 'ADMIN', 'Administrator', 'Full administrator Right', 'BOOLEAN', 'false');
""");

View File

@ -20,7 +20,8 @@ public class Migration20231015 extends MigrationSqlStep {
@Override
public void generateStep() throws Exception {
for (final String elem : List.of("application", "applicationToken", "right", "rightDescription", "settings", "user", "user_link_application")) { //, "user_link_cover")) {
for (final String elem : List.of("application", "applicationToken", "right", "rightDescription", "settings",
"user", "user_link_application")) { //, "user_link_cover")) {
addAction("""
ALTER TABLE `""" + elem + """

View File

@ -18,7 +18,8 @@ public class Migration20231126 extends MigrationSqlStep {
@Override
public void generateStep() throws Exception {
// update migration update (last one)
addAction("""
addAction(
"""
ALTER TABLE `KAR_migration`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `create_date` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -32,7 +33,8 @@ public class Migration20231126 extends MigrationSqlStep {
CHANGE `log` `log` text COLLATE 'utf8mb3_general_ci' NULL COMMENT 'Log generate by the migration' AFTER `count`;
""");
addAction("""
addAction(
"""
ALTER TABLE `application`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `createdAt` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -46,7 +48,8 @@ public class Migration20231126 extends MigrationSqlStep {
CHANGE `ttl` `ttl` int NOT NULL DEFAULT '666' COMMENT 'Expiration time ' AFTER `notification`,
CHANGE `manageRight` `manageRight` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Right is manage with Karso' AFTER `ttl`;
""");
addAction("""
addAction(
"""
ALTER TABLE `applicationToken`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `createdAt` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -58,7 +61,8 @@ public class Migration20231126 extends MigrationSqlStep {
CHANGE `token` `token` text COLLATE 'utf8mb3_general_ci' NOT NULL AFTER `endValidityTime`;
""");
addAction("""
addAction(
"""
ALTER TABLE `right`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `createdAt` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -70,7 +74,8 @@ public class Migration20231126 extends MigrationSqlStep {
CHANGE `value` `value` varchar(1024) COLLATE 'utf8mb4_0900_ai_ci' NOT NULL COMMENT 'Value of the right' AFTER `rightDescriptionId`;
""");
addAction("""
addAction(
"""
ALTER TABLE `rightDescription`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `createdAt` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -84,7 +89,8 @@ public class Migration20231126 extends MigrationSqlStep {
CHANGE `type` `type` varchar(16) COLLATE 'utf8mb4_0900_ai_ci' NOT NULL DEFAULT 'BOOLEAN' COMMENT 'Type of the property' AFTER `defaultValue`;
""");
addAction("""
addAction(
"""
ALTER TABLE `settings`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `createdAt` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -96,7 +102,8 @@ public class Migration20231126 extends MigrationSqlStep {
CHANGE `value` `value` text COLLATE 'utf8mb3_general_ci' NOT NULL COMMENT 'Value of the configuration' AFTER `type`;
""");
addAction("""
addAction(
"""
ALTER TABLE `user`
CHANGE `id` `id` bigint NOT NULL COMMENT 'Primary key of the base' AUTO_INCREMENT FIRST,
CHANGE `createdAt` `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' AFTER `id`,
@ -124,7 +131,8 @@ public class Migration20231126 extends MigrationSqlStep {
ADD FOREIGN KEY (`object1id`) REFERENCES `user` (`id`);
""");
addAction("""
addAction(
"""
CREATE TABLE `user_link_cover` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'Primary key of the base' ,
`createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Create time of the object' ,

View File

@ -0,0 +1,12 @@
package org.kar.karso.model;
public class AddUserData {
public Long userId;
public AddUserData() {}
public AddUserData(final long userId) {
this.userId = userId;
}
}

View File

@ -49,7 +49,8 @@ public class Application extends GenericDataSoftDelete {
@Override
public String toString() {
return "Application{" + "id=" + this.id + ", description='" + this.description + '\'' + ", redirect='" + this.redirect + '\'' + ", redirectDev='" + this.redirectDev + '\'' + ", notification='"
return "Application{" + "id=" + this.id + ", description='" + this.description + '\'' + ", redirect='"
+ this.redirect + '\'' + ", redirectDev='" + this.redirectDev + '\'' + ", notification='"
+ this.notification + '\'' + ", ttl='" + this.ttl + '\'' + '}';
}
}

View File

@ -0,0 +1,16 @@
package org.kar.karso.model;
public class ClientToken {
public String url;
public String jwt;
public ClientToken() {
}
public ClientToken(final String url, final String jwt) {
this.url = url;
this.jwt = jwt;
}
}

View File

@ -0,0 +1,14 @@
package org.kar.karso.model;
public class CreateTokenRequest {
public CreateTokenRequest() {}
public CreateTokenRequest(final String name, final Integer validity) {
this.name = name;
this.validity = validity;
}
public String name;
public Integer validity;
}

View File

@ -33,11 +33,20 @@ public record DataGetToken(
return generatedPassword;
}
public static DataGetToken generate(final String login, final String method, final String time, final String password) {
public static DataGetToken generate(
final String login,
final String method,
final String time,
final String password) {
return generateSha(login, method, time, sha512(password));
}
public static DataGetToken generateSha(final String login, final String method, final String time, final String password) {
return new DataGetToken(login, method, time, sha512("login='" + login + "';pass='" + password + "';date='" + time + "'"));
public static DataGetToken generateSha(
final String login,
final String method,
final String time,
final String password) {
return new DataGetToken(login, method, time,
sha512("login='" + login + "';pass='" + password + "';date='" + time + "'"));
}
}

View File

@ -33,7 +33,8 @@ public class Settings extends GenericDataSoftDelete {
@Override
public String toString() {
return "Settings [key=" + this.key + ", value=" + this.value + ", id=" + this.id + ", deleted=" + this.deleted + "]";
return "Settings [key=" + this.key + ", value=" + this.value + ", id=" + this.id + ", deleted=" + this.deleted
+ "]";
}
}

View File

@ -13,6 +13,7 @@ public class ConfigVariable {
}
return frontFolder;
}
public static String getUUIDKeyRoot() {
return uuid_for_key_generation;
}

View File

@ -12,11 +12,13 @@ class StepwiseExtension implements ExecutionCondition, TestExecutionExceptionHan
final ExtensionContext.Store store = storeFor(extensionContext, namespace);
final String value = store.get(StepwiseExtension.class, String.class);
return value == null ? ConditionEvaluationResult.enabled("No test failures in stepwise tests")
: ConditionEvaluationResult.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value));
: ConditionEvaluationResult
.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value));
}
@Override
public void handleTestExecutionException(final ExtensionContext extensionContext, final Throwable throwable) throws Throwable {
public void handleTestExecutionException(final ExtensionContext extensionContext, final Throwable throwable)
throws Throwable {
final ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
final ExtensionContext.Store store = storeFor(extensionContext, namespace);
store.put(StepwiseExtension.class, extensionContext.getDisplayName());
@ -27,7 +29,9 @@ class StepwiseExtension implements ExecutionCondition, TestExecutionExceptionHan
return ExtensionContext.Namespace.create(StepwiseExtension.class, extensionContext.getParent());
}
private ExtensionContext.Store storeFor(final ExtensionContext extensionContext, final ExtensionContext.Namespace namespace) {
private ExtensionContext.Store storeFor(
final ExtensionContext extensionContext,
final ExtensionContext.Namespace namespace) {
return extensionContext.getParent().get().getStore(namespace);
}
}

View File

@ -32,8 +32,9 @@ public class TestBase {
public void login(final String login, final String password) {
try {
final GetToken token = api.post(GetToken.class, "users/get_token", DataGetToken.generate(login, "v1", "202515252", password));
api.setToken(token.jwt());
final GetToken token = api.post(GetToken.class, "users/get_token",
DataGetToken.generate(login, "v1", "202515252", password));
api.setToken(token.jwt);
} catch (final Exception ex) {
Assertions.fail("Can not get Authentication for '" + login + "' ==> " + ex.getMessage());
}
@ -74,10 +75,11 @@ public class TestBase {
@Order(3)
@Test
public void firstUserConnect() throws Exception {
final GetToken result = api.post(GetToken.class, "users/get_token", DataGetToken.generate("karadmin", "v1", "202515252", "adminA@666"));
final String[] splitted = result.jwt().split("\\.");
final GetToken result = api.post(GetToken.class, "users/get_token",
DataGetToken.generate("karadmin", "v1", "202515252", "adminA@666"));
final String[] splitted = result.jwt.split("\\.");
Assertions.assertEquals(3, splitted.length);
final String authorization = result.jwt();
final String authorization = result.jwt;
LOGGER.debug(" validate token : " + authorization);
// Note with local access we get the internal key of the system.
final JWTClaimsSet ret = JWTWrapper.validateToken(authorization, "KarAuth", null);

View File

@ -27,8 +27,9 @@ public class TestUnAuthorizedAPI {
public void login(final String login, final String password) {
try {
final GetToken token = api.post(GetToken.class, "users/get_token", DataGetToken.generate(login, "v1", "202515252", password));
api.setToken(token.jwt());
final GetToken token = api.post(GetToken.class, "users/get_token",
DataGetToken.generate(login, "v1", "202515252", password));
api.setToken(token.jwt);
} catch (final Exception ex) {
Assertions.fail("Can not get Authentication for '" + login + "' ==> " + ex.getMessage());
}