From 6b3a7327de3b68cc9784319af79a04b08d8851e9 Mon Sep 17 00:00:00 2001 From: Igor I Date: Thu, 3 Apr 2025 09:34:25 +0500 Subject: [PATCH 1/3] =?UTF-8?q?=D0=92=20CustomException=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D0=B5=20saveToLog=20=D1=83=D1=87=D1=91=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + .../java/org/ccalm/jwt/MainController.java | 154 +++++++++--------- .../org/ccalm/jwt/tools/CustomException.java | 2 +- 3 files changed, 81 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 38a3079..2f78ebc 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ ____ 10. [Проверить валидность токена](#проверить-валидность-токена) ____ +### Получить токен для защиты от CSRF атак +https://istransit.kz/api/authorization/v02/get_request_token ### Получить список разрешений для пользователя по Access token https://istransit.kz/api/authorization/v02/access/ diff --git a/src/main/java/org/ccalm/jwt/MainController.java b/src/main/java/org/ccalm/jwt/MainController.java index cc2e8e5..ce0bd51 100644 --- a/src/main/java/org/ccalm/jwt/MainController.java +++ b/src/main/java/org/ccalm/jwt/MainController.java @@ -18,6 +18,7 @@ import net.logicsquad.nanocaptcha.image.ImageCaptcha; import net.logicsquad.nanocaptcha.image.backgrounds.GradiatedBackgroundProducer; import net.logicsquad.nanocaptcha.image.noise.CurvedLineNoiseProducer; import net.logicsquad.nanocaptcha.image.renderer.DefaultWordRenderer; +import org.apache.commons.codec.digest.DigestUtils; import org.json.JSONArray; import org.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; @@ -52,6 +53,7 @@ import javax.mail.MessagingException; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; +import java.security.SecureRandom; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.sql.Date; @@ -367,7 +369,7 @@ public class MainController implements ServletContextAware { try{ if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); } Jws claims = null; try { @@ -376,7 +378,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); } String sql = """ select @@ -413,7 +415,7 @@ public class MainController implements ServletContextAware { try{ if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); } //Проверяю подпись токена Jws claims = null; @@ -423,7 +425,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "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,false); } //TODO проверить доступ для выполнения данной функции //Выполняем функцию @@ -589,7 +591,7 @@ public class MainController implements ServletContextAware { } catch (IOException e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - throw new CustomException(10000, trt.trt(false, "Input_output_error"),uuid); + throw new CustomException(10000, trt.trt(false, "Input_output_error"),uuid,false); } //Формирую JSON токена и шифрую его @@ -623,19 +625,19 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(newUserModel.getName().length()<3) { - throw new CustomException(10000, trt.trt(false, "The_name_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_name_field_is_empty"),null,false); } if(newUserModel.getEmail().length()<6) { - throw new CustomException(10000, trt.trt(false, "The_email_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_email_field_is_empty"),null,false); } if (!Tools.isValidEmail(newUserModel.getEmail())) { - throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null); + throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null,false); } if(newUserModel.getCode().length()<3) { - throw new CustomException(10000, trt.trt(false, "The_code_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_code_field_is_empty"),null,false); } if(newUserModel.getToken().length()<3) { - throw new CustomException(10000, trt.trt(false, "The_token_field_is_empty"),null); + throw new CustomException(10000, trt.trt(false, "The_token_field_is_empty"),null,false); } //Проверяю что подпись одинакова @@ -644,7 +646,7 @@ public class MainController implements ServletContextAware { String signature2 = Tools.generateSignature(captchaKey, payload); if (!signature1.equals(signature2)) { - throw new CustomException(10000, trt.trt(false, "The_signature_did_not_match"),null); + throw new CustomException(10000, trt.trt(false, "The_signature_did_not_match"),null,false); } //Расшифровываю String sToken = Tools.decryptText(captchaKey,payload); @@ -657,19 +659,19 @@ public class MainController implements ServletContextAware { } if(jToken==null) { - throw new CustomException(10000, trt.trt(false, "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,false); } if (!newUserModel.getCode().equals(jToken.getString("code"))) { - throw new CustomException(10000, trt.trt(false, "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,false); } if (jToken.getLong("exp") < (System.currentTimeMillis() / 1000L)) { - throw new CustomException(10000, trt.trt(false, "Captcha_is_outdated"),null); + throw new CustomException(10000, trt.trt(false, "Captcha_is_outdated"),null,false); } if (!Tools.isValidEmail(jToken.getString("email"))) { - throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null); + throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null,false); } if (!newUserModel.getEmail().equals(jToken.getString("email"))) { - throw new CustomException(10000, trt.trt(false, "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,false); } //Проверяю существование пользователя с таким email @@ -680,7 +682,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(false, "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,false); } // Генерируем временный пароль @@ -734,7 +736,7 @@ public class MainController implements ServletContextAware { try { 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(false, "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,false); } json.put("error_message",trt.trt(false, "The_authorization_password_has_been_sent_to_your_email_address")); @@ -761,7 +763,7 @@ public class MainController implements ServletContextAware { if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); } //Проверяю подпись токена Jws claims = null; @@ -771,7 +773,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "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,false); } //Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине) @@ -787,15 +789,15 @@ public class MainController implements ServletContextAware { } catch (Exception ex) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, ex); - throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"), uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"), uuid,false); } if (json == null) { - throw new CustomException(10000, trt.trt(false, "Invalid_username_and_or_password"), null); + throw new CustomException(10000, trt.trt(false, "Invalid_username_and_or_password"), null,false); } else { if (json.has("block")) { if (!json.isNull("block") && json.getBoolean("block")) - throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), null); + throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), null,false); json.remove("block"); } @@ -830,15 +832,15 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(loginModel.getLogin().isEmpty()) - throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null,false); if(!Tools.isValidEmail(loginModel.getLogin())) - throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null,false); if(loginModel.getPassword().isEmpty()) - throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null,false); if(loginModel.getPassword().length()<=3) - throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null,false); if(loginModel.getAppid().isEmpty()) - throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null,false); String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания if (ipAddress == null) { @@ -866,9 +868,9 @@ public class MainController implements ServletContextAware { if (!json.has("result") || json.getBoolean("result")) { if(json.getInt("count")==0) { - throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null); + throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null,false); }else{ - 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); + 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,false); } } if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) { @@ -880,7 +882,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(false, "Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false); }*/ @@ -907,19 +909,19 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid); + throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid,false); } if(json==null) { String msg = trt.trt(false, "Invalid_username_and_or_password"); if(attempt_count>0){ msg = msg + " " + String.format(trt.trt(false, "Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit); } - throw new CustomException(10000, msg, null); + throw new CustomException(10000, msg, null,false); } if (json.has("block")) { if (json.getBoolean("block")) { - throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), (String)null); + throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), (String)null,false); } json.remove("block"); @@ -927,11 +929,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(false, "Password_expired_and_must_be_changed"), (String)null); + throw new CustomException(10009, trt.trt(false, "Password_expired_and_must_be_changed"), (String)null,false); } 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(false, "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,false); } ArrayList errorMessages; @@ -947,7 +949,7 @@ public class MainController implements ServletContextAware { errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";"); } - throw new CustomException(10012, errorMessages, errorSettings, (String)null); + throw new CustomException(10012, errorMessages, errorSettings, (String)null,false); } if (json.has("totp_success") && !json.getBoolean("totp_success")) { @@ -961,7 +963,7 @@ public class MainController implements ServletContextAware { errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";"); } - throw new CustomException(10000, errorMessages, errorSettings, (String)null); + throw new CustomException(10000, errorMessages, errorSettings, (String)null,false); } if (json.has("totp_required")) { @@ -989,7 +991,7 @@ public class MainController implements ServletContextAware { }catch (Exception ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false); } //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256"); @@ -1110,9 +1112,9 @@ public class MainController implements ServletContextAware { if (!json.has("result") || json.getBoolean("result")) { if(json.getInt("count")==0) { - throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null); + throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null,false); }else{ - 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); + 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,false); } } if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) { @@ -1124,11 +1126,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(false, "Internal_Server_Error"),uuid); + throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid,false); }catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid); + throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid,false); } Map result = new HashMap<>(); @@ -1148,15 +1150,15 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(loginModel.getLogin().isEmpty()) - throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null,false); if(!Tools.isValidEmail(loginModel.getLogin())) - throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null); + throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null,false); if(loginModel.getPassword().isEmpty()) - throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null,false); if(loginModel.getPassword().length()<=3) - throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null); + throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null,false); if(loginModel.getAppid().isEmpty()) - throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null,false); String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания if (ipAddress == null) { @@ -1184,9 +1186,9 @@ public class MainController implements ServletContextAware { if (!json.has("result") || json.getBoolean("result")) { if(json.getInt("count")==0) { - throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null); + throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null,false); }else{ - 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); + 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,false); } } if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) { @@ -1198,7 +1200,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(false, "Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false); }*/ String sql = ""; @@ -1222,19 +1224,19 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false); } if(json==null) { String msg = trt.trt(false, "Invalid_username_and_or_password"); if(attempt_count>0){ msg = msg + " " + String.format(trt.trt(false, "Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit); } - throw new CustomException(10000, msg, null); + throw new CustomException(10000, msg, null, false); } if(json.has("block")) { if(json.getBoolean("block")) - throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"),null); + throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"),null, false); json.remove("block"); } @@ -1243,13 +1245,13 @@ public class MainController implements ServletContextAware { if(!json.isNull("secret")) { if(!Tools.isInteger(loginModel.getTotp())) - throw new CustomException(10000,trt.trt(false, "The_TOTP_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false, "The_TOTP_field_is_empty"),null, false); //Проверяю на соответствие 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(false, "TOTP_key_does_not_match"), null); + throw new CustomException(10000, trt.trt(false, "TOTP_key_does_not_match"), null, false); } } json.remove("secret"); @@ -1270,7 +1272,7 @@ public class MainController implements ServletContextAware { }catch (DataAccessException ex){ String uuid = UUID.randomUUID().toString(); logger.error(uuid,ex); - throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid); + throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"), uuid, false); } // Создание OTP URL @@ -1319,7 +1321,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(false, "Please_log_in"),null); + throw new CustomException(10000, trt.trt(false, "Please_log_in"), null, false); } //Разбираю токен без проверки, чтобы выбрать email @@ -1341,7 +1343,7 @@ public class MainController implements ServletContextAware { .parseClaimsJws(jwt_r); } catch (Exception e) { logout(response,request); - throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "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, false); } //Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления @@ -1355,7 +1357,7 @@ public class MainController implements ServletContextAware { //TODO проверить не заблокирован ли пользователь //if(json.has("block")) { // if(json.getBoolean("block")) - // throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"),null); + // throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"), null, false); // json.remove("block"); //} @@ -1568,26 +1570,26 @@ public class MainController implements ServletContextAware { json.put("error_message",""); if(update==null) - throw new CustomException(10000,trt.trt(false,"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, false); if(update.getLogin().isEmpty()) - throw new CustomException(10000,trt.trt(false,"The_login_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false,"The_login_field_is_empty"), null, false); if (!Tools.isValidEmail(update.getLogin())) - throw new CustomException(10000, trt.trt(false,"The_email_field_is_incorrect"),null); + throw new CustomException(10000, trt.trt(false,"The_email_field_is_incorrect"), null, false); if(update.getPassword().isEmpty()) - throw new CustomException(10000,trt.trt(false,"The_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false,"The_password_field_is_empty"), null, false); if(update.getPasswordNew().isEmpty()) - throw new CustomException(10000,trt.trt(false,"The_new_password_field_is_empty"),null); + throw new CustomException(10000,trt.trt(false,"The_new_password_field_is_empty"), null, false); if(!Pattern.compile("[0-9]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_number"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_number"), null, false); if(!Pattern.compile("[a-z]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt(false,"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, false); if (!Pattern.compile("[A-Z]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt(false,"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, false); if (!Pattern.compile("[_!@#$%^&*]").matcher(update.getPasswordNew()).find()) - throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_special_letter"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_special_letter"), null, false); if (update.getPasswordNew().length() < 6) - throw new CustomException(10000,trt.trt(false,"The_password_is_less_than_six_characters"),null); + throw new CustomException(10000,trt.trt(false,"The_password_is_less_than_six_characters"), null, false); //Проверяем попытки смены пароля (сохраение попыток в функции логина) String ipAddress = request.getHeader("X-FORWARDED-FOR"); @@ -1610,12 +1612,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(false,"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, false); } } if(rows==null) { logger.error("Функция main.user_is_blocked не вернула результата!"); - throw new CustomException(10000, trt.trt(false,"Error_executing_SQL_query"),null); + throw new CustomException(10000, trt.trt(false,"Error_executing_SQL_query"),null, false); }*/ //Получаю id пользователя TODO should work through the authorization function @@ -1629,7 +1631,7 @@ public class MainController implements ServletContextAware { rows = new JSONObject(ret.get(i)); } if(rows==null) - throw new CustomException(10000,trt.trt(false,"Invalid_username_and_or_password"),null); + throw new CustomException(10000,trt.trt(false,"Invalid_username_and_or_password"), null, false); //Обновляю пароль 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"; @@ -1685,7 +1687,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(false,"Please_log_in")),null); + throw new CustomException(10000, Collections.singletonList(trt.trt(false,"Please_log_in")), null, false); } UserDetails userDetails = (UserDetails) authentication.getPrincipal(); @@ -1697,9 +1699,9 @@ public class MainController implements ServletContextAware { if (data != null) { logout(response,request); if (data.equals("repeat")) { - 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); + 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, false); }else { - throw new CustomException(10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"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, false); } } } diff --git a/src/main/java/org/ccalm/jwt/tools/CustomException.java b/src/main/java/org/ccalm/jwt/tools/CustomException.java index 2e123db..f8889fa 100644 --- a/src/main/java/org/ccalm/jwt/tools/CustomException.java +++ b/src/main/java/org/ccalm/jwt/tools/CustomException.java @@ -1,4 +1,4 @@ -package org.ccalm.main.utils; +package org.ccalm.jwt.tools; import lombok.Getter; import org.apache.logging.log4j.LogManager; From 117c1e53dfd82da4b8a4da3af0b602630a11e5fc Mon Sep 17 00:00:00 2001 From: Igor I Date: Thu, 3 Apr 2025 10:09:22 +0500 Subject: [PATCH 2/3] Corrected the comments --- README.md | 10 ++++++++++ src/main/java/org/ccalm/jwt/tools/CustomException.java | 1 - 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2f78ebc..a681b5b 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,16 @@ ____ ### Получить токен для защиты от CSRF атак https://istransit.kz/api/authorization/v02/get_request_token +GET запрос без данных. + +Пример ответа: +```json +{ + "ttl":600, + "token":"VTf8zvHKqK7QFJ0ZEyheOYAUrI7cRIbejxMzRKlMzYM" +} +``` + ### Получить список разрешений для пользователя по Access token https://istransit.kz/api/authorization/v02/access/ diff --git a/src/main/java/org/ccalm/jwt/tools/CustomException.java b/src/main/java/org/ccalm/jwt/tools/CustomException.java index f8889fa..5b5f7d2 100644 --- a/src/main/java/org/ccalm/jwt/tools/CustomException.java +++ b/src/main/java/org/ccalm/jwt/tools/CustomException.java @@ -75,5 +75,4 @@ public class CustomException extends Exception { public ErrorResponseModel getErrorResponseModel() { return error; } - } From bd35689d6cf22dc877b6e51c020e9340d0130b06 Mon Sep 17 00:00:00 2001 From: Igor I Date: Thu, 3 Apr 2025 18:10:24 +0500 Subject: [PATCH 3/3] =?UTF-8?q?=D0=BF=D0=9F=D0=BE=D0=BB=D1=83=D1=87=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/org/ccalm/jwt/MainController.java | 21 ++++++------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/ccalm/jwt/MainController.java b/src/main/java/org/ccalm/jwt/MainController.java index ce0bd51..debdfdb 100644 --- a/src/main/java/org/ccalm/jwt/MainController.java +++ b/src/main/java/org/ccalm/jwt/MainController.java @@ -500,26 +500,17 @@ public class MainController implements ServletContextAware { @RequestMapping(value = "/access", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8") @ResponseBody public ResponseEntity access( - Model model, - @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, + Authentication authentication, @Nullable @RequestBody ActionNameModel action_name, @CookieValue(value = "lng", defaultValue = "1") String language_id ) { Translation trt = new Translation(language_id, jdbcTemplate); try { - if (jwt_a.isEmpty() || countOccurrences(jwt_a, '.') != 2) { - return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Please_log_in"), null, null), HttpStatus.INTERNAL_SERVER_ERROR); - } - - Jws claims; - try { - claims = Jwts.parserBuilder() - .setSigningKey(getPublicKey()) - .build() - .parseClaimsJws(jwt_a); - } catch (Exception e) { - 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); + if (authentication == null || !authentication.isAuthenticated()) { + String uuid = UUID.randomUUID().toString(); + return new ResponseEntity<>(new ErrorResponseModel(10401, trt.trt(false, "Please_log_in"), null, uuid), HttpStatus.UNAUTHORIZED); } + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); String sql = """ select @@ -533,7 +524,7 @@ public class MainController implements ServletContextAware { """; MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("user_id", claims.getBody().get("user_id")); + parameters.addValue("user_id", userDetails.getUserId()); if (action_name == null) { parameters.addValue("action_name", null); } else {