From 14c6db21b17662af46df46244d1db6c7389e3cf7 Mon Sep 17 00:00:00 2001 From: igor Date: Tue, 11 Mar 2025 07:32:27 +0500 Subject: [PATCH] + --- Dockerfile | 14 + Jenkinsfile | 55 ++++ .../java/org/ccalm/jwt/MainController.java | 248 +++++++++--------- src/main/java/org/ccalm/jwt/Translation.java | 50 ++-- 4 files changed, 220 insertions(+), 147 deletions(-) create mode 100644 Dockerfile create mode 100644 Jenkinsfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ffc3f31 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +# Используем базовый образ OpenJDK 21 (Debian Slim) +FROM openjdk:21-jdk-slim + +# Устанавливаем рабочую директорию в контейнере +WORKDIR /app + +# Копируем JAR-файл в контейнер +COPY target/*.jar app.jar + +# Копируем файл конфигурации +COPY config.yml config.yml + +# Указываем команду запуска приложения +CMD ["java", "-jar", "app.jar", "--spring.config.location=file:config.yml", "--spring.profiles.active=prod"] diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..77bbe1e --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,55 @@ +pipeline { + agent any + + environment { + APP_NAME = "kz_istransit_jwt" + IMAGE_NAME = "myrepo/kz_istransit_jwt" + DOCKER_REGISTRY = "my-docker-registry.com" // Укажите свой Docker Registry + } + + stages { + stage('Checkout') { + steps { + git branch: 'main', url: 'git@github.com:your-repo.git' + } + } + + stage('Build JAR') { + steps { + script { + sh './mvnw clean package -DskipTests' + } + } + } + + stage('Build Docker Image') { + steps { + script { + sh "docker build -t ${IMAGE_NAME}:latest ." + } + } + } + + stage('Push to Registry') { + steps { + withDockerRegistry([credentialsId: 'docker-hub-credentials', url: "https://${DOCKER_REGISTRY}"]) { + sh "docker tag ${IMAGE_NAME}:latest ${DOCKER_REGISTRY}/${IMAGE_NAME}:latest" + sh "docker push ${DOCKER_REGISTRY}/${IMAGE_NAME}:latest" + } + } + } + + stage('Deploy') { + steps { + sshagent(['ssh-server-credentials']) { + sh """ + ssh user@remote-server "docker pull ${DOCKER_REGISTRY}/${IMAGE_NAME}:latest && + docker stop ${APP_NAME} || true && + docker rm ${APP_NAME} || true && + docker run -d --name ${APP_NAME} -p 8080:8080 -v /opt/kz_istransit_jwt/config.yml:/app/config.yml ${DOCKER_REGISTRY}/${IMAGE_NAME}:latest" + """ + } + } + } + } +} diff --git a/src/main/java/org/ccalm/jwt/MainController.java b/src/main/java/org/ccalm/jwt/MainController.java index a750303..2c9124c 100644 --- a/src/main/java/org/ccalm/jwt/MainController.java +++ b/src/main/java/org/ccalm/jwt/MainController.java @@ -326,7 +326,7 @@ public class MainController implements ServletContextAware { try{ if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { - throw new CustomException(10000, trt.trt("Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); } Jws claims = null; try { @@ -335,7 +335,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, trt.trt("Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); } String sql = """ select @@ -360,7 +360,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - return new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), (String)null, uuid); + return new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } } //------------------------------------------------------------------------------------------------------------------ @@ -372,7 +372,7 @@ public class MainController implements ServletContextAware { try{ if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { - throw new CustomException(10000, trt.trt("Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); } //Проверяю подпись токена Jws claims = null; @@ -382,7 +382,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); + throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null); } //TODO проверить доступ для выполнения данной функции //Выполняем функцию @@ -428,7 +428,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, e); - return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } } //------------------------------------------------------------------------------------------------------------------ @@ -465,7 +465,7 @@ public class MainController implements ServletContextAware { Translation trt = new Translation(language_id, jdbcTemplate); try { if (jwt_a.isEmpty() || countOccurrences(jwt_a, '.') != 2) { - return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Please_log_in"), null, null), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Please_log_in"), null, null), HttpStatus.INTERNAL_SERVER_ERROR); } Jws claims; @@ -475,7 +475,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - return new ResponseEntity<>(new ErrorResponseModel(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")), null, null), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new ErrorResponseModel(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")), null, null), HttpStatus.INTERNAL_SERVER_ERROR); } String sql = """ @@ -507,7 +507,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, e); - return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } } //------------------------------------------------------------------------------------------------------------------ @@ -548,7 +548,7 @@ public class MainController implements ServletContextAware { } catch (IOException e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - throw new CustomException(10000, trt.trt("Input_output_error"),uuid); + throw new CustomException(10000, trt.trt(false, "Input_output_error"),uuid); } //Формирую JSON токена и шифрую его @@ -566,7 +566,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid); + json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } return json.toString(); } @@ -582,19 +582,19 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(newUserModel.getName().length()<3) { - throw new CustomException(10000, trt.trt("The_name_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_name_field_is_empty"),null); } if(newUserModel.getEmail().length()<6) { - throw new CustomException(10000, trt.trt("The_email_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_email_field_is_empty"),null); } if (!Tools.isValidEmail(newUserModel.getEmail())) { - throw new CustomException(10000, trt.trt("The_email_field_is_incorrect"),null); + throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null); } if(newUserModel.getCode().length()<3) { - throw new CustomException(10000, trt.trt("The_code_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_code_field_is_empty"),null); } if(newUserModel.getToken().length()<3) { - throw new CustomException(10000, trt.trt("The_token_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_token_field_is_empty"),null); } //Проверяю что подпись одинакова @@ -603,7 +603,7 @@ public class MainController implements ServletContextAware { String signature2 = Tools.generateSignature(captchaKey, payload); if (!signature1.equals(signature2)) { - throw new CustomException(10000, trt.trt("The_signature_did_not_match"),null); + throw new CustomException(10000, trt.trt(false, "The_signature_did_not_match"),null); } //Расшифровываю String sToken = Tools.decryptText(captchaKey,payload); @@ -616,19 +616,19 @@ public class MainController implements ServletContextAware { } if(jToken==null) { - throw new CustomException(10000, trt.trt("Please_send_a_valid_JSON_string_in_your_token"),null); + throw new CustomException(10000, trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"),null); } if (!newUserModel.getCode().equals(jToken.getString("code"))) { - throw new CustomException(10000, trt.trt("The_code_did_not_match_what_was_specified_in_the_captcha"),null); + throw new CustomException(10000, trt.trt(false, "The_code_did_not_match_what_was_specified_in_the_captcha"),null); } if (jToken.getLong("exp") < (System.currentTimeMillis() / 1000L)) { - throw new CustomException(10000, trt.trt("Captcha_is_outdated"),null); + throw new CustomException(10000, trt.trt(false, "Captcha_is_outdated"),null); } if (!Tools.isValidEmail(jToken.getString("email"))) { - throw new CustomException(10000, trt.trt("The_email_field_is_incorrect"),null); + throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null); } if (!newUserModel.getEmail().equals(jToken.getString("email"))) { - throw new CustomException(10000, trt.trt("The_email_did_not_match_what_was_specified_in_the_captcha"),null); + throw new CustomException(10000, trt.trt(false, "The_email_did_not_match_what_was_specified_in_the_captcha"),null); } //Проверяю существование пользователя с таким email @@ -639,7 +639,7 @@ public class MainController implements ServletContextAware { parameters.addValue("email", newUserModel.getEmail()); List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); for (int i = 0; i < ret.size(); i++) { - throw new CustomException(10000, trt.trt("A_user_with_the_same_email_address_already_exists"),null); + throw new CustomException(10000, trt.trt(false, "A_user_with_the_same_email_address_already_exists"),null); } // Генерируем временный пароль @@ -684,26 +684,26 @@ public class MainController implements ServletContextAware { //Отправляю пароль на почту с ссылкой на активацию этого пользователя String html=""; - html += "" + trt.trt("Now_user") + ""; - html += "

" + trt.trt("To_activate_the_user_please_log_in") + ":

"; + html += "" + trt.trt(true,"Now_user") + ""; + html += "

" + trt.trt(true, "To_activate_the_user_please_log_in") + ":

"; html += "istransit.kz

"; - html += trt.trt("To_log_in_please_use_the_following_password") + ": \"" + password + "\""; + html += trt.trt(true, "To_log_in_please_use_the_following_password") + ": \"" + password + "\""; html += ""; try { - EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, newUserModel.getEmail(), trt.trt("Password"), html); + EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, newUserModel.getEmail(), trt.trt(true,"Password"), html); } catch (MessagingException e) { - throw new CustomException(10000, String.format(trt.trt("Failed_send_mail_to_s"), newUserModel.getEmail()),null); + throw new CustomException(10000, String.format(trt.trt(false, "Failed_send_mail_to_s"), newUserModel.getEmail()),null); } - json.put("error_message",trt.trt("The_authorization_password_has_been_sent_to_your_email_address")); + json.put("error_message",trt.trt(false, "The_authorization_password_has_been_sent_to_your_email_address")); } catch (CustomException e) { json = e.getJson(); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid); + json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } return json.toString(); } @@ -720,7 +720,7 @@ public class MainController implements ServletContextAware { if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { - throw new CustomException(10000, trt.trt("Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); } //Проверяю подпись токена Jws claims = null; @@ -730,7 +730,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); + throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null); } //Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине) @@ -746,15 +746,15 @@ public class MainController implements ServletContextAware { } catch (Exception ex) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, ex); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"), uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"), uuid); } if (json == null) { - throw new CustomException(10000, trt.trt("Invalid_username_and_or_password"), null); + throw new CustomException(10000, trt.trt(false, "Invalid_username_and_or_password"), null); } else { if (json.has("block")) { if (!json.isNull("block") && json.getBoolean("block")) - throw new CustomException(10006, trt.trt("The_user_account_is_blocked"), null); + throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), null); json.remove("block"); } @@ -770,7 +770,7 @@ public class MainController implements ServletContextAware { catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid); + json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } finally { //try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } @@ -789,15 +789,15 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(loginModel.getLogin().isEmpty()) - throw new CustomException(10000,trt.trt("The_login_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null); if(!Tools.isValidEmail(loginModel.getLogin())) - throw new CustomException(10000,trt.trt("The_login_field_is_incorrect"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null); if(loginModel.getPassword().isEmpty()) - throw new CustomException(10000,trt.trt("The_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null); if(loginModel.getPassword().length()<=3) - throw new CustomException(10000,trt.trt("The_password_field_is_short"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null); if(loginModel.getAppid().isEmpty()) - throw new CustomException(10000,trt.trt("The_application_name_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null); String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания if (ipAddress == null) { @@ -825,9 +825,9 @@ public class MainController implements ServletContextAware { if (!json.has("result") || json.getBoolean("result")) { if(json.getInt("count")==0) { - throw new CustomException(10000, trt.trt("The_user_account_is_blocked"),null); + throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null); }else{ - throw new CustomException(10000, trt.trt("The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), String.valueOf(json.getInt("limit_duration")),(String)null); + throw new CustomException(10000, trt.trt(false, "The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), String.valueOf(json.getInt("limit_duration")),(String)null); } } if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) { @@ -839,7 +839,7 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error("Функция main.user_is_blocked не вернула результата!", uuid, ex); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); }*/ @@ -866,19 +866,19 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt("Internal_Server_Error"),uuid); + throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid); } if(json==null) { - String msg = trt.trt("Invalid_username_and_or_password"); + String msg = trt.trt(false, "Invalid_username_and_or_password"); if(attempt_count>0){ - msg = msg + " " + String.format(trt.trt("Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit); + msg = msg + " " + String.format(trt.trt(false, "Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit); } throw new CustomException(10000, msg, null); } if (json.has("block")) { if (json.getBoolean("block")) { - throw new CustomException(10006, trt.trt("The_user_account_is_blocked"), (String)null); + throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), (String)null); } json.remove("block"); @@ -886,11 +886,11 @@ public class MainController implements ServletContextAware { long currentTime = System.currentTimeMillis() / 1000L; if (json.has("expiration") && json.getLong("expiration") < currentTime) { - throw new CustomException(10009, trt.trt("Password_expired_and_must_be_changed"), (String)null); + throw new CustomException(10009, trt.trt(false, "Password_expired_and_must_be_changed"), (String)null); } if (json.has("totp_required") && !json.isNull("totp_required") && json.getBoolean("totp_required") && json.has("totp_key") && json.isNull("totp_key")) { - throw new CustomException(10010, trt.trt("You_need_to_get_a_new_TOTP_key"), (String)null); + throw new CustomException(10010, trt.trt(false, "You_need_to_get_a_new_TOTP_key"), (String)null); } ArrayList errorMessages; @@ -898,10 +898,10 @@ public class MainController implements ServletContextAware { if (json.has("totp_required") && !json.isNull("totp_required") && json.getBoolean("totp_required") && !Tools.isInteger(loginModel.getTotp())) { errorMessages = new ArrayList(); errorSettings = new ArrayList(); - errorMessages.add(trt.trt("The_TOTP_field_is_empty")); + errorMessages.add(trt.trt(false, "The_TOTP_field_is_empty")); errorSettings.add(""); if (attempt_count > 1) { - errorMessages.add(trt.trt("Authorization_attempts_s_out_of_s")); + errorMessages.add(trt.trt(false, "Authorization_attempts_s_out_of_s")); String str = String.valueOf(attempt_count); errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";"); } @@ -912,10 +912,10 @@ public class MainController implements ServletContextAware { if (json.has("totp_success") && !json.getBoolean("totp_success")) { errorMessages = new ArrayList(); errorSettings = new ArrayList(); - errorMessages.add(trt.trt("Please_send_the_correct_TOTP_code")); + errorMessages.add(trt.trt(false, "Please_send_the_correct_TOTP_code")); errorSettings.add(""); if (attempt_count > 1) { - errorMessages.add(trt.trt("Authorization_attempts_s_out_of_s")); + errorMessages.add(trt.trt(false, "Authorization_attempts_s_out_of_s")); String str = String.valueOf(attempt_count); errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";"); } @@ -948,7 +948,7 @@ public class MainController implements ServletContextAware { }catch (Exception ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); } //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256"); @@ -1047,7 +1047,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid); + json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } finally { //try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } @@ -1069,9 +1069,9 @@ public class MainController implements ServletContextAware { if (!json.has("result") || json.getBoolean("result")) { if(json.getInt("count")==0) { - throw new CustomException(10000, trt.trt("The_user_account_is_blocked"),null); + throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null); }else{ - throw new CustomException(10000, java.lang.String.format(trt.trt("The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), json.getInt("limit_duration")),null); + throw new CustomException(10000, java.lang.String.format(trt.trt(false, "The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), json.getInt("limit_duration")),null); } } if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) { @@ -1083,11 +1083,11 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ java.lang.String uuid = UUID.randomUUID().toString(); logger.error(uuid, ex); - throw new CustomException(10000, trt.trt("Internal_Server_Error"),uuid); + throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid); }catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - throw new CustomException(10000, trt.trt("Internal_Server_Error"),uuid); + throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid); } Map result = new HashMap<>(); @@ -1107,15 +1107,15 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(loginModel.getLogin().isEmpty()) - throw new CustomException(10000,trt.trt("The_login_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null); if(!Tools.isValidEmail(loginModel.getLogin())) - throw new CustomException(10000,trt.trt("The_login_field_is_incorrect"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null); if(loginModel.getPassword().isEmpty()) - throw new CustomException(10000,trt.trt("The_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null); if(loginModel.getPassword().length()<=3) - throw new CustomException(10000,trt.trt("The_password_field_is_short"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null); if(loginModel.getAppid().isEmpty()) - throw new CustomException(10000,trt.trt("The_application_name_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null); String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания if (ipAddress == null) { @@ -1143,9 +1143,9 @@ public class MainController implements ServletContextAware { if (!json.has("result") || json.getBoolean("result")) { if(json.getInt("count")==0) { - throw new CustomException(10000, trt.trt("The_user_account_is_blocked"),null); + throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null); }else{ - throw new CustomException(10000, trt.trt("The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), String.valueOf(json.getInt("limit_duration")),(String)null); + throw new CustomException(10000, trt.trt(false, "The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), String.valueOf(json.getInt("limit_duration")),(String)null); } } if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) { @@ -1157,7 +1157,7 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error("Error executing SQL query", uuid, ex); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); }*/ String sql = ""; @@ -1181,19 +1181,19 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); } if(json==null) { - String msg = trt.trt("Invalid_username_and_or_password"); + String msg = trt.trt(false, "Invalid_username_and_or_password"); if(attempt_count>0){ - msg = msg + " " + String.format(trt.trt("Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit); + msg = msg + " " + String.format(trt.trt(false, "Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit); } throw new CustomException(10000, msg, null); } if(json.has("block")) { if(json.getBoolean("block")) - throw new CustomException(10006,trt.trt("The_user_account_is_blocked"),null); + throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"),null); json.remove("block"); } @@ -1202,13 +1202,13 @@ public class MainController implements ServletContextAware { if(!json.isNull("secret")) { if(!Tools.isInteger(loginModel.getTotp())) - throw new CustomException(10000,trt.trt("The_TOTP_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_TOTP_field_is_empty"),null); //Проверяю на соответствие TOTP ключа TODO потом написать поверку в функции p__Login плагином GoogleAuthenticator gAuth = new GoogleAuthenticator(); boolean isCodeValid = gAuth.authorize(json.getString("secret"), Integer.valueOf(loginModel.getTotp())); if(!isCodeValid){ - throw new CustomException(10000, trt.trt("TOTP_key_does_not_match"), null); + throw new CustomException(10000, trt.trt(false, "TOTP_key_does_not_match"), null); } } json.remove("secret"); @@ -1229,7 +1229,7 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); } // Создание OTP URL @@ -1249,7 +1249,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid); + json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } finally { //try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } @@ -1278,7 +1278,7 @@ public class MainController implements ServletContextAware { if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2 || jwt_r.isEmpty() || countOccurrences(jwt_r, '.')!=2 ) { logout(response,request); - throw new CustomException(10000, trt.trt("Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); } //Разбираю токен без проверки, чтобы выбрать email @@ -1300,7 +1300,7 @@ public class MainController implements ServletContextAware { .parseClaimsJws(jwt_r); } catch (Exception e) { logout(response,request); - throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); + throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null); } //Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления @@ -1308,13 +1308,13 @@ public class MainController implements ServletContextAware { String token_ar_sig = token.getBody().get("sig", String.class); //Она же но уже в токене обновления if(token_aa_sig==null || !token_aa_sig.equals(token_ar_sig)){ logout(response,request); //Удаляю куки чтобы эмулировать выход из приложения - return createStrJSONError(10000,trt.trt("Attempt_to_substitution_tokens"),(String)null,(String)null); + return createStrJSONError(10000,trt.trt(false, "Attempt_to_substitution_tokens"),(String)null,(String)null); } //TODO проверить не заблокирован ли пользователь //if(json.has("block")) { // if(json.getBoolean("block")) - // throw new CustomException(10006,trt.trt("The_user_account_is_blocked"),null); + // throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"),null); // json.remove("block"); //} @@ -1356,7 +1356,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid); + json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); } finally { } @@ -1368,29 +1368,29 @@ public class MainController implements ServletContextAware { public String reset(@RequestParam(required=false,name="token",defaultValue = "") String token,@RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - String result=createHTMLError(1,trt.trt("Request_not_processed")); + String result=createHTMLError(1,trt.trt(false, "Request_not_processed")); try { int index = token.indexOf("."); if (index < 0) - return createHTMLError(10000, trt.trt("Please_send_a_valid_token")); + return createHTMLError(10000, trt.trt(false, "Please_send_a_valid_token")); String payload = token.substring(0, index); String signature1 = token.substring(index + 1); String signature2 = Tools.generateSignature(captchaKey, payload); if (!signature1.equals(signature2)) { - return createHTMLError(1, trt.trt("The_signature_did_not_match")); + return createHTMLError(1, trt.trt(false, "The_signature_did_not_match")); } //расшифровываю JSONObject jToken = new JSONObject(Tools.decryptText(captchaKey, payload)); if (jToken == null) - return createHTMLError(10000, trt.trt("Please_send_a_valid_JSON_string_in_your_token")); + return createHTMLError(10000, trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token")); if (jToken.getLong("exp") < Instant.now().getEpochSecond()) { - return createHTMLError(10000, trt.trt("Captcha_is_outdated")); + return createHTMLError(10000, trt.trt(false, "Captcha_is_outdated")); } if (!Tools.isValidEmail(jToken.getString("email"))) { - return createHTMLError(10000, trt.trt("The_email_field_is_incorrect")); + return createHTMLError(10000, trt.trt(false, "The_email_field_is_incorrect")); } //Проверяю на то что не нажали много раз на востановление пароля @@ -1404,7 +1404,7 @@ public class MainController implements ServletContextAware { id = (new JSONObject(ret.get(i))).getLong("id"); } if (id == 0) - return createHTMLError(10000, trt.trt("The_password_update_request_has_expired")); + return createHTMLError(10000, trt.trt(false, "The_password_update_request_has_expired")); //Теперь обновляем пароль в базе sql = "update main._users set password=crypt(password_new, gen_salt('bf')),password_new = null,expiration='1970-01-01' where password_new is not null and email=:email"; @@ -1414,9 +1414,9 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - return createHTMLError(10000,trt.trt("Internal_Server_Error")); + return createHTMLError(10000,trt.trt(false, "Internal_Server_Error")); } - return createHTMLError(0,trt.trt("The_password_has_been_changed_and_you_will_be_redirected_to_the_main_page")); + return createHTMLError(0,trt.trt(false, "The_password_has_been_changed_and_you_have_been_redirected_to_the_main_page")); } //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/restore",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @@ -1424,7 +1424,7 @@ public class MainController implements ServletContextAware { public String restore(Model model, @RequestBody RestoreModel restore, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - String result=createStrJSONError(10000,trt.trt("Request_not_processed"), (String)null, (String)null); + String result=createStrJSONError(10000,trt.trt(false, "Request_not_processed"), (String)null, (String)null); try{ int index = restore.getToken().indexOf("."); String payload = restore.getToken().substring(0, index); @@ -1436,7 +1436,7 @@ public class MainController implements ServletContextAware { String signature2 = Tools.generateSignature(captchaKey,payload); if(! signature1.equals(signature2)) { - result=createStrJSONError(10000,trt.trt("The_signature_did_not_match"), (String)null, (String)null); + result=createStrJSONError(10000,trt.trt(false, "The_signature_did_not_match"), (String)null, (String)null); } System.out.println("signature2: " + signature2); @@ -1445,16 +1445,16 @@ public class MainController implements ServletContextAware { JSONObject token = new JSONObject(Tools.decryptText(captchaKey,payload)); if(token==null) - return createStrJSONError(10000,trt.trt("Please_send_a_valid_JSON_string_in_your_token"), (String)null,(String)null); + return createStrJSONError(10000,trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"), (String)null,(String)null); if(!restore.getCode().equals(token.getString("code"))){ - return createStrJSONError(10000,trt.trt("The_code_did_not_match"),(String)null,(String)null); + return createStrJSONError(10000,trt.trt(false, "The_code_did_not_match"),(String)null,(String)null); } if(token.getLong("exp")"; - html += "

"+trt.trt("To_reset_your_password_click_on_the_link")+":

"; - html += ""+trt.trt("Reset_the_password")+"

"; - html += trt.trt("After_clicking_on_the_link_the_new_password_will_be")+": \"" + password_new + "\""; + String html = ""+trt.trt(true,"Password_recovery")+""; + html += "

"+trt.trt(true,"To_reset_your_password_click_on_the_link")+":

"; + html += ""+trt.trt(true,"Reset_the_password")+"

"; + html += trt.trt(true,"After_clicking_on_the_link_the_new_password_will_be")+": \"" + password_new + "\""; html += ""; try { - EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, token.getString("email"), trt.trt("Password_recovery"), html); + EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, token.getString("email"), trt.trt(true,"Password_recovery"), html); } catch (Exception ex) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, ex); - return createStrJSONError(10000,trt.trt("Failed_send_mail_to_s"), token.getString("email"),uuid); + return createStrJSONError(10000,trt.trt(false,"Failed_send_mail_to_s"), token.getString("email"),uuid); } } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - return createStrJSONError(10000,trt.trt("Internal_Server_Error"), (String)null,uuid); + return createStrJSONError(10000,trt.trt(false,"Internal_Server_Error"), (String)null,uuid); } - return createStrJSONError(0, trt.trt("A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null); + return createStrJSONError(0, trt.trt(false,"A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null); } //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/update",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @@ -1527,26 +1527,26 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(update==null) - throw new CustomException(10000,trt.trt("Please_send_a_valid_JSON_string_in_your_request"),null); + throw new CustomException(10000,trt.trt(false,"Please_send_a_valid_JSON_string_in_your_request"),null); if(update.getLogin().isEmpty()) - throw new CustomException(10000,trt.trt("The_login_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false,"The_login_field_is_empty"),null); if (!Tools.isValidEmail(update.getLogin())) - throw new CustomException(10000, trt.trt("The_email_field_is_incorrect"),null); + throw new CustomException(10000, trt.trt(false,"The_email_field_is_incorrect"),null); if(update.getPassword().isEmpty()) - throw new CustomException(10000,trt.trt("The_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false,"The_password_field_is_empty"),null); if(update.getPasswordNew().isEmpty()) - throw new CustomException(10000,trt.trt("The_new_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false,"The_new_password_field_is_empty"),null); if(!Pattern.compile("[0-9]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt("The_password_is_missing_a_number"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_number"),null); if(!Pattern.compile("[a-z]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt("The_password_is_missing_a_small_Latin_letter"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_small_Latin_letter"),null); if (!Pattern.compile("[A-Z]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt("The_password_is_missing_a_big_Latin_letter"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_big_Latin_letter"),null); if (!Pattern.compile("[_!@#$%^&*]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt("The_password_is_missing_a_special_letter"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_special_letter"),null); if (update.getPasswordNew().length() < 6) - throw new CustomException(10000,trt.trt("The_password_is_less_than_six_characters"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_less_than_six_characters"),null); //Проверяем попытки смены пароля (сохраение попыток в функции логина) String ipAddress = request.getHeader("X-FORWARDED-FOR"); @@ -1569,12 +1569,12 @@ public class MainController implements ServletContextAware { for (int i = 0; i < ret.size(); i++) { rows = new JSONObject(ret.get(i)); if(rows.getBoolean("result")) { - throw new CustomException(10000, String.format(trt.trt("The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), 5),null); + throw new CustomException(10000, String.format(trt.trt(false,"The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), 5),null); } } if(rows==null) { logger.error("Функция main.user_is_blocked не вернула результата!"); - throw new CustomException(10000, trt.trt("Error_executing_SQL_query"),null); + throw new CustomException(10000, trt.trt(false,"Error_executing_SQL_query"),null); }*/ //Получаю id пользователя TODO should work through the authorization function @@ -1588,7 +1588,7 @@ public class MainController implements ServletContextAware { rows = new JSONObject(ret.get(i)); } if(rows==null) - throw new CustomException(10000,trt.trt("Invalid_username_and_or_password"),null); + throw new CustomException(10000,trt.trt(false,"Invalid_username_and_or_password"),null); //Обновляю пароль sql = "update main._users set password=crypt(:password_new, gen_salt('bf')),password_new = null,expiration=now()+INTERVAL '1 year' where password=crypt(:password, password) and email=:email"; @@ -1609,7 +1609,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - return createStrJSONError(10000,trt.trt("Internal_Server_Error"), (String)null,uuid); + return createStrJSONError(10000,trt.trt(false,"Internal_Server_Error"), (String)null,uuid); } finally { } return json.toString(); @@ -1644,7 +1644,7 @@ public class MainController implements ServletContextAware { Translation trt = new Translation(language_id,jdbcTemplate); try { if (authentication == null || !authentication.isAuthenticated()) { - throw new CustomException(10000, Collections.singletonList(trt.trt("Please_log_in")),null); + throw new CustomException(10000, Collections.singletonList(trt.trt(false,"Please_log_in")),null); } UserDetails userDetails = (UserDetails) authentication.getPrincipal(); @@ -1656,9 +1656,9 @@ public class MainController implements ServletContextAware { if (data != null) { logout(response,request); if (data.equals("repeat")) { - throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("Reauthorization_detected_if_it_is_not_you_please_change_your_password")), null); + throw new CustomException(10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"Reauthorization_detected_if_it_is_not_you_please_change_your_password")), null); }else { - throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("Your_authorization_token_is_not_valid")), null); + throw new CustomException(10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"Your_authorization_token_is_not_valid")), null); } } } @@ -1668,7 +1668,7 @@ public class MainController implements ServletContextAware { } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, e); - return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false,"Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } } } \ No newline at end of file diff --git a/src/main/java/org/ccalm/jwt/Translation.java b/src/main/java/org/ccalm/jwt/Translation.java index 9e9ef3d..49fb38b 100644 --- a/src/main/java/org/ccalm/jwt/Translation.java +++ b/src/main/java/org/ccalm/jwt/Translation.java @@ -38,29 +38,33 @@ public class Translation { this.jdbcTemplate = jdbcTemplate; } - String trt(String text){ - /*String sql = """ - select - translation - from - main._translations - where - del=false - and language_id=:language_id - and identifier=:identifier; - """; - MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("language_id", language_id); - parameters.addValue("identifier", text); - List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); - int i = 0; - for (i = 0; i < ret.size(); i++) { - JSONObject json = new JSONObject(ret.get(i)); - text = json.getString("translation"); + String trt(boolean translate,String text){ + if(translate) { + String sql = """ + select + translation + from + main._translations + where + del=false + and language_id=:language_id + and identifier=:identifier; + """; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("language_id", language_id); + parameters.addValue("identifier", text); + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); + int i = 0; + for (i = 0; i < ret.size(); i++) { + JSONObject json = new JSONObject(ret.get(i)); + text = json.getString("translation"); + } + if(i==0){ + text = text.replace("_", " "); + } + return text; + }else { + return text; } - if(i==0){ - text = text.replace("_", " "); - }*/ - return text; } }