Модификация для документирования

This commit is contained in:
2025-02-02 09:33:15 +05:00
parent 230de423da
commit 76988693e4
6 changed files with 264 additions and 194 deletions

View File

@ -234,7 +234,7 @@ https://istransit.kz/api/authorization/v02/update/
} }
``` ```
### Проверить валидность токена ### Проверить валидность токена доступа
https://istransit.kz/api/authorization/v02/alive/ https://istransit.kz/api/authorization/v02/alive/
На вход Cookie с jwt_a токеном, на выход код ошибки. На вход Cookie с jwt_a токеном, на выход код ошибки.

View File

@ -24,6 +24,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.BadSqlGrammarException;
@ -162,7 +163,7 @@ public class MainController implements ServletContextAware {
return count; return count;
} }
//------------------------------------------------------------------------------------------------------------------
public static String afterLast(String str, String sub) { public static String afterLast(String str, String sub) {
int pos = str.lastIndexOf(sub); int pos = str.lastIndexOf(sub);
if (pos == -1) { if (pos == -1) {
@ -170,7 +171,7 @@ public class MainController implements ServletContextAware {
} }
return str.substring(pos + sub.length()); return str.substring(pos + sub.length());
} }
//------------------------------------------------------------------------------------------------------------------
public static String beforeFirst(String str, String ch) { public static String beforeFirst(String str, String ch) {
int i=str.indexOf(ch); int i=str.indexOf(ch);
if(i!=-1) if(i!=-1)
@ -179,7 +180,7 @@ public class MainController implements ServletContextAware {
} }
return ""; return "";
} }
//------------------------------------------------------------------------------------------------------------------
private PrivateKey getPrivateKey() { private PrivateKey getPrivateKey() {
try { try {
byte[] keyBytes = Base64.getDecoder().decode(this.private_key); byte[] keyBytes = Base64.getDecoder().decode(this.private_key);
@ -191,7 +192,7 @@ public class MainController implements ServletContextAware {
} }
return null; return null;
} }
//------------------------------------------------------------------------------------------------------------------
private PublicKey getPublicKey() { private PublicKey getPublicKey() {
try { try {
byte[] keyBytes = Base64.getDecoder().decode(this.public_key); byte[] keyBytes = Base64.getDecoder().decode(this.public_key);
@ -204,7 +205,7 @@ public class MainController implements ServletContextAware {
} }
return null; return null;
} }
//------------------------------------------------------------------------------------------------------------------
/** /**
* Create a Refresh Cookie * Create a Refresh Cookie
*/ */
@ -240,7 +241,7 @@ public class MainController implements ServletContextAware {
return true; return true;
} }
//------------------------------------------------------------------------------------------------------------------
/** /**
* Create a Access Cookie * Create a Access Cookie
*/ */
@ -264,7 +265,7 @@ public class MainController implements ServletContextAware {
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString()); response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
return true; return true;
} }
//------------------------------------------------------------------------------------------------------------------
@Operation(summary = "Get API version(date) of build", description = "Returns the date and API name") @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") @RequestMapping(value = "/",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
@ -297,23 +298,17 @@ public class MainController implements ServletContextAware {
} }
return ResponseEntity.ok(json.toString()); 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") @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,RequestMethod.GET},produces = "application/json;charset=utf-8") @RequestMapping(value = "/get_settings",method = {RequestMethod.POST},produces = "application/json;charset=utf-8")
@ResponseBody @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); Translation trt = new Translation(language_id,jdbcTemplate);
JSONObject json = new JSONObject();
try{ try{
json.put("error_code",0);
//json.put("error_message","");
//json.put("error_marker",(String)null);
if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2)
{ {
throw new CustomException(10000, trt.trt("Please_log_in"),null); throw new CustomException(10000, trt.trt("Please_log_in"),null);
} }
//Проверяю подпись токена
Jws<Claims> claims = null; Jws<Claims> claims = null;
try { try {
claims = Jwts.parserBuilder() claims = Jwts.parserBuilder()
@ -321,7 +316,7 @@ public class MainController implements ServletContextAware {
.build() .build()
.parseClaimsJws(jwt_a); .parseClaimsJws(jwt_a);
} catch (Exception e) { } 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 = """ String sql = """
select select
@ -336,26 +331,21 @@ public class MainController implements ServletContextAware {
MapSqlParameterSource parameters = new MapSqlParameterSource(); MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("user_id", claims.getBody().get("user_id")); parameters.addValue("user_id", claims.getBody().get("user_id"));
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
JSONArray data = new JSONArray(); List<String> data = new ArrayList<>();
for (int i = 0; i < ret.size(); i++) { for (String s : ret) {
data.put((new JSONObject(ret.get(i))).getString("name")); data.add((new JSONObject(s)).getString("name"));
} }
json.put("data",data); return ApiResponseData.success(data);
} catch (CustomException e) { } catch (CustomException e) {
json = e.getJson(); return e.getErrorResponseModel();
} catch (BadSqlGrammarException e) {
String uuid = UUID.randomUUID().toString();
logger.error(uuid,e);
json = createJSONError(10000,trt.trt("Error_executing_SQL_query"),(String)null, uuid);
} catch (Exception e) { } catch (Exception e) {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
logger.error(uuid,e); 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") @RequestMapping(value = "/set_settings",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @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) { 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() .build()
.parseClaimsJws(jwt_a); .parseClaimsJws(jwt_a);
} catch (Exception e) { } 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 проверить доступ для выполнения данной функции //TODO проверить доступ для выполнения данной функции
//Выполняем функцию //Выполняем функцию
@ -424,49 +414,56 @@ public class MainController implements ServletContextAware {
} }
return json.toString(); return json.toString();
} }
//------------------------------------------------------------------------------------------------------------------
@Operation( @Operation(
summary = "Get list of permissions", summary = "Get list of permissions",
description = "Get list of permissions for user by Access token", description = "Get list of permissions for user by Access token",
responses = { responses = {
@ApiResponse( @ApiResponse(
responseCode = "200", responseCode = "200",
description = "Успешный ответ", description = "Successful response",
content = @Content( content = @Content(
mediaType = "application/json", mediaType = "application/json",
schema = @Schema(implementation = ApiResponseData.class) 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 @ResponseBody
public <T> ApiResponseData<T> access( public ResponseEntity<Object> access(
Model model, Model model,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@Nullable @RequestBody ActionNameModel action_name, @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); Translation trt = new Translation(language_id, jdbcTemplate);
ApiResponseData<List<String>> result = null;
try { try {
if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) 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);
return ApiResponseData.error(10000, trt.trt("Please_log_in"),null,null);
} }
//Проверяю подпись токена
Jws<Claims> claims = null; Jws<Claims> claims;
try { try {
claims = Jwts.parserBuilder() claims = Jwts.parserBuilder()
.setSigningKey(getPublicKey()) .setSigningKey(getPublicKey())
.build() .build()
.parseClaimsJws(jwt_a); .parseClaimsJws(jwt_a);
} catch (Exception e) { } 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 select
name name1
from from
main.get_access_list(:user_id) main.get_access_list(:user_id)
where where
@ -475,28 +472,30 @@ public class MainController implements ServletContextAware {
order by name order by name
"""; """;
MapSqlParameterSource parameters = new MapSqlParameterSource(); MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("user_id", claims.getBody().get("user_id")); parameters.addValue("user_id", claims.getBody().get("user_id"));
if(action_name == null) if (action_name == null) {
parameters.addValue("action_name", null); parameters.addValue("action_name", null);
else } else {
parameters.addValue("action_name", action_name.getAction_name()); parameters.addValue("action_name", action_name.getAction_name());
}
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
List<String> data = new ArrayList<>(); List<String> data = new ArrayList<>();
for (String s : ret) { for (String s : ret) {
data.add((new JSONObject(s)).getString("name")); data.add((new JSONObject(s)).getString("name"));
} }
result = ApiResponseData.success(data);
return new ResponseEntity<>(ApiResponseData.success(data), HttpStatus.OK);
} 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 ApiResponseData.error(10000, trt.trt("Internal_Server_Error"),(String)null,uuid); return new ResponseEntity<>(new ErrorResponseModel(10000, trt.trt("Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
} }
return (ApiResponseData<T>) 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 @ResponseBody
public String captcha(Model model, @RequestBody EmailModel email_model, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { 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); Translation trt = new Translation(language_id,jdbcTemplate);
@ -547,8 +546,9 @@ public class MainController implements ServletContextAware {
} }
return json.toString(); 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 @ResponseBody
public String create(@RequestBody NewUserModel newUserModel,@RequestParam(required=false,name="lng",defaultValue="1") String language_id) { public String create(@RequestBody NewUserModel newUserModel,@RequestParam(required=false,name="lng",defaultValue="1") String language_id) {
Translation trt = new Translation(language_id,jdbcTemplate); Translation trt = new Translation(language_id,jdbcTemplate);
@ -681,7 +681,8 @@ public class MainController implements ServletContextAware {
} }
return json.toString(); return json.toString();
} }
//------------------------------------------------------------------------------------------------------------------
@Operation(summary = "Get user account information", description = "")
@RequestMapping(value = "/info",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @RequestMapping(value = "/info",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
public String info(Model model, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @CookieValue(value = "lng",defaultValue="1") String language_id) { 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() .build()
.parseClaimsJws(jwt_a); .parseClaimsJws(jwt_a);
} catch (Exception e) { } 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 также и при логине) //Выбираю данные о пользователе (TODO наверно стоит вызывать функцию get_user_info также и при логине)
@ -749,7 +750,7 @@ public class MainController implements ServletContextAware {
} }
return json.toString(); return json.toString();
} }
//------------------------------------------------------------------------------------------------------------------
@Operation(summary = "Login and get JWT token", description = "Login and get JWT token") @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") @RequestMapping(value = "/login",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
@ -1026,7 +1027,7 @@ public class MainController implements ServletContextAware {
} }
return json.toString(); return json.toString();
} }
//------------------------------------------------------------------------------------------------------------------
Map<String, Integer> userIsBlocked(Translation trt, String login,String ip) throws CustomException { Map<String, Integer> userIsBlocked(Translation trt, String login,String ip) throws CustomException {
int attempt_count=0, attempt_limit=0;//, attempt_duration=0; int attempt_count=0, attempt_limit=0;//, attempt_duration=0;
MapSqlParameterSource parameters = null; MapSqlParameterSource parameters = null;
@ -1068,9 +1069,8 @@ public class MainController implements ServletContextAware {
result.put("attempt_limit", attempt_limit); result.put("attempt_limit", attempt_limit);
return result; return result;
} }
//------------------------------------------------------------------------------------------------------------------
//Функция для генерации нового 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!")
//Если это первое получение TOTP, то старый TOTP не нужен если последующее, то нужен!
@RequestMapping(value = "/newtotp",method = {RequestMethod.POST},produces = "application/json;charset=utf-8") @RequestMapping(value = "/newtotp",method = {RequestMethod.POST},produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
public String newtotp(HttpServletRequest request, @RequestBody LoginModel loginModel, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { 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(); return json.toString();
} }
//------------------------------------------------------------------------------------------------------------------
@RequestMapping(value = "/logout",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @RequestMapping(value = "/logout",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
public String logout(HttpServletResponse response,HttpServletRequest request) { public String logout(HttpServletResponse response,HttpServletRequest request) {
@ -1241,7 +1241,7 @@ public class MainController implements ServletContextAware {
return createStrJSONError(0,"",(String)null,(String)null); return createStrJSONError(0,"",(String)null,(String)null);
} }
//------------------------------------------------------------------------------------------------------------------
//Update refresh token //Update refresh token
@RequestMapping(value = "/refresh",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8") @RequestMapping(value = "/refresh",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
@ -1278,7 +1278,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, 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(); return json.toString();
} }
//------------------------------------------------------------------------------------------------------------------
@RequestMapping(value = "/reset",method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html;charset=utf-8") @RequestMapping(value = "/reset",method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html;charset=utf-8")
@ResponseBody @ResponseBody
public String reset(@RequestParam(required=false,name="token",defaultValue = "") String token,@RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { 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")); 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") @RequestMapping(value = "/restore",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
public String restore(Model model, @RequestBody RestoreModel restore, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) { 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); 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") @RequestMapping(value = "/update",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @ResponseBody
public String update(HttpServletRequest request, @RequestBody UpdateModel update, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) { public String update(HttpServletRequest request, @RequestBody UpdateModel update, @RequestParam(required=false,name="lng",defaultValue="1") String language_id) {
@ -1594,28 +1594,47 @@ public class MainController implements ServletContextAware {
} }
return json.toString(); 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") @RequestMapping(value = "/alive",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody @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<Object> 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); Translation trt = new Translation(language_id,jdbcTemplate);
try {
if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2) if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2)
{ {
return createStrJSONError(10000,trt.trt("Please_log_in"),(String)null,(String)null); throw new CustomException(10000, Collections.singletonList(trt.trt("Please_log_in")),null);
} }
//Connection conn = getConnection();
//Checking the token signature //Checking the token signature
Jws<Claims> claims = null; Jws<Claims> claims = null;
//SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256");
try { try {
claims = Jwts.parserBuilder() claims = Jwts.parserBuilder()
.setSigningKey(getPublicKey()) //.setSigningKey(key_a) .setSigningKey(getPublicKey()) //.setSigningKey(key_a)
.build() .build()
.parseClaimsJws(jwt_a); .parseClaimsJws(jwt_a);
} catch (Exception e) { } catch (Exception e) {
return createStrJSONError(10000, trt.trt("JWT_token_verification_error"),(String)null,(String)null); 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 //If this is a repeat authorization, then we inform the client about it
String result=null; String result=null;
@ -1623,20 +1642,20 @@ public class MainController implements ServletContextAware {
cache.open(); cache.open();
String data = cache.get(claims.getSignature()); String data = cache.get(claims.getSignature());
if (data != null) { 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);
}
} catch (Exception e) {
logger.error("An error occurred", e);
e.printStackTrace();
}
if(result!=null)
{
logout(response,request); logout(response,request);
return result; 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);
return createStrJSONError(0,"",(String)null,(String)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) {
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 {
}
} }
} }

View File

@ -13,5 +13,4 @@ public class ActionNameModel {
@Schema(description = "Action name", example = "arm_") @Schema(description = "Action name", example = "arm_")
@JsonProperty("action_name") @JsonProperty("action_name")
private String action_name; private String action_name;
} }

View File

@ -1,87 +1,44 @@
package org.ccalm.jwt.models; package org.ccalm.jwt.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Schema( @Schema(
description = "Стандартный ответ API", description = "Standard API response",
example = "{ \"error_code\": 0, \"error_message\": \"\", \"data\": [\"arm_accounting\",\"arm_carrier\",\"arm_hr\"] }" example = "{ \"error_code\": 0, \"error_message\": \"\", \"data\": [\"arm_accounting\",\"arm_carrier\",\"arm_hr\"] }"
) )
public class ApiResponseData<T> { public class ApiResponseData<T> {
@Schema(description = "Код ошибки", example = "0") @Schema(description = "Error code", example = "0")
@JsonProperty("error_code")
private int errorCode; private int errorCode;
@Schema(description = "Сообщение об ошибке", example = "") @Setter
private String errorMessage; @Getter
@Schema(description = "Data")
private List<String> data;
@Schema(description = "Параметры для переводимого текста", example = "") public ApiResponseData(List<String> data) {
private String errorSetting; errorCode = 0;
@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;
this.data = data; this.data = data;
} }
public static <T> ApiResponseData<T> success(T data) { public static ApiResponseData success(List<String> data) {
return new ApiResponseData<>(0, "","","", data); return new ApiResponseData(data);
} }
public static <T> ApiResponseData<T> error(int code, String message, String setting, String marker) { public int getError_code() {
return new ApiResponseData<>(code, message, setting, marker, null);
}
// Геттеры и сеттеры
public int getErrorCode() {
return errorCode; return errorCode;
} }
public void setErrorCode(int errorCode) { public void setError_code(int errorCode) {
this.errorCode = 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;
}
} }

View File

@ -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<String> errorMessage;
@Schema(description = "Options for translated text", example = "[\"99;day\",\"1;2\"]")
@JsonProperty("error_setting")
private List<String> 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<String> 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<String> errorMessage, List<String> 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<String> getError_message() {
return errorMessage;
}
public void setError_message(List<String> errorMessage) {
this.errorMessage = errorMessage;
}
public void setError_setting(List<String> errorSetting) {
this.errorSetting = errorSetting;
}
public List<String> getError_setting() {
return errorSetting;
}
public void setError_marker(String errorMarker) {
this.errorMarker = errorMarker;
}
public String getError_marker() {
return errorMarker;
}
}

View File

@ -2,63 +2,56 @@ package org.ccalm.jwt.tools;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 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.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class CustomException extends Exception { public class CustomException extends Exception {
private static final Logger logger = LogManager.getLogger(CustomException.class); private static final Logger logger = LogManager.getLogger(CustomException.class);
private int errorCode;
private String marker; private ErrorResponseModel error;
private List<String> errorMessages;
private List<String> errorSettings;
public CustomException(int errorCode, String errorMessage, String marker) { public CustomException(int errorCode, String errorMessage, String marker) {
super(errorMessage); super(errorMessage);
this.errorMessages = Arrays.asList(errorMessage); error = new ErrorResponseModel(errorCode, errorMessage, marker);
this.errorCode = errorCode;
this.marker = marker;
} }
public CustomException(int errorCode, String errorMessage, String errorSetting, String marker) { public CustomException(int errorCode, String errorMessage, String errorSetting, String marker) {
super(errorMessage); super(errorMessage);
this.errorMessages = Arrays.asList(errorMessage); error = new ErrorResponseModel(errorCode, errorMessage, errorSetting, marker);
this.errorSettings = Arrays.asList(errorSetting);
this.errorCode = errorCode;
this.marker = marker;
} }
public CustomException(int errorCode, List<String> errorMessages, String marker) { public CustomException(int errorCode, List<String> errorMessages, String marker) {
super(String.join(" ", errorMessages)); super(String.join(" ", errorMessages));
this.errorMessages = errorMessages; error = new ErrorResponseModel(errorCode, errorMessages, marker);
this.errorCode = errorCode;
this.marker = marker;
} }
public CustomException(int errorCode, List<String> errorMessages, List<String> errorSettings, String marker) { public CustomException(int errorCode, List<String> errorMessages, List<String> errorSettings, String marker) {
super(String.join(" ", errorMessages)); super(String.join(" ", errorMessages));
this.errorMessages = errorMessages; error = new ErrorResponseModel(errorCode, errorMessages, errorSettings, marker);
this.errorSettings = errorSettings;
this.errorCode = errorCode;
this.marker = marker;
} }
public int getErrorCode() { public int getErrorCode() {
return this.errorCode; return error.getError_code();
} }
public String getErrorMarker() { public String getErrorMarker() {
return this.marker; return error.getError_marker();
} }
public List<String> getErrorMessages() { public List<String> getErrorMessages() {
return this.errorMessages; return error.getError_message();
} }
public List<String> getErrorSettings() { public List<String> getErrorSettings() {
return this.errorSettings; return error.getError_setting();
} }
public JSONObject getJson() { public JSONObject getJson() {
@ -73,4 +66,8 @@ public class CustomException extends Exception {
} }
return json; return json;
} }
public ErrorResponseModel getErrorResponseModel() {
return error;
}
} }