+HTTP код +Правка текста количества попыток
This commit is contained in:
29
README.md
29
README.md
@ -27,6 +27,35 @@ ____
|
|||||||
10. [Проверить валидность токена](#проверить-валидность-токена)
|
10. [Проверить валидность токена](#проверить-валидность-токена)
|
||||||
|
|
||||||
____
|
____
|
||||||
|
|
||||||
|
Запаковка в хранилище ключей
|
||||||
|
|
||||||
|
```sh
|
||||||
|
openssl pkcs12 -export \
|
||||||
|
-in authorization.crt \
|
||||||
|
-inkey authorization.key \
|
||||||
|
-out keystore.p12 \
|
||||||
|
-name tomcat \
|
||||||
|
-CAfile authorization-ca.crt \
|
||||||
|
-caname root \
|
||||||
|
-password pass:MFNX344yh4
|
||||||
|
```
|
||||||
|
|
||||||
|
📖 Расшифровка аргументов:
|
||||||
|
|
||||||
|
| Параметр | Назначение |
|
||||||
|
|---------------------------------|---------------------------------------------------------------------------------------------|
|
||||||
|
| `openssl pkcs12` | Утилита OpenSSL, работающая с PKCS#12 контейнерами (включают сертификаты и ключи). |
|
||||||
|
| `-export` | Указывает, что нужно экспортировать (создать) PKCS#12-файл. |
|
||||||
|
| `-in authorization.crt` | Основной (публичный) сертификат. Это то, что выдано для твоего домена. |
|
||||||
|
| `-inkey authorization.key` | Приватный ключ, соответствующий сертификату. Нужен для использования сертификата. |
|
||||||
|
| `-out keystore.p12` | Выходной файл (итоговый контейнер PKCS#12). Это будет твой `keystore`. |
|
||||||
|
| `-name tomcat` | Алиас (имя) для ключа в хранилище. Spring Boot (и Tomcat) по умолчанию ищет alias `tomcat`. |
|
||||||
|
| `-CAfile authorization-ca.crt` | (Необязательно) Цепочка доверенных сертификатов (например, корневой и промежуточные CA). |
|
||||||
|
| `-caname root` | Имя для CA-сертификата (используется внутри контейнера). |
|
||||||
|
| `-password pass: XXXXXX` | Пароль для защиты хранилища (в Spring Boot это `key-store-password`). |
|
||||||
|
|
||||||
|
|
||||||
### Получить токен для защиты от CSRF атак
|
### Получить токен для защиты от CSRF атак
|
||||||
https://istransit.kz/api/authorization/v02/get_request_token
|
https://istransit.kz/api/authorization/v02/get_request_token
|
||||||
|
|
||||||
|
|||||||
@ -16,7 +16,8 @@ public class GlobalExceptionHandler {
|
|||||||
@ExceptionHandler(NoHandlerFoundException.class)
|
@ExceptionHandler(NoHandlerFoundException.class)
|
||||||
public ResponseEntity<ErrorResponseModel> handleNotFound(NoHandlerFoundException ex) {
|
public ResponseEntity<ErrorResponseModel> handleNotFound(NoHandlerFoundException ex) {
|
||||||
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
||||||
10000 + HttpStatus.NOT_FOUND.value(),
|
HttpStatus.NOT_FOUND.value(),
|
||||||
|
10000,
|
||||||
"Not_Found",
|
"Not_Found",
|
||||||
UUID.randomUUID().toString()
|
UUID.randomUUID().toString()
|
||||||
);
|
);
|
||||||
@ -26,7 +27,8 @@ public class GlobalExceptionHandler {
|
|||||||
@ExceptionHandler(Exception.class)
|
@ExceptionHandler(Exception.class)
|
||||||
public ResponseEntity<ErrorResponseModel> handleException(Exception ex) {
|
public ResponseEntity<ErrorResponseModel> handleException(Exception ex) {
|
||||||
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
||||||
10000 + HttpStatus.NOT_FOUND.value(),
|
HttpStatus.NOT_FOUND.value(),
|
||||||
|
10000,
|
||||||
"Internal_Server_Error", //Collections.singletonList("Internal_Server_Error"),
|
"Internal_Server_Error", //Collections.singletonList("Internal_Server_Error"),
|
||||||
UUID.randomUUID().toString()
|
UUID.randomUUID().toString()
|
||||||
);
|
);
|
||||||
@ -36,7 +38,8 @@ public class GlobalExceptionHandler {
|
|||||||
@RequestMapping("/error")
|
@RequestMapping("/error")
|
||||||
public ResponseEntity<ErrorResponseModel> handleError() {
|
public ResponseEntity<ErrorResponseModel> handleError() {
|
||||||
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
||||||
10000 + HttpStatus.NOT_FOUND.value(),
|
HttpStatus.NOT_FOUND.value(),
|
||||||
|
10000,
|
||||||
"Unknown_error",
|
"Unknown_error",
|
||||||
UUID.randomUUID().toString()
|
UUID.randomUUID().toString()
|
||||||
);
|
);
|
||||||
|
|||||||
@ -163,6 +163,14 @@ public class MainController implements ServletContextAware {
|
|||||||
return json.toString();
|
return json.toString();
|
||||||
}
|
}
|
||||||
//---------------------------------------------------------------------------
|
//---------------------------------------------------------------------------
|
||||||
|
public static HttpStatus getHttpStatus(int code) {
|
||||||
|
try {
|
||||||
|
return HttpStatus.valueOf(code);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
return HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//---------------------------------------------------------------------------
|
||||||
public String createHTMLError(int code, String message) {
|
public String createHTMLError(int code, String message) {
|
||||||
return "<!DOCTYPE html><html><head><meta http-equiv=\"refresh\" content=\"0; url='" + this.url_main + "?msg=" + message + "'\" /></head><body></body></html>";
|
return "<!DOCTYPE html><html><head><meta http-equiv=\"refresh\" content=\"0; url='" + this.url_main + "?msg=" + message + "'\" /></head><body></body></html>";
|
||||||
}
|
}
|
||||||
@ -301,7 +309,7 @@ public class MainController implements ServletContextAware {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"), null, true);
|
throw new CustomException(500, 10000, trt.trt(false, "Internal_Server_Error"), null, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@ -314,11 +322,11 @@ public class MainController implements ServletContextAware {
|
|||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -368,7 +376,7 @@ public class MainController implements ServletContextAware {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -382,7 +390,7 @@ public class MainController implements ServletContextAware {
|
|||||||
Translation trt = new Translation(language_id,jdbcTemplate);
|
Translation trt = new Translation(language_id,jdbcTemplate);
|
||||||
try{
|
try{
|
||||||
if (authentication == null || !authentication.isAuthenticated()) {
|
if (authentication == null || !authentication.isAuthenticated()) {
|
||||||
throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
||||||
}
|
}
|
||||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||||
|
|
||||||
@ -409,11 +417,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -428,7 +436,7 @@ public class MainController implements ServletContextAware {
|
|||||||
Translation trt = new Translation(language_id,jdbcTemplate);
|
Translation trt = new Translation(language_id,jdbcTemplate);
|
||||||
try{
|
try{
|
||||||
if (authentication == null || !authentication.isAuthenticated()) {
|
if (authentication == null || !authentication.isAuthenticated()) {
|
||||||
throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
||||||
}
|
}
|
||||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||||
|
|
||||||
@ -467,16 +475,16 @@ public class MainController implements ServletContextAware {
|
|||||||
parameters.addValue("value", setting.getValue());
|
parameters.addValue("value", setting.getValue());
|
||||||
jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||||
|
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(0), HttpStatus.OK);
|
return new ResponseEntity<>(new ErrorResponseModel(200, 0), HttpStatus.OK);
|
||||||
} catch (CustomException e) {
|
} catch (CustomException e) {
|
||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -512,7 +520,7 @@ public class MainController implements ServletContextAware {
|
|||||||
Translation trt = new Translation(language_id, jdbcTemplate);
|
Translation trt = new Translation(language_id, jdbcTemplate);
|
||||||
try {
|
try {
|
||||||
if (authentication == null || !authentication.isAuthenticated()) {
|
if (authentication == null || !authentication.isAuthenticated()) {
|
||||||
throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
||||||
}
|
}
|
||||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||||
|
|
||||||
@ -546,14 +554,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
if(e.getErrorCode()==10401)
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.UNAUTHORIZED);
|
|
||||||
else
|
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -592,7 +597,7 @@ public class MainController implements ServletContextAware {
|
|||||||
byte[] bytes = baos.toByteArray();
|
byte[] bytes = baos.toByteArray();
|
||||||
json.put("image",Base64.getEncoder().encodeToString(bytes));
|
json.put("image",Base64.getEncoder().encodeToString(bytes));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new CustomException(10000, trt.trt(false, "Input_output_error"),UUID.randomUUID().toString(),true);
|
throw new CustomException(401, 10000, trt.trt(false, "Input_output_error"),UUID.randomUUID().toString(),true);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Формирую JSON токена и шифрую его
|
//Формирую JSON токена и шифрую его
|
||||||
@ -610,11 +615,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -656,7 +661,7 @@ public class MainController implements ServletContextAware {
|
|||||||
|
|
||||||
String signature2 = Tools.generateSignature(captchaKey, payload);
|
String signature2 = Tools.generateSignature(captchaKey, payload);
|
||||||
if (!signature1.equals(signature2)) {
|
if (!signature1.equals(signature2)) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_signature_did_not_match"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "The_signature_did_not_match"),null,false);
|
||||||
}
|
}
|
||||||
//Расшифровываю
|
//Расшифровываю
|
||||||
String sToken = Tools.decryptText(captchaKey,payload);
|
String sToken = Tools.decryptText(captchaKey,payload);
|
||||||
@ -669,19 +674,19 @@ public class MainController implements ServletContextAware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(jToken==null) {
|
if(jToken==null) {
|
||||||
throw new CustomException(10000, trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"),null,false);
|
||||||
}
|
}
|
||||||
if (!verificationModel.getCode().equals(jToken.getString("code"))) {
|
if (!verificationModel.getCode().equals(jToken.getString("code"))) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_code_did_not_match_what_was_specified_in_the_captcha"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "The_code_did_not_match_what_was_specified_in_the_captcha"),null,false);
|
||||||
}
|
}
|
||||||
if (jToken.getLong("exp") < (System.currentTimeMillis() / 1000L)) {
|
if (jToken.getLong("exp") < (System.currentTimeMillis() / 1000L)) {
|
||||||
throw new CustomException(10000, List.of(trt.trt(false, "Captcha_is_outdated"),trt.trt(false, "Please_update_the_captcha")),null,false);
|
throw new CustomException(401, 10000, List.of(trt.trt(false, "Captcha_is_outdated"),trt.trt(false, "Please_update_the_captcha")),null,false);
|
||||||
}
|
}
|
||||||
if (!Tools.isValidEmail(jToken.getString("email"))) {
|
if (!Tools.isValidEmail(jToken.getString("email"))) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "The_email_field_is_incorrect"),null,false);
|
||||||
}
|
}
|
||||||
if (!verificationModel.getEmail().equals(jToken.getString("email"))) {
|
if (!verificationModel.getEmail().equals(jToken.getString("email"))) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_email_did_not_match_what_was_specified_in_the_captcha"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "The_email_did_not_match_what_was_specified_in_the_captcha"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//If this is a repeat authorization, then we inform the client about it
|
//If this is a repeat authorization, then we inform the client about it
|
||||||
@ -692,9 +697,9 @@ public class MainController implements ServletContextAware {
|
|||||||
// if (data != null) {
|
// if (data != null) {
|
||||||
// logout(response,request);
|
// logout(response,request);
|
||||||
// if (data.equals("repeat")) {
|
// 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, false);
|
// throw new CustomException(401, 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 {
|
// }else {
|
||||||
// throw new CustomException(10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"Your_authorization_token_is_not_valid")), null, false);
|
// throw new CustomException(401, 10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"Your_authorization_token_is_not_valid")), null, false);
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
@ -717,7 +722,7 @@ public class MainController implements ServletContextAware {
|
|||||||
parameters.addValue("captcha", verificationModel.getCode());
|
parameters.addValue("captcha", verificationModel.getCode());
|
||||||
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||||
for (int i = 0; i < ret.size(); i++) {
|
for (int i = 0; i < ret.size(); i++) {
|
||||||
throw new CustomException(10000, trt.trt(false, "Please_update_the_captcha_and_resubmit_it"),null,false);
|
throw new CustomException(200, 10000, trt.trt(false, "Please_update_the_captcha_and_resubmit_it"),null,false);
|
||||||
}
|
}
|
||||||
//Delete previous verification records
|
//Delete previous verification records
|
||||||
sql= """
|
sql= """
|
||||||
@ -755,19 +760,19 @@ public class MainController implements ServletContextAware {
|
|||||||
try {
|
try {
|
||||||
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, verificationModel.getEmail(), trt.trt(true,"Email_verification_code"), html);
|
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, verificationModel.getEmail(), trt.trt(true,"Email_verification_code"), html);
|
||||||
} catch (MessagingException e) {
|
} catch (MessagingException e) {
|
||||||
throw new CustomException(10000, String.format(trt.trt(false, "Failed_send_mail_to_s"), verificationModel.getEmail()),null,false);
|
throw new CustomException(500, 10000, String.format(trt.trt(false, "Failed_send_mail_to_s"), verificationModel.getEmail()),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(0,trt.trt(false, "The_verification_code_has_been_sent_to_your_email_address"),null), HttpStatus.OK);
|
return new ResponseEntity<>(new ErrorResponseModel(200, 0,trt.trt(false, "The_verification_code_has_been_sent_to_your_email_address"),null), HttpStatus.OK);
|
||||||
} catch (CustomException e) {
|
} catch (CustomException e) {
|
||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -783,19 +788,19 @@ public class MainController implements ServletContextAware {
|
|||||||
json.put("error_message","");
|
json.put("error_message","");
|
||||||
|
|
||||||
if(newUserModel.getName().length()<3) {
|
if(newUserModel.getName().length()<3) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_name_field_is_empty"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_name_field_is_empty"),null,false);
|
||||||
}
|
}
|
||||||
if(newUserModel.getEmail().length()<6) {
|
if(newUserModel.getEmail().length()<6) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_email_field_is_empty"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_email_field_is_empty"),null,false);
|
||||||
}
|
}
|
||||||
if (!Tools.isValidEmail(newUserModel.getEmail())) {
|
if (!Tools.isValidEmail(newUserModel.getEmail())) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_email_field_is_incorrect"),null,false);
|
||||||
}
|
}
|
||||||
if(newUserModel.getCode().length()<3) {
|
if(newUserModel.getCode().length()<3) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_code_field_is_empty"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_code_field_is_empty"),null,false);
|
||||||
}
|
}
|
||||||
if(newUserModel.getToken().length()<3) {
|
if(newUserModel.getToken().length()<3) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_token_field_is_empty"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_token_field_is_empty"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Проверяю что подпись одинакова
|
//Проверяю что подпись одинакова
|
||||||
@ -804,7 +809,7 @@ public class MainController implements ServletContextAware {
|
|||||||
|
|
||||||
String signature2 = Tools.generateSignature(captchaKey, payload);
|
String signature2 = Tools.generateSignature(captchaKey, payload);
|
||||||
if (!signature1.equals(signature2)) {
|
if (!signature1.equals(signature2)) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_signature_did_not_match"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_signature_did_not_match"),null,false);
|
||||||
}
|
}
|
||||||
//Расшифровываю
|
//Расшифровываю
|
||||||
String sToken = Tools.decryptText(captchaKey,payload);
|
String sToken = Tools.decryptText(captchaKey,payload);
|
||||||
@ -817,19 +822,19 @@ public class MainController implements ServletContextAware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(jToken==null) {
|
if(jToken==null) {
|
||||||
throw new CustomException(10000, trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"),null,false);
|
||||||
}
|
}
|
||||||
if (!newUserModel.getCode().equals(jToken.getString("code"))) {
|
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,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_code_did_not_match_what_was_specified_in_the_captcha"),null,false);
|
||||||
}
|
}
|
||||||
if (jToken.getLong("exp") < (System.currentTimeMillis() / 1000L)) {
|
if (jToken.getLong("exp") < (System.currentTimeMillis() / 1000L)) {
|
||||||
throw new CustomException(10000, List.of(trt.trt(false, "Captcha_is_outdated"),trt.trt(false, "Please_update_the_captcha")),null,false);
|
throw new CustomException(400, 10000, List.of(trt.trt(false, "Captcha_is_outdated"),trt.trt(false, "Please_update_the_captcha")),null,false);
|
||||||
}
|
}
|
||||||
if (!Tools.isValidEmail(jToken.getString("email"))) {
|
if (!Tools.isValidEmail(jToken.getString("email"))) {
|
||||||
throw new CustomException(10000, trt.trt(false, "The_email_field_is_incorrect"),null,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_email_field_is_incorrect"),null,false);
|
||||||
}
|
}
|
||||||
if (!newUserModel.getEmail().equals(jToken.getString("email"))) {
|
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,false);
|
throw new CustomException(400, 10000, trt.trt(false, "The_email_did_not_match_what_was_specified_in_the_captcha"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Проверяю существование пользователя с таким email
|
//Проверяю существование пользователя с таким email
|
||||||
@ -840,7 +845,7 @@ public class MainController implements ServletContextAware {
|
|||||||
parameters.addValue("email", newUserModel.getEmail());
|
parameters.addValue("email", newUserModel.getEmail());
|
||||||
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||||
for (int i = 0; i < ret.size(); i++) {
|
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,false);
|
throw new CustomException(200, 10000, trt.trt(false, "A_user_with_the_same_email_address_already_exists"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Генерируем временный пароль
|
// Генерируем временный пароль
|
||||||
@ -911,7 +916,7 @@ public class MainController implements ServletContextAware {
|
|||||||
try {
|
try {
|
||||||
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, newUserModel.getEmail(), trt.trt(true,"Password"), html);
|
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, newUserModel.getEmail(), trt.trt(true,"Password"), html);
|
||||||
} catch (MessagingException e) {
|
} catch (MessagingException e) {
|
||||||
throw new CustomException(10000, String.format(trt.trt(false, "Failed_send_mail_to_s"), newUserModel.getEmail()),null,false);
|
throw new CustomException(500, 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"));
|
json.put("error_message",trt.trt(false, "The_authorization_password_has_been_sent_to_your_email_address"));
|
||||||
@ -921,11 +926,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -939,7 +944,7 @@ public class MainController implements ServletContextAware {
|
|||||||
Translation trt = new Translation(language_id,jdbcTemplate);
|
Translation trt = new Translation(language_id,jdbcTemplate);
|
||||||
try {
|
try {
|
||||||
if (authentication == null || !authentication.isAuthenticated()) {
|
if (authentication == null || !authentication.isAuthenticated()) {
|
||||||
throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false);
|
||||||
}
|
}
|
||||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||||
|
|
||||||
@ -958,17 +963,15 @@ public class MainController implements ServletContextAware {
|
|||||||
json = new JSONObject(ret.get(i));
|
json = new JSONObject(ret.get(i));
|
||||||
}
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
throw new CustomException(500, 10000, trt.trt(false, "Error_executing_SQL_query"), UUID.randomUUID().toString(), true);
|
||||||
logger.error(uuid, ex);
|
|
||||||
throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"), uuid,false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (json == null) {
|
if (json == null) {
|
||||||
throw new CustomException(10000, trt.trt(false, "Invalid_username_and_or_password"), null,false);
|
throw new CustomException(200, 10000, trt.trt(false, "Invalid_username_and_or_password"), null,false);
|
||||||
} else {
|
} else {
|
||||||
if (json.has("block")) {
|
if (json.has("block")) {
|
||||||
if (!json.isNull("block") && json.getBoolean("block"))
|
if (!json.isNull("block") && json.getBoolean("block"))
|
||||||
throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), null,false);
|
throw new CustomException(200, 10006, trt.trt(false, "The_user_account_is_blocked"), null,false);
|
||||||
json.remove("block");
|
json.remove("block");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -984,11 +987,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -1008,15 +1011,15 @@ public class MainController implements ServletContextAware {
|
|||||||
json.put("error_message","");
|
json.put("error_message","");
|
||||||
|
|
||||||
if(loginModel.getLogin().isEmpty())
|
if(loginModel.getLogin().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_login_field_is_empty"),null,false);
|
||||||
if(!Tools.isValidEmail(loginModel.getLogin()))
|
if(!Tools.isValidEmail(loginModel.getLogin()))
|
||||||
throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_login_field_is_incorrect"),null,false);
|
||||||
if(loginModel.getPassword().isEmpty())
|
if(loginModel.getPassword().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_password_field_is_empty"),null,false);
|
||||||
if(loginModel.getPassword().length()<=3)
|
if(loginModel.getPassword().length()<=3)
|
||||||
throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_password_field_is_short"),null,false);
|
||||||
if(loginModel.getAppid().isEmpty())
|
if(loginModel.getAppid().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_application_name_field_is_empty"),null,false);
|
||||||
|
|
||||||
String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания
|
String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания
|
||||||
if (ipAddress == null) {
|
if (ipAddress == null) {
|
||||||
@ -1044,9 +1047,9 @@ public class MainController implements ServletContextAware {
|
|||||||
if (!json.has("result") || json.getBoolean("result")) {
|
if (!json.has("result") || json.getBoolean("result")) {
|
||||||
if(json.getInt("count")==0)
|
if(json.getInt("count")==0)
|
||||||
{
|
{
|
||||||
throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null,false);
|
throw new CustomException(200, 10000, trt.trt(false, "The_user_account_is_blocked"),null,false);
|
||||||
}else{
|
}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,false);
|
throw new CustomException(200, 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")) {
|
if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) {
|
||||||
@ -1058,7 +1061,7 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (DataAccessException ex){
|
}catch (DataAccessException ex){
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error("Функция main.user_is_blocked не вернула результата!", uuid, ex);
|
logger.error("Функция main.user_is_blocked не вернула результата!", uuid, ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
|
|
||||||
@ -1085,19 +1088,23 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (DataAccessException ex){
|
}catch (DataAccessException ex){
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid,ex);
|
logger.error(uuid,ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Internal_Server_Error"),uuid,true);
|
||||||
}
|
}
|
||||||
if(json==null) {
|
if(json==null) {
|
||||||
String msg = trt.trt(false, "Invalid_username_and_or_password");
|
List<String> msglist = new ArrayList<>();
|
||||||
if(attempt_count>0){
|
List<String> parlist = new ArrayList<>();
|
||||||
msg = msg + " " + String.format(trt.trt(false, "Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit);
|
msglist.add(trt.trt(false, "Invalid_username_and_or_password"));
|
||||||
|
parlist.add("");
|
||||||
|
if(attempt_count>0) {
|
||||||
|
msglist.add(trt.trt(false, "Authorization_attempts_s_out_of_s"));
|
||||||
|
parlist.add(attempt_count+";"+attempt_limit+";");
|
||||||
}
|
}
|
||||||
throw new CustomException(10000, msg, null,false);
|
throw new CustomException(200, 10000, msglist, parlist, null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (json.has("block")) {
|
if (json.has("block")) {
|
||||||
if (json.getBoolean("block")) {
|
if (json.getBoolean("block")) {
|
||||||
throw new CustomException(10006, trt.trt(false, "The_user_account_is_blocked"), (String)null,false);
|
throw new CustomException(200, 10006, trt.trt(false, "The_user_account_is_blocked"), (String)null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
json.remove("block");
|
json.remove("block");
|
||||||
@ -1105,11 +1112,11 @@ public class MainController implements ServletContextAware {
|
|||||||
|
|
||||||
long currentTime = System.currentTimeMillis() / 1000L;
|
long currentTime = System.currentTimeMillis() / 1000L;
|
||||||
if (json.has("expiration") && json.getLong("expiration") < currentTime) {
|
if (json.has("expiration") && json.getLong("expiration") < currentTime) {
|
||||||
throw new CustomException(10009, trt.trt(false, "Password_expired_and_must_be_changed"), (String)null,false);
|
throw new CustomException(200, 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")) {
|
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,false);
|
throw new CustomException(200, 10010, trt.trt(false, "You_need_to_get_a_new_TOTP_key"), (String)null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
ArrayList errorMessages;
|
ArrayList errorMessages;
|
||||||
@ -1125,7 +1132,7 @@ public class MainController implements ServletContextAware {
|
|||||||
errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";");
|
errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";");
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new CustomException(10012, errorMessages, errorSettings, (String)null,false);
|
throw new CustomException(200, 10012, errorMessages, errorSettings, (String)null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (json.has("totp_success") && !json.getBoolean("totp_success")) {
|
if (json.has("totp_success") && !json.getBoolean("totp_success")) {
|
||||||
@ -1139,7 +1146,7 @@ public class MainController implements ServletContextAware {
|
|||||||
errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";");
|
errorSettings.add(str + ";" + String.valueOf(attempt_limit) + ";");
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new CustomException(10000, errorMessages, errorSettings, (String)null,false);
|
throw new CustomException(200, 10000, errorMessages, errorSettings, (String)null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (json.has("totp_required")) {
|
if (json.has("totp_required")) {
|
||||||
@ -1167,7 +1174,7 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (Exception ex){
|
}catch (Exception ex){
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid,ex);
|
logger.error(uuid,ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256");
|
//SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256");
|
||||||
@ -1266,11 +1273,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -1289,9 +1296,9 @@ public class MainController implements ServletContextAware {
|
|||||||
if (!json.has("result") || json.getBoolean("result")) {
|
if (!json.has("result") || json.getBoolean("result")) {
|
||||||
if(json.getInt("count")==0)
|
if(json.getInt("count")==0)
|
||||||
{
|
{
|
||||||
throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null,false);
|
throw new CustomException(200, 10000, trt.trt(false, "The_user_account_is_blocked"),null,false);
|
||||||
}else{
|
}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,false);
|
throw new CustomException(200, 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")) {
|
if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) {
|
||||||
@ -1303,11 +1310,11 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (DataAccessException ex){
|
}catch (DataAccessException ex){
|
||||||
java.lang.String uuid = UUID.randomUUID().toString();
|
java.lang.String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, ex);
|
logger.error(uuid, ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Internal_Server_Error"),uuid,false);
|
||||||
}catch (Exception e) {
|
}catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid,e);
|
logger.error(uuid,e);
|
||||||
throw new CustomException(10000, trt.trt(false, "Internal_Server_Error"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Internal_Server_Error"),uuid,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Integer> result = new HashMap<>();
|
Map<String, Integer> result = new HashMap<>();
|
||||||
@ -1327,15 +1334,15 @@ public class MainController implements ServletContextAware {
|
|||||||
json.put("error_message","");
|
json.put("error_message","");
|
||||||
|
|
||||||
if(loginModel.getLogin().isEmpty())
|
if(loginModel.getLogin().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false, "The_login_field_is_empty"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_login_field_is_empty"),null,false);
|
||||||
if(!Tools.isValidEmail(loginModel.getLogin()))
|
if(!Tools.isValidEmail(loginModel.getLogin()))
|
||||||
throw new CustomException(10000,trt.trt(false, "The_login_field_is_incorrect"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_login_field_is_incorrect"),null,false);
|
||||||
if(loginModel.getPassword().isEmpty())
|
if(loginModel.getPassword().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false, "The_password_field_is_empty"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_password_field_is_empty"),null,false);
|
||||||
if(loginModel.getPassword().length()<=3)
|
if(loginModel.getPassword().length()<=3)
|
||||||
throw new CustomException(10000,trt.trt(false, "The_password_field_is_short"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_password_field_is_short"),null,false);
|
||||||
if(loginModel.getAppid().isEmpty())
|
if(loginModel.getAppid().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false, "The_application_name_field_is_empty"),null,false);
|
throw new CustomException(400, 10000,trt.trt(false, "The_application_name_field_is_empty"),null,false);
|
||||||
|
|
||||||
String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания
|
String ipAddress = request.getHeader("X-FORWARDED-FOR"); //Не беспокойся на регистр не обращает внимания
|
||||||
if (ipAddress == null) {
|
if (ipAddress == null) {
|
||||||
@ -1363,9 +1370,9 @@ public class MainController implements ServletContextAware {
|
|||||||
if (!json.has("result") || json.getBoolean("result")) {
|
if (!json.has("result") || json.getBoolean("result")) {
|
||||||
if(json.getInt("count")==0)
|
if(json.getInt("count")==0)
|
||||||
{
|
{
|
||||||
throw new CustomException(10000, trt.trt(false, "The_user_account_is_blocked"),null,false);
|
throw new CustomException(200, 10000, trt.trt(false, "The_user_account_is_blocked"),null,false);
|
||||||
}else{
|
}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,false);
|
throw new CustomException(200, 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")) {
|
if(json.has("count") && json.has("limit_count") && json.has("limit_duration")) {
|
||||||
@ -1377,7 +1384,7 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (DataAccessException ex){
|
}catch (DataAccessException ex){
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error("Error executing SQL query", uuid, ex);
|
logger.error("Error executing SQL query", uuid, ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
throw new CustomException(200, 10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
String sql = "";
|
String sql = "";
|
||||||
@ -1401,19 +1408,23 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (DataAccessException ex){
|
}catch (DataAccessException ex){
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid,ex);
|
logger.error(uuid,ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
||||||
}
|
}
|
||||||
if(json==null) {
|
if(json==null) {
|
||||||
String msg = trt.trt(false, "Invalid_username_and_or_password");
|
List<String> msglist = new ArrayList<>();
|
||||||
if(attempt_count>0){
|
List<String> parlist = new ArrayList<>();
|
||||||
msg = msg + " " + String.format(trt.trt(false, "Authorization_attempts_s_out_of_s"),attempt_count,attempt_limit);
|
msglist.add(trt.trt(false, "Invalid_username_and_or_password"));
|
||||||
|
parlist.add(null);
|
||||||
|
if(attempt_count>0) {
|
||||||
|
msglist.add(trt.trt(false, "Authorization_attempts_s_out_of_s"));
|
||||||
|
parlist.add(attempt_count+";"+attempt_limit+";");
|
||||||
}
|
}
|
||||||
throw new CustomException(10000, msg, null,false);
|
throw new CustomException(200, 10000, msglist, parlist, null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(json.has("block")) {
|
if(json.has("block")) {
|
||||||
if(json.getBoolean("block"))
|
if(json.getBoolean("block"))
|
||||||
throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"),null,false);
|
throw new CustomException(200, 10006,trt.trt(false, "The_user_account_is_blocked"),null,false);
|
||||||
json.remove("block");
|
json.remove("block");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1422,13 +1433,13 @@ public class MainController implements ServletContextAware {
|
|||||||
if(!json.isNull("secret")) {
|
if(!json.isNull("secret")) {
|
||||||
|
|
||||||
if(!Tools.isInteger(loginModel.getTotp()))
|
if(!Tools.isInteger(loginModel.getTotp()))
|
||||||
throw new CustomException(10000,trt.trt(false, "The_TOTP_field_is_empty"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false, "The_TOTP_field_is_empty"),null,false);
|
||||||
|
|
||||||
//Проверяю на соответствие TOTP ключа TODO потом написать поверку в функции p__Login плагином
|
//Проверяю на соответствие TOTP ключа TODO потом написать поверку в функции p__Login плагином
|
||||||
GoogleAuthenticator gAuth = new GoogleAuthenticator();
|
GoogleAuthenticator gAuth = new GoogleAuthenticator();
|
||||||
boolean isCodeValid = gAuth.authorize(json.getString("secret"), Integer.valueOf(loginModel.getTotp()));
|
boolean isCodeValid = gAuth.authorize(json.getString("secret"), Integer.valueOf(loginModel.getTotp()));
|
||||||
if(!isCodeValid){
|
if(!isCodeValid){
|
||||||
throw new CustomException(10000, trt.trt(false, "TOTP_key_does_not_match"), null,false);
|
throw new CustomException(200, 10000, trt.trt(false, "TOTP_key_does_not_match"), null,false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
json.remove("secret");
|
json.remove("secret");
|
||||||
@ -1449,7 +1460,7 @@ public class MainController implements ServletContextAware {
|
|||||||
}catch (DataAccessException ex){
|
}catch (DataAccessException ex){
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid,ex);
|
logger.error(uuid,ex);
|
||||||
throw new CustomException(10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
throw new CustomException(500, 10000, trt.trt(false, "Error_executing_SQL_query"),uuid,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Создание OTP URL
|
// Создание OTP URL
|
||||||
@ -1469,11 +1480,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -1499,7 +1510,7 @@ public class MainController implements ServletContextAware {
|
|||||||
if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2 || jwt_r.isEmpty() || countOccurrences(jwt_r, '.')!=2 )
|
if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2 || jwt_r.isEmpty() || countOccurrences(jwt_r, '.')!=2 )
|
||||||
{
|
{
|
||||||
logout(response,request);
|
logout(response,request);
|
||||||
throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "Please_log_in"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Разбираю токен без проверки, чтобы выбрать email
|
//Разбираю токен без проверки, чтобы выбрать email
|
||||||
@ -1521,7 +1532,7 @@ public class MainController implements ServletContextAware {
|
|||||||
.parseClaimsJws(jwt_r);
|
.parseClaimsJws(jwt_r);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logout(response,request);
|
logout(response,request);
|
||||||
throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null,false);
|
throw new CustomException(401, 10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления
|
//Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления
|
||||||
@ -1529,13 +1540,13 @@ public class MainController implements ServletContextAware {
|
|||||||
String token_ar_sig = token.getBody().get("sig", String.class); //Она же но уже в токене обновления
|
String token_ar_sig = token.getBody().get("sig", String.class); //Она же но уже в токене обновления
|
||||||
if(token_aa_sig==null || !token_aa_sig.equals(token_ar_sig)){
|
if(token_aa_sig==null || !token_aa_sig.equals(token_ar_sig)){
|
||||||
logout(response,request); //Удаляю куки чтобы эмулировать выход из приложения
|
logout(response,request); //Удаляю куки чтобы эмулировать выход из приложения
|
||||||
throw new CustomException(10000, trt.trt(false, "Attempt_to_substitution_tokens"),null,false);
|
throw new CustomException(401, 10000, trt.trt(false, "Attempt_to_substitution_tokens"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO проверить не заблокирован ли пользователь
|
//TODO проверить не заблокирован ли пользователь
|
||||||
//if(json.has("block")) {
|
//if(json.has("block")) {
|
||||||
// if(json.getBoolean("block"))
|
// if(json.getBoolean("block"))
|
||||||
// throw new CustomException(10006,trt.trt(false, "The_user_account_is_blocked"), null, false);
|
// throw new CustomException(401, 10006,trt.trt(false, "The_user_account_is_blocked"), null, false);
|
||||||
// json.remove("block");
|
// json.remove("block");
|
||||||
//}
|
//}
|
||||||
|
|
||||||
@ -1577,11 +1588,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -1667,17 +1678,17 @@ public class MainController implements ServletContextAware {
|
|||||||
JSONObject token = new JSONObject(Tools.decryptText(captchaKey,payload));
|
JSONObject token = new JSONObject(Tools.decryptText(captchaKey,payload));
|
||||||
|
|
||||||
if(token==null) {
|
if(token==null) {
|
||||||
throw new CustomException(10000,trt.trt(false,"Please_send_a_valid_JSON_string_in_your_token"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"Please_send_a_valid_JSON_string_in_your_token"),null,false);
|
||||||
}
|
}
|
||||||
if(!restore.getCode().equals(token.getString("code"))){
|
if(!restore.getCode().equals(token.getString("code"))){
|
||||||
throw new CustomException(10000,trt.trt(false,"The_code_did_not_match"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_code_did_not_match"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(token.getLong("exp")<Instant.now().getEpochSecond()){
|
if(token.getLong("exp")<Instant.now().getEpochSecond()){
|
||||||
throw new CustomException(10000,trt.trt(false,"Captcha_is_outdated"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"Captcha_is_outdated"),null,false);
|
||||||
}
|
}
|
||||||
if (!token.has("email") || !Tools.isValidEmail(token.getString("email"))) {
|
if (!token.has("email") || !Tools.isValidEmail(token.getString("email"))) {
|
||||||
throw new CustomException(10000,trt.trt(false,"The_email_field_is_incorrect"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_email_field_is_incorrect"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Проверяю есть ли в базе пользователь если есть отправляю ему почту для востановления
|
//Проверяю есть ли в базе пользователь если есть отправляю ему почту для востановления
|
||||||
@ -1690,7 +1701,7 @@ public class MainController implements ServletContextAware {
|
|||||||
id = (new JSONObject(ret.get(i))).getLong("id");
|
id = (new JSONObject(ret.get(i))).getLong("id");
|
||||||
}
|
}
|
||||||
if(id==0) {
|
if(id==0) {
|
||||||
throw new CustomException(10000,trt.trt(false,"User_with_this_email_was_not_found"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"User_with_this_email_was_not_found"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
String password_new = Tools.generatePassword(6);
|
String password_new = Tools.generatePassword(6);
|
||||||
@ -1713,7 +1724,7 @@ public class MainController implements ServletContextAware {
|
|||||||
try {
|
try {
|
||||||
token_new = URLEncoder.encode(token_new, StandardCharsets.UTF_8.toString());
|
token_new = URLEncoder.encode(token_new, StandardCharsets.UTF_8.toString());
|
||||||
} catch (UnsupportedEncodingException e) {
|
} catch (UnsupportedEncodingException e) {
|
||||||
throw new CustomException(10000,trt.trt(false,"Internal_Server_Error"),null,false);
|
throw new CustomException(500, 10000,trt.trt(false,"Internal_Server_Error"),null,false);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Формирую ссылку для отправки на почту для сброса пароля
|
//Формирую ссылку для отправки на почту для сброса пароля
|
||||||
@ -1725,7 +1736,7 @@ public class MainController implements ServletContextAware {
|
|||||||
try {
|
try {
|
||||||
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, token.getString("email"), trt.trt(true,"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) {
|
} catch (Exception ex) {
|
||||||
throw new CustomException(10000,trt.trt(false,"Failed_send_mail_to_s"),token.getString("email"),UUID.randomUUID().toString(),true);
|
throw new CustomException(200, 10000,trt.trt(false,"Failed_send_mail_to_s"),token.getString("email"),UUID.randomUUID().toString(),true);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ResponseEntity<>(createStrJSONError(0, trt.trt(false,"A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null), HttpStatus.OK);
|
return new ResponseEntity<>(createStrJSONError(0, trt.trt(false,"A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null), HttpStatus.OK);
|
||||||
@ -1733,11 +1744,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -1752,26 +1763,26 @@ public class MainController implements ServletContextAware {
|
|||||||
json.put("error_message","");
|
json.put("error_message","");
|
||||||
|
|
||||||
if(update==null)
|
if(update==null)
|
||||||
throw new CustomException(10000,trt.trt(false,"Please_send_a_valid_JSON_string_in_your_request"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"Please_send_a_valid_JSON_string_in_your_request"),null,false);
|
||||||
if(update.getLogin().isEmpty())
|
if(update.getLogin().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false,"The_login_field_is_empty"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_login_field_is_empty"),null,false);
|
||||||
if (!Tools.isValidEmail(update.getLogin()))
|
if (!Tools.isValidEmail(update.getLogin()))
|
||||||
throw new CustomException(10000, trt.trt(false,"The_email_field_is_incorrect"),null,false);
|
throw new CustomException(200, 10000, trt.trt(false,"The_email_field_is_incorrect"),null,false);
|
||||||
if(update.getPassword().isEmpty())
|
if(update.getPassword().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false,"The_password_field_is_empty"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_password_field_is_empty"),null,false);
|
||||||
if(update.getPasswordNew().isEmpty())
|
if(update.getPasswordNew().isEmpty())
|
||||||
throw new CustomException(10000,trt.trt(false,"The_new_password_field_is_empty"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_new_password_field_is_empty"),null,false);
|
||||||
|
|
||||||
if(!Pattern.compile("[0-9]").matcher(update.getPasswordNew()).find())
|
if(!Pattern.compile("[0-9]").matcher(update.getPasswordNew()).find())
|
||||||
throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_number"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_password_is_missing_a_number"),null,false);
|
||||||
if(!Pattern.compile("[a-z]").matcher(update.getPasswordNew()).find())
|
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,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_password_is_missing_a_small_Latin_letter"),null,false);
|
||||||
if (!Pattern.compile("[A-Z]").matcher(update.getPasswordNew()).find())
|
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,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_password_is_missing_a_big_Latin_letter"),null,false);
|
||||||
if (!Pattern.compile("[_!@#$%^&*]").matcher(update.getPasswordNew()).find())
|
if (!Pattern.compile("[_!@#$%^&*]").matcher(update.getPasswordNew()).find())
|
||||||
throw new CustomException(10000,trt.trt(false,"The_password_is_missing_a_special_letter"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_password_is_missing_a_special_letter"),null,false);
|
||||||
if (update.getPasswordNew().length() < 6)
|
if (update.getPasswordNew().length() < 6)
|
||||||
throw new CustomException(10000,trt.trt(false,"The_password_is_less_than_six_characters"),null,false);
|
throw new CustomException(200, 10000,trt.trt(false,"The_password_is_less_than_six_characters"),null,false);
|
||||||
|
|
||||||
//Проверяем попытки смены пароля (сохраение попыток в функции логина)
|
//Проверяем попытки смены пароля (сохраение попыток в функции логина)
|
||||||
String ipAddress = request.getHeader("X-FORWARDED-FOR");
|
String ipAddress = request.getHeader("X-FORWARDED-FOR");
|
||||||
@ -1794,12 +1805,12 @@ public class MainController implements ServletContextAware {
|
|||||||
for (int i = 0; i < ret.size(); i++) {
|
for (int i = 0; i < ret.size(); i++) {
|
||||||
rows = new JSONObject(ret.get(i));
|
rows = new JSONObject(ret.get(i));
|
||||||
if(rows.getBoolean("result")) {
|
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, false);
|
throw new CustomException(200, 10000, String.format(trt.trt(false,"The_limit_of_authorization_attempts_has_been_exceeded_please_wait_s_minutes"), 5),null, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(rows==null) {
|
if(rows==null) {
|
||||||
logger.error("Функция main.user_is_blocked не вернула результата!");
|
logger.error("Функция main.user_is_blocked не вернула результата!");
|
||||||
throw new CustomException(10000, trt.trt(false,"Error_executing_SQL_query"),null, false);
|
throw new CustomException(200, 10000, trt.trt(false,"Error_executing_SQL_query"),null, false);
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
//Получаю id пользователя TODO should work through the authorization function
|
//Получаю id пользователя TODO should work through the authorization function
|
||||||
@ -1813,7 +1824,7 @@ public class MainController implements ServletContextAware {
|
|||||||
rows = new JSONObject(ret.get(i));
|
rows = new JSONObject(ret.get(i));
|
||||||
}
|
}
|
||||||
if(rows==null)
|
if(rows==null)
|
||||||
throw new CustomException(10000,trt.trt(false,"Invalid_username_and_or_password"),null,false);
|
throw new CustomException(200, 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";
|
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";
|
||||||
@ -1834,11 +1845,11 @@ public class MainController implements ServletContextAware {
|
|||||||
if(e.isSaveToLog()) {
|
if(e.isSaveToLog()) {
|
||||||
logger.error(e.getErrorMarker(), e);
|
logger.error(e.getErrorMarker(), e);
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//------------------------------------------------------------------------------------------------------------------
|
//------------------------------------------------------------------------------------------------------------------
|
||||||
@ -1875,7 +1886,7 @@ public class MainController implements ServletContextAware {
|
|||||||
Translation trt = new Translation(language_id,jdbcTemplate);
|
Translation trt = new Translation(language_id,jdbcTemplate);
|
||||||
try {
|
try {
|
||||||
if (authentication == null || !authentication.isAuthenticated()) {
|
if (authentication == null || !authentication.isAuthenticated()) {
|
||||||
throw new CustomException(10000, Collections.singletonList(trt.trt(false,"Please_log_in")),null,false);
|
throw new CustomException(200, 10000, Collections.singletonList(trt.trt(false,"Please_log_in")),null,false);
|
||||||
}
|
}
|
||||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||||
|
|
||||||
@ -1887,19 +1898,22 @@ public class MainController implements ServletContextAware {
|
|||||||
if (data != null) {
|
if (data != null) {
|
||||||
logout(response,request);
|
logout(response,request);
|
||||||
if (data.equals("repeat")) {
|
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, false);
|
throw new CustomException(200, 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 {
|
}else {
|
||||||
throw new CustomException(10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"Your_authorization_token_is_not_valid")), null, false);
|
throw new CustomException(200, 10000, Arrays.asList(trt.trt(false,"Please_log_in"), trt.trt(false,"Your_authorization_token_is_not_valid")), null, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(0), HttpStatus.OK);
|
return new ResponseEntity<>(new ErrorResponseModel(200, 0), HttpStatus.OK);
|
||||||
} catch (CustomException e) {
|
} catch (CustomException e) {
|
||||||
return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.OK);
|
if(e.isSaveToLog()) {
|
||||||
|
logger.error(e.getErrorMarker(), e);
|
||||||
|
}
|
||||||
|
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
logger.error(uuid, e);
|
logger.error(uuid, e);
|
||||||
return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false,"Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false,"Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -61,6 +61,7 @@ public class SecurityConfig {
|
|||||||
path.equals("/get_session") ||
|
path.equals("/get_session") ||
|
||||||
path.equals("/get_request_token") ||
|
path.equals("/get_request_token") ||
|
||||||
path.equals("/verification") ||
|
path.equals("/verification") ||
|
||||||
|
path.equals("/update") ||
|
||||||
path.equals("/access");
|
path.equals("/access");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,6 +87,7 @@ public class SecurityConfig {
|
|||||||
//Simple check
|
//Simple check
|
||||||
if (jwt_a == null || !jwt_a.contains(".")) {
|
if (jwt_a == null || !jwt_a.contains(".")) {
|
||||||
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
||||||
|
HttpServletResponse.SC_UNAUTHORIZED,
|
||||||
10000 + HttpServletResponse.SC_UNAUTHORIZED,
|
10000 + HttpServletResponse.SC_UNAUTHORIZED,
|
||||||
List.of("Please_log_in", "Please_send_a_valid_JWT_token"),
|
List.of("Please_log_in", "Please_send_a_valid_JWT_token"),
|
||||||
""
|
""
|
||||||
@ -108,6 +110,7 @@ public class SecurityConfig {
|
|||||||
|
|
||||||
if(userId==0L) {
|
if(userId==0L) {
|
||||||
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
ErrorResponseModel errorResponse = new ErrorResponseModel(
|
||||||
|
HttpServletResponse.SC_UNAUTHORIZED,
|
||||||
10000 + HttpServletResponse.SC_UNAUTHORIZED,
|
10000 + HttpServletResponse.SC_UNAUTHORIZED,
|
||||||
List.of("Please_log_in"),
|
List.of("Please_log_in"),
|
||||||
""
|
""
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
package org.ccalm.jwt.models;
|
package org.ccalm.jwt.models;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@ -16,6 +17,9 @@ import java.util.UUID;
|
|||||||
|
|
||||||
public class ErrorResponseModel {
|
public class ErrorResponseModel {
|
||||||
|
|
||||||
|
@JsonIgnore
|
||||||
|
private int httpCode;
|
||||||
|
|
||||||
@Schema(description = "Error code", example = "10000")
|
@Schema(description = "Error code", example = "10000")
|
||||||
@JsonProperty("error_code")
|
@JsonProperty("error_code")
|
||||||
private int errorCode;
|
private int errorCode;
|
||||||
@ -32,39 +36,51 @@ public class ErrorResponseModel {
|
|||||||
@JsonProperty("error_marker")
|
@JsonProperty("error_marker")
|
||||||
private String errorMarker;
|
private String errorMarker;
|
||||||
|
|
||||||
public ErrorResponseModel(int errorCode) {
|
public ErrorResponseModel(int httpCode, int errorCode) {
|
||||||
|
this.httpCode = httpCode;
|
||||||
this.errorCode = errorCode;
|
this.errorCode = errorCode;
|
||||||
this.errorMessage = null;
|
this.errorMessage = null;
|
||||||
this.errorSetting = null;
|
this.errorSetting = null;
|
||||||
this.errorMarker = UUID.randomUUID().toString();
|
this.errorMarker = UUID.randomUUID().toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public ErrorResponseModel(int errorCode, List<String> errorMessage, String errorMarker) {
|
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, String errorMarker) {
|
||||||
|
this.httpCode = httpCode;
|
||||||
this.errorCode = errorCode;
|
this.errorCode = errorCode;
|
||||||
this.errorMessage = errorMessage;
|
this.errorMessage = errorMessage;
|
||||||
this.errorMarker = errorMarker;
|
this.errorMarker = errorMarker;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ErrorResponseModel(int errorCode, String errorMessage, String errorMarker) {
|
public ErrorResponseModel(int httpCode, int errorCode, String errorMessage, String errorMarker) {
|
||||||
|
this.httpCode = httpCode;
|
||||||
this.errorCode = errorCode;
|
this.errorCode = errorCode;
|
||||||
this.errorMessage = Collections.singletonList(errorMessage);
|
this.errorMessage = Collections.singletonList(errorMessage);
|
||||||
this.errorMarker = errorMarker;
|
this.errorMarker = errorMarker;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ErrorResponseModel(int errorCode, String errorMessage, String errorSetting, String errorMarker) {
|
public ErrorResponseModel(int httpCode, int errorCode, String errorMessage, String errorSetting, String errorMarker) {
|
||||||
|
this.httpCode = httpCode;
|
||||||
this.errorCode = errorCode;
|
this.errorCode = errorCode;
|
||||||
this.errorMessage = Collections.singletonList(errorMessage);
|
this.errorMessage = Collections.singletonList(errorMessage);
|
||||||
this.errorSetting = Collections.singletonList(errorSetting);
|
this.errorSetting = Collections.singletonList(errorSetting);
|
||||||
this.errorMarker = errorMarker;
|
this.errorMarker = errorMarker;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ErrorResponseModel(int errorCode, List<String> errorMessage, List<String> errorSetting, String errorMarker) {
|
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, List<String> errorSetting, String errorMarker) {
|
||||||
|
this.httpCode = httpCode;
|
||||||
this.errorCode = errorCode;
|
this.errorCode = errorCode;
|
||||||
this.errorMessage = errorMessage;
|
this.errorMessage = errorMessage;
|
||||||
this.errorSetting = errorSetting;
|
this.errorSetting = errorSetting;
|
||||||
this.errorMarker = errorMarker;
|
this.errorMarker = errorMarker;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getHttp_code() {
|
||||||
|
return httpCode;
|
||||||
|
}
|
||||||
|
public void setHttp_code(int errorCode) {
|
||||||
|
this.httpCode = httpCode;
|
||||||
|
}
|
||||||
|
|
||||||
public int getError_code() {
|
public int getError_code() {
|
||||||
return errorCode;
|
return errorCode;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,30 +19,34 @@ public class CustomException extends Exception {
|
|||||||
@Getter
|
@Getter
|
||||||
private boolean saveToLog = false;
|
private boolean saveToLog = false;
|
||||||
|
|
||||||
public CustomException(int errorCode, String errorMessage, String marker, boolean saveToLog) {
|
public CustomException(int httpCode, int errorCode, String errorMessage, String marker, boolean saveToLog) {
|
||||||
super(errorMessage);
|
super(errorMessage);
|
||||||
error = new ErrorResponseModel(errorCode, errorMessage, marker);
|
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, marker);
|
||||||
this.saveToLog = saveToLog;
|
this.saveToLog = saveToLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CustomException(int errorCode, String errorMessage, String errorSetting, String marker, boolean saveToLog) {
|
public CustomException(int httpCode, int errorCode, String errorMessage, String errorSetting, String marker, boolean saveToLog) {
|
||||||
super(errorMessage);
|
super(errorMessage);
|
||||||
error = new ErrorResponseModel(errorCode, errorMessage, errorSetting, marker);
|
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, errorSetting, marker);
|
||||||
this.saveToLog = saveToLog;
|
this.saveToLog = saveToLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CustomException(int errorCode, List<String> errorMessages, String marker, boolean saveToLog) {
|
public CustomException(int httpCode, int errorCode, List<String> errorMessages, String marker, boolean saveToLog) {
|
||||||
super(String.join(" ", errorMessages));
|
super(String.join(" ", errorMessages));
|
||||||
error = new ErrorResponseModel(errorCode, errorMessages, marker);
|
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, marker);
|
||||||
this.saveToLog = saveToLog;
|
this.saveToLog = saveToLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CustomException(int errorCode, List<String> errorMessages, List<String> errorSettings, String marker, boolean saveToLog) {
|
public CustomException(int httpCode, int errorCode, List<String> errorMessages, List<String> errorSettings, String marker, boolean saveToLog) {
|
||||||
super(String.join(" ", errorMessages));
|
super(String.join(" ", errorMessages));
|
||||||
error = new ErrorResponseModel(errorCode, errorMessages, errorSettings, marker);
|
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, errorSettings, marker);
|
||||||
this.saveToLog = saveToLog;
|
this.saveToLog = saveToLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getHttpCode() {
|
||||||
|
return error.getHttp_code();
|
||||||
|
}
|
||||||
|
|
||||||
public int getErrorCode() {
|
public int getErrorCode() {
|
||||||
return error.getError_code();
|
return error.getError_code();
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
BIN
src/main/resources/keystore.p12
Normal file
BIN
src/main/resources/keystore.p12
Normal file
Binary file not shown.
Reference in New Issue
Block a user