[DEV] update get tocken

This commit is contained in:
Edouard DUPIN 2023-11-23 21:53:37 +01:00
parent a135ff746d
commit caa3ccba33
3 changed files with 67 additions and 65 deletions

View File

@ -88,7 +88,7 @@ public class WebLauncher {
WebLauncher.LOGGER.info("Add migration since last version"); WebLauncher.LOGGER.info("Add migration since last version");
// NOTHING for now // NOTHING for now
WebLauncher.LOGGER.info("Migrate the DB [START]"); WebLauncher.LOGGER.info("Migrate the DB [START]");
migrationEngine.migrate(GlobalConfiguration.dbConfig); migrationEngine.migrateErrorThrow(GlobalConfiguration.dbConfig);
WebLauncher.LOGGER.info("Migrate the DB [STOP]"); WebLauncher.LOGGER.info("Migrate the DB [STOP]");
} }

View File

@ -50,26 +50,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")
@ -77,7 +77,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")
@ -91,14 +91,14 @@ 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 @PUT
@Path("{userId}/application/{applicationId}/rights") @Path("{userId}/application/{applicationId}/rights")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@ -108,7 +108,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")
@ -122,7 +122,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")
@ -135,7 +135,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")
@ -146,17 +146,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 QueryCondition("login", "=", user.login)); List<UserAuth> out = DataAccess.getsWhere(UserAuth.class, new QueryCondition("login", "=", user.login));
if (out.size() >= 1) { if (out.size() >= 1) {
@ -167,7 +167,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;
@ -182,7 +182,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")
@ -192,7 +192,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")
@ -200,7 +200,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...");
} }
@ -216,24 +216,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
@ -245,7 +245,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")
@ -258,7 +258,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)) {
@ -277,7 +277,7 @@ public class UserResource {
query = "email"; query = "email";
} }
final UserAuth user = DataAccess.getWhere(UserAuth.class, new QueryCondition(query, "=", login)); final UserAuth user = DataAccess.getWhere(UserAuth.class, 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 + "')");
} }
@ -292,7 +292,7 @@ public class UserResource {
} }
return user; return user;
} }
@POST @POST
@Path("/get_token") @Path("/get_token")
@PermitAll @PermitAll
@ -303,7 +303,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")) {
@ -317,16 +317,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) {
@ -334,7 +334,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");
@ -345,5 +345,5 @@ public class UserResource {
} }
return null; return null;
} }
} }

View File

@ -4,38 +4,40 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
public record DataGetToken(String login, public record DataGetToken(
String method, String login,
String time, String method,
String password String time,
) { String password) {
/*public DataGetToken(String login, String method, /*public DataGetToken(String login, String method,
String time, String time,
String password) { String password) {
this(login, method, time, password); this(login, method, time, password);
}*/ }*/
public static String sha512(final String passwordToHash) { //, String salt){
String generatedPassword = null;
try {
final MessageDigest md = MessageDigest.getInstance("SHA-512");
//md.update(salt.getBytes(StandardCharsets.UTF_8));
final byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
final StringBuilder sb = new StringBuilder();
for (final byte element : bytes) {
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1));
}
generatedPassword = sb.toString();
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
return generatedPassword;
}
public static String sha512(String passwordToHash) { //, String salt){ public static DataGetToken generate(final String login, final String method, final String time, final String password) {
String generatedPassword = null; return generateSha(login, method, time, sha512(password));
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
//md.update(salt.getBytes(StandardCharsets.UTF_8));
byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++){
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
generatedPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return generatedPassword;
} }
public static DataGetToken generate(String login, String method, String time, 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(String login, String method, String time, String password) {
return new DataGetToken(login, method , time , sha512("login='" + login + "';pass='" + password + "';date='" + time + "'"));
} }
} }