diff --git a/src/main/java/org/ccalm/jwt/MainController.java b/src/main/java/org/ccalm/jwt/MainController.java index f367e77..d7865b8 100644 --- a/src/main/java/org/ccalm/jwt/MainController.java +++ b/src/main/java/org/ccalm/jwt/MainController.java @@ -325,9 +325,12 @@ public class MainController implements ServletContextAware { @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 - public ResponseEntity index() { - JSONObject json = new JSONObject(); + public ResponseEntity index( + @CookieValue(value = "lng", defaultValue = "1") String language_id + ) { + Translation trt = new Translation(language_id,jdbcTemplate); try { + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); json.put("error_marker",(String)null); @@ -361,31 +364,28 @@ public class MainController implements ServletContextAware { endpoints.forEach(System.out::println); }*/ - } catch (JSONException e) { - throw new RuntimeException(e); + return new ResponseEntity<>(json.toString(), HttpStatus.OK); + } catch (Exception e) { + String uuid = UUID.randomUUID().toString(); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return ResponseEntity.ok(json.toString()); } //------------------------------------------------------------------------------------------------------------------ @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 Object get_settings(@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { + public ResponseEntity get_settings( + Authentication authentication, + @RequestParam(required=false,name="lng",defaultValue = "1") String language_id + ) { Translation trt = new Translation(language_id,jdbcTemplate); try{ - if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) - { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); - } - Jws claims = null; - try { - claims = Jwts.parserBuilder() - .setSigningKey(getPublicKey()) //.setSigningKey(key_a) - .build() - .parseClaimsJws(jwt_a); - } catch (Exception e) { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); + if (authentication == null || !authentication.isAuthenticated()) { + throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false); } + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + String sql = """ select us.name, @@ -397,49 +397,48 @@ public class MainController implements ServletContextAware { and user_id=:user_id """; MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("user_id", claims.getBody().get("user_id")); + parameters.addValue("user_id", userDetails.getUserId()); List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); List data = new ArrayList<>(); for (String s : ret) { data.add((new JSONObject(s)).getString("name")); } - return ApiResponseData.success(data); + + return new ResponseEntity<>(data, HttpStatus.OK); } catch (CustomException e) { - return e.getErrorResponseModel(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - return new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), (String)null, uuid); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } } //------------------------------------------------------------------------------------------------------------------ @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 ResponseEntity set_settings(SettingModel setting, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { + public ResponseEntity set_settings( + Authentication authentication, + SettingModel setting, + @RequestParam(required=false,name="lng",defaultValue = "1") String language_id + ) { Translation trt = new Translation(language_id,jdbcTemplate); try{ - if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) - { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); - } - //Проверяю подпись токена - Jws claims = null; - try { - claims = Jwts.parserBuilder() - .setSigningKey(getPublicKey()) - .build() - .parseClaimsJws(jwt_a); - } catch (Exception e) { - throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null,false); + if (authentication == null || !authentication.isAuthenticated()) { + throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false); } + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + //TODO проверить доступ для выполнения данной функции //Выполняем функцию String sql = """ select id from main._users_settings where user_id=:user_id and identifier=:identifier limit 1 """; MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("user_id", claims.getBody().get("user_id")); + parameters.addValue("user_id", userDetails.getUserId()); parameters.addValue("identifier", setting.getIdentifier()); List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); long id=0; @@ -463,16 +462,16 @@ public class MainController implements ServletContextAware { """; } parameters = new MapSqlParameterSource(); - parameters.addValue("user_id", claims.getBody().get("user_id")); + parameters.addValue("user_id", userDetails.getUserId()); parameters.addValue("identifier", setting.getIdentifier()); parameters.addValue("value", setting.getValue()); jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); return new ResponseEntity<>(new ErrorResponseModel(0), HttpStatus.OK); - } catch (CustomException e) { - String uuid = UUID.randomUUID().toString(); - logger.error(uuid, e); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); @@ -513,8 +512,7 @@ public class MainController implements ServletContextAware { Translation trt = new Translation(language_id, jdbcTemplate); try { if (authentication == null || !authentication.isAuthenticated()) { - String uuid = UUID.randomUUID().toString(); - return new ResponseEntity<>(new ErrorResponseModel(10401, trt.trt(false, "Please_log_in"), null, uuid), HttpStatus.UNAUTHORIZED); + throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false); } UserDetails userDetails = (UserDetails) authentication.getPrincipal(); @@ -544,6 +542,14 @@ public class MainController implements ServletContextAware { } return new ResponseEntity<>(ApiResponseData.success(data), HttpStatus.OK); + } catch (CustomException e) { + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + if(e.getErrorCode()==10401) + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.UNAUTHORIZED); + else + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); logger.error(uuid, e); @@ -554,12 +560,12 @@ public class MainController implements ServletContextAware { @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) { + public ResponseEntity captcha(Model model, @RequestBody EmailModel email_model, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try{ + JSONObject json = new JSONObject(); json.put("error_code",0); - json.put("error_message",""); + //json.put("error_message",""); ImageCaptcha.Builder builder; if(Tools.isInteger(email_model.getWidth())) { @@ -586,9 +592,7 @@ public class MainController implements ServletContextAware { byte[] bytes = baos.toByteArray(); json.put("image",Base64.getEncoder().encodeToString(bytes)); } catch (IOException e) { - String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - throw new CustomException(10000, trt.trt(false, "Input_output_error"),uuid,false); + throw new CustomException(10000, trt.trt(false, "Input_output_error"),UUID.randomUUID().toString(),true); } //Формирую JSON токена и шифрую его @@ -601,14 +605,17 @@ public class MainController implements ServletContextAware { //Подпись для как бы токена json.put("token",sToken+"."+Tools.generateSignature(captchaKey, sToken)); + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return json.toString(); } //------------------------------------------------------------------------------------------------------------------ @Operation( @@ -753,11 +760,14 @@ public class MainController implements ServletContextAware { return new ResponseEntity<>(new ErrorResponseModel(0,trt.trt(false, "The_verification_code_has_been_sent_to_your_email_address"),null), HttpStatus.OK); } catch (CustomException e) { - return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.OK); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); 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(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } } //------------------------------------------------------------------------------------------------------------------ @@ -765,10 +775,10 @@ public class MainController implements ServletContextAware { @Operation(summary = "Create new user account", description = "After creating a user, adding a default user role") @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) { + public ResponseEntity create(@RequestBody NewUserModel newUserModel,@RequestParam(required=false,name="lng",defaultValue="1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try{ + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); @@ -906,47 +916,43 @@ public class MainController implements ServletContextAware { json.put("error_message",trt.trt(false, "The_authorization_password_has_been_sent_to_your_email_address")); + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - 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) { + public ResponseEntity info( + Authentication authentication, + @CookieValue(value = "lng",defaultValue="1") String language_id + ) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try { + if (authentication == null || !authentication.isAuthenticated()) { + throw new CustomException(10401, trt.trt(false, "Please_log_in"),UUID.randomUUID().toString(),false); + } + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); - if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) - { - throw new CustomException(10000, trt.trt(false, "Please_log_in"),null,false); - } - //Проверяю подпись токена - Jws claims = null; - try { - claims = Jwts.parserBuilder() - .setSigningKey(getPublicKey()) - .build() - .parseClaimsJws(jwt_a); - } catch (Exception e) { - throw new CustomException(10000, Arrays.asList(trt.trt(false, "Please_log_in"), trt.trt(false, "JWT_token_verification_error")),null,false); - } - //Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине) String sql = "select * from main.get_user_info(1,:user_id);"; try { MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("user_id", claims.getBody().get("user_id")); + parameters.addValue("user_id", userDetails.getUserId()); List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); for (int i = 0; i < ret.size(); i++) { json = new JSONObject(ret.get(i)); @@ -972,27 +978,32 @@ public class MainController implements ServletContextAware { json.put("error_code",0); } + + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); - } - catch (Exception e) { + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); + } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); - } finally { - //try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - 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 - public String login(HttpServletResponse response, HttpServletRequest request, @RequestBody LoginModel loginModel, @CookieValue(value = "lng", defaultValue = "1") String language_id) { - + public ResponseEntity login( + HttpServletResponse response, + HttpServletRequest request, + @RequestBody LoginModel loginModel, + @CookieValue(value = "lng", defaultValue = "1") String language_id + ) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try { + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); @@ -1250,16 +1261,17 @@ public class MainController implements ServletContextAware { json.put("roles",rolesArray); } + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); - } finally { - //try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return json.toString(); } //------------------------------------------------------------------------------------------------------------------ Map userIsBlocked(Translation trt, String login,String ip) throws CustomException { @@ -1307,10 +1319,10 @@ public class MainController implements ServletContextAware { @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) { + public ResponseEntity newtotp(HttpServletRequest request, @RequestBody LoginModel loginModel, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try { + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); @@ -1452,16 +1464,17 @@ public class MainController implements ServletContextAware { json.put("error_message", ""); json.put("url", otpauthUrl); + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); - } finally { - //try { if(conn!=null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return json.toString(); } //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/logout",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @@ -1475,11 +1488,11 @@ public class MainController implements ServletContextAware { //Update refresh token @RequestMapping(value = "/refresh",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody - public String refresh(HttpServletResponse response,HttpServletRequest request,@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,@CookieValue(value = "jwt_r", defaultValue = "") String jwt_r,@RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { + public ResponseEntity refresh(HttpServletResponse response,HttpServletRequest request,@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,@CookieValue(value = "jwt_r", defaultValue = "") String jwt_r,@RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try { + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); @@ -1516,7 +1529,7 @@ public class MainController implements ServletContextAware { String token_ar_sig = token.getBody().get("sig", String.class); //Она же но уже в токене обновления if(token_aa_sig==null || !token_aa_sig.equals(token_ar_sig)){ logout(response,request); //Удаляю куки чтобы эмулировать выход из приложения - return createStrJSONError(10000,trt.trt(false, "Attempt_to_substitution_tokens"),(String)null,(String)null); + throw new CustomException(10000, trt.trt(false, "Attempt_to_substitution_tokens"),null,false); } //TODO проверить не заблокирован ли пользователь @@ -1559,16 +1572,17 @@ public class MainController implements ServletContextAware { (System.currentTimeMillis() + access_time * 1000)/1000 ); + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - json = Tools.createJSONError(10000,trt.trt(false, "Internal_Server_Error"), (String)null, uuid); - } finally { - + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return json.toString(); } //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/reset",method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html;charset=utf-8") @@ -1629,7 +1643,7 @@ public class MainController implements ServletContextAware { //------------------------------------------------------------------------------------------------------------------ @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) { + public ResponseEntity restore(Model model, @RequestBody RestoreModel restore, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); String result=createStrJSONError(10000,trt.trt(false, "Request_not_processed"), (String)null, (String)null); @@ -1652,17 +1666,18 @@ public class MainController implements ServletContextAware { //расшифровываю JSONObject token = new JSONObject(Tools.decryptText(captchaKey,payload)); - if(token==null) - return createStrJSONError(10000,trt.trt(false, "Please_send_a_valid_JSON_string_in_your_token"), (String)null,(String)null); + if(token==null) { + throw new CustomException(10000,trt.trt(false,"Please_send_a_valid_JSON_string_in_your_token"),null,false); + } if(!restore.getCode().equals(token.getString("code"))){ - return createStrJSONError(10000,trt.trt(false, "The_code_did_not_match"),(String)null,(String)null); + throw new CustomException(10000,trt.trt(false,"The_code_did_not_match"),null,false); } if(token.getLong("exp")(createStrJSONError(0, trt.trt(false,"A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null), HttpStatus.OK); + } catch (CustomException e) { + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - return createStrJSONError(10000,trt.trt(false,"Internal_Server_Error"), (String)null,uuid); + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return createStrJSONError(0, trt.trt(false,"A_recovery_link_has_been_sent_to_your_email"),(String)null,(String)null); } //------------------------------------------------------------------------------------------------------------------ @RequestMapping(value = "/update",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody - public String update(HttpServletRequest request, @RequestBody UpdateModel update, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { + public ResponseEntity update(HttpServletRequest request, @RequestBody UpdateModel update, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); - JSONObject json = new JSONObject(); try { + JSONObject json = new JSONObject(); json.put("error_code",0); json.put("error_message",""); @@ -1812,15 +1829,17 @@ public class MainController implements ServletContextAware { json.put("error_marker",(String)null); } + return new ResponseEntity<>(json.toString(), HttpStatus.OK); } catch (CustomException e) { - json = e.getJson(); + if(e.isSaveToLog()) { + logger.error(e.getErrorMarker(), e); + } + return new ResponseEntity<>(e.getErrorResponseModel(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String uuid = UUID.randomUUID().toString(); - logger.error(uuid,e); - return createStrJSONError(10000,trt.trt(false,"Internal_Server_Error"), (String)null,uuid); - } finally { + logger.error(uuid, e); + return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR); } - return json.toString(); } //------------------------------------------------------------------------------------------------------------------ @Operation( @@ -1847,8 +1866,12 @@ public class MainController implements ServletContextAware { ) @RequestMapping(value = "/alive",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @ResponseBody - //public ResponseEntity 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, Authentication authentication, @CookieValue(value = "lng",defaultValue="1") String language_id) { + public ResponseEntity alive( + Authentication authentication, + HttpServletResponse response, + HttpServletRequest request, + @CookieValue(value = "lng",defaultValue="1") String language_id + ) { Translation trt = new Translation(language_id,jdbcTemplate); try { if (authentication == null || !authentication.isAuthenticated()) { diff --git a/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java b/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java index 0332a49..79891bf 100644 --- a/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java +++ b/src/main/java/org/ccalm/jwt/models/ErrorResponseModel.java @@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; import java.util.Collections; import java.util.List; +import java.util.UUID; @Schema( description = "Error API response", @@ -35,7 +36,7 @@ public class ErrorResponseModel { this.errorCode = errorCode; this.errorMessage = null; this.errorSetting = null; - this.errorMarker = null; + this.errorMarker = UUID.randomUUID().toString(); } public ErrorResponseModel(int errorCode, List errorMessage, String errorMarker) {