diff --git a/README.md b/README.md index f876d23..fd7cd9c 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ https://istransit.kz/api/authorization/v02/update/ } ``` -### Проверить валидность токена +### Проверить валидность токена доступа https://istransit.kz/api/authorization/v02/alive/ На вход Cookie с jwt_a токеном, на выход код ошибки. diff --git a/src/main/java/org/ccalm/jwt/MainController.java b/src/main/java/org/ccalm/jwt/MainController.java index 402a175..d19b4a7 100644 --- a/src/main/java/org/ccalm/jwt/MainController.java +++ b/src/main/java/org/ccalm/jwt/MainController.java @@ -24,6 +24,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.BadSqlGrammarException; @@ -162,7 +163,7 @@ public class MainController implements ServletContextAware { return count; } - + //------------------------------------------------------------------------------------------------------------------ public static String afterLast(String str, String sub) { int pos = str.lastIndexOf(sub); if (pos == -1) { @@ -170,7 +171,7 @@ public class MainController implements ServletContextAware { } return str.substring(pos + sub.length()); } - + //------------------------------------------------------------------------------------------------------------------ public static String beforeFirst(String str, String ch) { int i=str.indexOf(ch); if(i!=-1) @@ -179,7 +180,7 @@ public class MainController implements ServletContextAware { } return ""; } - + //------------------------------------------------------------------------------------------------------------------ private PrivateKey getPrivateKey() { try { byte[] keyBytes = Base64.getDecoder().decode(this.private_key); @@ -191,7 +192,7 @@ public class MainController implements ServletContextAware { } return null; } - + //------------------------------------------------------------------------------------------------------------------ private PublicKey getPublicKey() { try { byte[] keyBytes = Base64.getDecoder().decode(this.public_key); @@ -204,7 +205,7 @@ public class MainController implements ServletContextAware { } return null; } - + //------------------------------------------------------------------------------------------------------------------ /** * Create a Refresh Cookie */ @@ -240,7 +241,7 @@ public class MainController implements ServletContextAware { return true; } - + //------------------------------------------------------------------------------------------------------------------ /** * Create a Access Cookie */ @@ -264,7 +265,7 @@ public class MainController implements ServletContextAware { response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString()); return true; } - + //------------------------------------------------------------------------------------------------------------------ @Operation(summary = "Get API version(date) of build", description = "Returns the date and API name") @RequestMapping(value = "/",method = RequestMethod.GET,produces = "application/json;charset=utf-8") @ResponseBody @@ -297,23 +298,17 @@ public class MainController implements ServletContextAware { } return ResponseEntity.ok(json.toString()); } - - @Operation(summary = "Get user settings from the database by their ID from JWT", description = "Get user settings from the database by their ID from JWT") - @RequestMapping(value = "/get_settings",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") + //------------------------------------------------------------------------------------------------------------------ + @Operation(summary = "Get user settings from the database by their ID in JWT", description = "Get user settings from the database by their ID from JWT") + @RequestMapping(value = "/get_settings",method = {RequestMethod.POST},produces = "application/json;charset=utf-8") @ResponseBody - public String get_settings(@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { + public Object get_settings(@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try{ - json.put("error_code",0); - //json.put("error_message",""); - //json.put("error_marker",(String)null); - if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) { throw new CustomException(10000, trt.trt("Please_log_in"),null); } - //Проверяю подпись токена Jws claims = null; try { claims = Jwts.parserBuilder() @@ -321,7 +316,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - return createStrJSONError(10000, trt.trt("JWT_token_verification_error"),(String)null,(String)null); + throw new CustomException(10000, trt.trt("Please_log_in"),null); } String sql = """ select @@ -336,26 +331,21 @@ public class MainController implements ServletContextAware { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("user_id", claims.getBody().get("user_id")); List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); - JSONArray data = new JSONArray(); - for (int i = 0; i < ret.size(); i++) { - data.put((new JSONObject(ret.get(i))).getString("name")); + List data = new ArrayList<>(); + for (String s : ret) { + data.add((new JSONObject(s)).getString("name")); } - json.put("data",data); - + return ApiResponseData.success(data); } catch (CustomException e) { - json = e.getJson(); - } catch (BadSqlGrammarException e) { - String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = createJSONError(10000,trt.trt("Error_executing_SQL_query"),(String)null, uuid); + return e.getErrorResponseModel(); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid,e); - json = createJSONError(10000,trt.trt("Internal_Server_Error"),(String)null, uuid); + return new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), (String)null, uuid); } - return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ + @Operation(summary = "Create or update user settings", description = "") @RequestMapping(value = "/set_settings",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody public String set_settings(SettingModel setting, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { @@ -378,7 +368,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, trt.trt("JWT_token_verification_error"),null); + throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); } //TODO проверить доступ для выполнения данной функции //Выполняем функцию @@ -424,49 +414,56 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ @Operation( summary = "Get list of permissions", description = "Get list of permissions for user by Access token", responses = { @ApiResponse( responseCode = "200", - description = "Успешный ответ", + description = "Successful response", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiResponseData.class) ) + ), + @ApiResponse( + responseCode = "500", + description = "Internal server error", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorResponseModel.class) + ) ) } ) - @RequestMapping(value = "/access",method = {RequestMethod.POST},produces = "application/json;charset=utf-8") + @RequestMapping(value = "/access", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8") @ResponseBody - public ApiResponseData access( + public ResponseEntity access( Model model, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @Nullable @RequestBody ActionNameModel action_name, - @CookieValue(value = "lng",defaultValue = "1") String language_id + @CookieValue(value = "lng", defaultValue = "1") String language_id ) { - Translation trt = new Translation(language_id,jdbcTemplate); - ApiResponseData> result = null; + Translation trt = new Translation(language_id, jdbcTemplate); try { - if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) - { - return ApiResponseData.error(10000, trt.trt("Please_log_in"),null,null); + if (jwt_a.equals("") || countOccurrences(jwt_a, '.') != 2) { + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Please_log_in"), null, null), HttpStatus.INTERNAL_SERVER_ERROR); } - //Проверяю подпись токена - Jws claims = null; + + Jws claims; try { claims = Jwts.parserBuilder() .setSigningKey(getPublicKey()) .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - return ApiResponseData.error(10000, trt.trt("JWT_token_verification_error"),null,null); + return new ResponseEntity<>(new ErrorResponseModel(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")), null, null), HttpStatus.INTERNAL_SERVER_ERROR); } - String sql = """ + + String sql = """ select - name + name1 from main.get_access_list(:user_id) where @@ -475,28 +472,30 @@ public class MainController implements ServletContextAware { order by name """; - MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("user_id", claims.getBody().get("user_id")); - if(action_name == null) + if (action_name == null) { parameters.addValue("action_name", null); - else + } else { parameters.addValue("action_name", action_name.getAction_name()); + } + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); List data = new ArrayList<>(); for (String s : ret) { data.add((new JSONObject(s)).getString("name")); } - result = ApiResponseData.success(data); + + return new ResponseEntity<>(ApiResponseData.success(data), HttpStatus.OK); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - return ApiResponseData.error(10000, trt.trt("Internal_Server_Error"),(String)null,uuid); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return (ApiResponseData) result; } - - @RequestMapping(value = "/captcha",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") + //------------------------------------------------------------------------------------------------------------------ + @Operation(summary = "Generate CAPTCHA by email", description = "") + @RequestMapping(value = "/captcha",method = RequestMethod.POST,produces = "application/json;charset=utf-8") @ResponseBody public String captcha(Model model, @RequestBody EmailModel email_model, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); @@ -547,8 +546,9 @@ public class MainController implements ServletContextAware { } return json.toString(); } - - @RequestMapping(value = "/create",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") + //------------------------------------------------------------------------------------------------------------------ + @Operation(summary = "Create new user account", description = "") + @RequestMapping(value = "/create",method = RequestMethod.POST,produces = "application/json;charset=utf-8") @ResponseBody public String create(@RequestBody NewUserModel newUserModel,@RequestParam(required=false,name="lng",defaultValue="1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); @@ -681,7 +681,8 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ + @Operation(summary = "Get user account information", description = "") @RequestMapping(value = "/info",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody public String info(Model model, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @CookieValue(value = "lng",defaultValue="1") String language_id) { @@ -703,7 +704,7 @@ public class MainController implements ServletContextAware { .build() .parseClaimsJws(jwt_a); } catch (Exception e) { - throw new CustomException(10000, trt.trt("JWT_token_verification_error"),null); + throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); } //Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине) @@ -749,7 +750,7 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ @Operation(summary = "Login and get JWT token", description = "Login and get JWT token") @RequestMapping(value = "/login",method = RequestMethod.POST,produces = "application/json;charset=utf-8") @ResponseBody @@ -1026,7 +1027,7 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ Map userIsBlocked(Translation trt, String login,String ip) throws CustomException { int attempt_count=0, attempt_limit=0;//, attempt_duration=0; MapSqlParameterSource parameters = null; @@ -1068,9 +1069,8 @@ public class MainController implements ServletContextAware { result.put("attempt_limit", attempt_limit); return result; } - - //Функция для генерации нового TOTP ключа (немного похожа на логин, но не логин). - //Если это первое получение TOTP, то старый TOTP не нужен если последующее, то нужен! + //------------------------------------------------------------------------------------------------------------------ + @Operation(summary = "Function for generating a new TOTP key", description = "Function to generate a new TOTP key (a bit like login, but not login). If this is the first time you receive TOTP, then the old TOTP is not needed, but if it is the next one, then you do!") @RequestMapping(value = "/newtotp",method = {RequestMethod.POST},produces = "application/json;charset=utf-8") @ResponseBody public String newtotp(HttpServletRequest request, @RequestBody LoginModel loginModel, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { @@ -1229,7 +1229,7 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/logout",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody public String logout(HttpServletResponse response,HttpServletRequest request) { @@ -1241,7 +1241,7 @@ public class MainController implements ServletContextAware { return createStrJSONError(0,"",(String)null,(String)null); } - + //------------------------------------------------------------------------------------------------------------------ //Update refresh token @RequestMapping(value = "/refresh",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody @@ -1278,7 +1278,7 @@ public class MainController implements ServletContextAware { .parseClaimsJws(jwt_r); } catch (Exception e) { logout(response,request); - throw new CustomException(10000, trt.trt("JWT_token_verification_error"),null); + throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); } //Для обнаружения попытки взлома проверяю чтобы подпись токена доступа совпадала с тем что записано в токете обновления @@ -1340,7 +1340,7 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/reset",method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html;charset=utf-8") @ResponseBody public String reset(@RequestParam(required=false,name="token",defaultValue = "") String token,@RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { @@ -1396,7 +1396,7 @@ public class MainController implements ServletContextAware { } return createHTMLError(0,trt.trt("The_password_has_been_changed_and_you_will_be_redirected_to_the_main_page")); } - + //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/restore",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody public String restore(Model model, @RequestBody RestoreModel restore, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { @@ -1495,7 +1495,7 @@ public class MainController implements ServletContextAware { } return createStrJSONError(0, trt.trt("A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null); } - + //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/update",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody public String update(HttpServletRequest request, @RequestBody UpdateModel update, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { @@ -1594,49 +1594,68 @@ public class MainController implements ServletContextAware { } return json.toString(); } - + //------------------------------------------------------------------------------------------------------------------ + @Operation( + summary = "Check the validity of the access token", + description = "Check by key and in Redis for reauthorization", + responses = { + @ApiResponse( + responseCode = "200", + description = "Successful response error_code = 0", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorResponseModel.class) + ) + ), + @ApiResponse( + responseCode = "500", + description = "Internal server error", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorResponseModel.class) + ) + ) + } + ) @RequestMapping(value = "/alive",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody - public String alive(HttpServletResponse response,HttpServletRequest request, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @CookieValue(value = "lng",defaultValue="1") String language_id) { - + public ResponseEntity alive(HttpServletResponse response,HttpServletRequest request, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @CookieValue(value = "lng",defaultValue="1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - - if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) - { - return createStrJSONError(10000,trt.trt("Please_log_in"),(String)null,(String)null); - } - //Connection conn = getConnection(); - //Checking the token signature - Jws claims = null; - //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256"); try { - claims = Jwts.parserBuilder() - .setSigningKey(getPublicKey()) //.setSigningKey(key_a) - .build() - .parseClaimsJws(jwt_a); - } catch (Exception e) { - return createStrJSONError(10000, trt.trt("JWT_token_verification_error"),(String)null,(String)null); - } - //If this is a repeat authorization, then we inform the client about it - String result=null; - try(Cache cache = new Cache(redis_host,redis_port,redis_password)) { - cache.open(); - String data = cache.get(claims.getSignature()); - if (data != null) { - if (data.equals("repeat")) - result = createStrJSONError(10000, trt.trt("Reauthorization_detected_if_it_is_not_you_please_change_your_password"),(String)null,(String)null); - else - result = createStrJSONError(10000, trt.trt("Your_authorization_token_is_not_valid"),(String)null,(String)null); + if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) + { + throw new CustomException(10000, Collections.singletonList(trt.trt("Please_log_in")),null); } + //Checking the token signature + Jws claims = null; + try { + claims = Jwts.parserBuilder() + .setSigningKey(getPublicKey()) //.setSigningKey(key_a) + .build() + .parseClaimsJws(jwt_a); + } catch (Exception e) { + throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("JWT_token_verification_error")),null); + } + //If this is a repeat authorization, then we inform the client about it + String result=null; + try(Cache cache = new Cache(redis_host,redis_port,redis_password)) { + cache.open(); + String data = cache.get(claims.getSignature()); + if (data != null) { + logout(response,request); + if (data.equals("repeat")) { + throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("Reauthorization_detected_if_it_is_not_you_please_change_your_password")), null); + }else { + throw new CustomException(10000, Arrays.asList(trt.trt("Please_log_in"), trt.trt("Your_authorization_token_is_not_valid")), null); + } + } + } + return new ResponseEntity<>(new ErrorResponseModel(0), HttpStatus.OK); } catch (Exception e) { - logger.error("An error occurred", e); - e.printStackTrace(); + String uuid = UUID.randomUUID().toString(); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); + } finally { } - if(result!=null) - { - logout(response,request); - return result; - } - return createStrJSONError(0,"",(String)null,(String)null); } } \ No newline at end of file diff --git a/src/main/java/org/ccalm/jwt/models/ActionNameModel.java b/src/main/java/org/ccalm/jwt/models/ActionNameModel.java index 621669d..78138f4 100644 --- a/src/main/java/org/ccalm/jwt/models/ActionNameModel.java +++ b/src/main/java/org/ccalm/jwt/models/ActionNameModel.java @@ -13,5 +13,4 @@ public class ActionNameModel { @Schema(description = "Action name", example = "arm_") @JsonProperty("action_name") private String action_name; - } diff --git a/src/main/java/org/ccalm/jwt/models/ApiResponseData.java b/src/main/java/org/ccalm/jwt/models/ApiResponseData.java index 0532c5f..0ef4d68 100644 --- a/src/main/java/org/ccalm/jwt/models/ApiResponseData.java +++ b/src/main/java/org/ccalm/jwt/models/ApiResponseData.java @@ -1,87 +1,44 @@ package org.ccalm.jwt.models; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; import java.util.Arrays; +import java.util.Collections; +import java.util.List; @Schema( - description = "Стандартный ответ API", - example = "{ \"error_code\": 0, \"error_message\": \"\", \"data\": [\"arm_accounting\", \"arm_carrier\", \"arm_hr\"] }" + description = "Standard API response", + example = "{ \"error_code\": 0, \"error_message\": \"\", \"data\": [\"arm_accounting\",\"arm_carrier\",\"arm_hr\"] }" ) public class ApiResponseData { - @Schema(description = "Код ошибки", example = "0") + @Schema(description = "Error code", example = "0") + @JsonProperty("error_code") private int errorCode; - @Schema(description = "Сообщение об ошибке", example = "") - private String errorMessage; + @Setter + @Getter + @Schema(description = "Data") + private List data; - @Schema(description = "Параметры для переводимого текста", example = "") - private String errorSetting; - - @Schema(description = "Уникальный идентификатор для поиска в базе", example = "") - private String errorMarker; - - @Schema(description = "Данные", example = "[\"arm_accounting\", \"arm_carrier\", \"arm_hr\"]") - private T data; - - public ApiResponseData() { - } - - public ApiResponseData(int errorCode, String errorMessage, String errorSetting, String errorMarker, T data) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - this.errorSetting = errorSetting; - this.errorMarker = errorMarker; + public ApiResponseData(List data) { + errorCode = 0; this.data = data; } - public static ApiResponseData success(T data) { - return new ApiResponseData<>(0, "","","", data); + public static ApiResponseData success(List data) { + return new ApiResponseData(data); } - public static ApiResponseData error(int code, String message, String setting, String marker) { - return new ApiResponseData<>(code, message, setting, marker, null); - } - - // Геттеры и сеттеры - public int getErrorCode() { + public int getError_code() { return errorCode; } - public void setErrorCode(int errorCode) { + public void setError_code(int errorCode) { this.errorCode = errorCode; } - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public void setErrorSetting(String errorSetting) { - this.errorSetting = errorSetting; - } - - public String getErrorSetting() { - return errorSetting; - } - - public void setErrorMarker(String errorMarker) { - this.errorMarker = errorMarker; - } - - public String getErrorMarker() { - return errorMarker; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } } \ No newline at end of file diff --git a/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java b/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java new file mode 100644 index 0000000..0332a49 --- /dev/null +++ b/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java @@ -0,0 +1,98 @@ +package org.ccalm.jwt.models; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +import java.util.Collections; +import java.util.List; + +@Schema( + description = "Error API response", + example = "{ \"error_code\": 10000, \"error_message\": [\"Internal_Server_Error\",\"Please_log_in\"], \"error_setting\": [\"99;day\",\"1;2\"], \"error_marker\": \"2a449883-c7c6-468e-b3ae-5f73fc96627d\" }" +) + +public class ErrorResponseModel { + + @Schema(description = "Error code", example = "10000") + @JsonProperty("error_code") + private int errorCode; + + @Schema(description = "List of error descriptions", example = "[\"Internal_Server_Error\",\"Please_log_in\"]") + @JsonProperty("error_message") + private List errorMessage; + + @Schema(description = "Options for translated text", example = "[\"99;day\",\"1;2\"]") + @JsonProperty("error_setting") + private List errorSetting; + + @Schema(description = "Unique identifier for searching in the database", example = "4260aad8-f7ee-4be4-b52c-15d56ec83232") + @JsonProperty("error_marker") + private String errorMarker; + + public ErrorResponseModel(int errorCode) { + this.errorCode = errorCode; + this.errorMessage = null; + this.errorSetting = null; + this.errorMarker = null; + } + + public ErrorResponseModel(int errorCode, List errorMessage, String errorMarker) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + this.errorMarker = errorMarker; + } + + public ErrorResponseModel(int errorCode, String errorMessage, String errorMarker) { + this.errorCode = errorCode; + this.errorMessage = Collections.singletonList(errorMessage); + this.errorMarker = errorMarker; + } + + public ErrorResponseModel(int errorCode, String errorMessage, String errorSetting, String errorMarker) { + this.errorCode = errorCode; + this.errorMessage = Collections.singletonList(errorMessage); + this.errorSetting = Collections.singletonList(errorSetting); + this.errorMarker = errorMarker; + } + + public ErrorResponseModel(int errorCode, List errorMessage, List errorSetting, String errorMarker) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + this.errorSetting = errorSetting; + this.errorMarker = errorMarker; + } + + public int getError_code() { + return errorCode; + } + + public void setError_code(int errorCode) { + this.errorCode = errorCode; + } + + public List getError_message() { + return errorMessage; + } + + public void setError_message(List errorMessage) { + this.errorMessage = errorMessage; + } + + public void setError_setting(List errorSetting) { + this.errorSetting = errorSetting; + } + + public List getError_setting() { + return errorSetting; + } + + public void setError_marker(String errorMarker) { + this.errorMarker = errorMarker; + } + + public String getError_marker() { + return errorMarker; + } +} \ No newline at end of file diff --git a/src/main/java/org/ccalm/jwt/tools/CustomException.java b/src/main/java/org/ccalm/jwt/tools/CustomException.java index 2cfcba7..c0214ec 100644 --- a/src/main/java/org/ccalm/jwt/tools/CustomException.java +++ b/src/main/java/org/ccalm/jwt/tools/CustomException.java @@ -2,63 +2,56 @@ package org.ccalm.jwt.tools; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.ccalm.jwt.models.ApiResponseData; +import org.ccalm.jwt.models.ErrorResponseModel; import org.json.JSONException; import org.json.JSONObject; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; import java.util.Arrays; import java.util.List; +@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public class CustomException extends Exception { private static final Logger logger = LogManager.getLogger(CustomException.class); - private int errorCode; - private String marker; - private List errorMessages; - private List errorSettings; + + private ErrorResponseModel error; public CustomException(int errorCode, String errorMessage, String marker) { super(errorMessage); - this.errorMessages = Arrays.asList(errorMessage); - this.errorCode = errorCode; - this.marker = marker; + error = new ErrorResponseModel(errorCode, errorMessage, marker); } public CustomException(int errorCode, String errorMessage, String errorSetting, String marker) { super(errorMessage); - this.errorMessages = Arrays.asList(errorMessage); - this.errorSettings = Arrays.asList(errorSetting); - this.errorCode = errorCode; - this.marker = marker; + error = new ErrorResponseModel(errorCode, errorMessage, errorSetting, marker); } public CustomException(int errorCode, List errorMessages, String marker) { super(String.join(" ", errorMessages)); - this.errorMessages = errorMessages; - this.errorCode = errorCode; - this.marker = marker; + error = new ErrorResponseModel(errorCode, errorMessages, marker); } public CustomException(int errorCode, List errorMessages, List errorSettings, String marker) { super(String.join(" ", errorMessages)); - this.errorMessages = errorMessages; - this.errorSettings = errorSettings; - this.errorCode = errorCode; - this.marker = marker; + error = new ErrorResponseModel(errorCode, errorMessages, errorSettings, marker); } public int getErrorCode() { - return this.errorCode; + return error.getError_code(); } public String getErrorMarker() { - return this.marker; + return error.getError_marker(); } public List getErrorMessages() { - return this.errorMessages; + return error.getError_message(); } public List getErrorSettings() { - return this.errorSettings; + return error.getError_setting(); } public JSONObject getJson() { @@ -73,4 +66,8 @@ public class CustomException extends Exception { } return json; } + + public ErrorResponseModel getErrorResponseModel() { + return error; + } }