!!!СВАГГЕР!!!

This commit is contained in:
Igor I
2025-01-31 19:51:24 +05:00
parent c374fb881e
commit e7d5085f94
17 changed files with 347 additions and 215 deletions

View File

@ -1,7 +1,7 @@
package org.ccalm.jwt;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ -10,7 +10,7 @@ import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"org.ccalm.jwt"})
public class JwtApplication {
private static final Logger logger = LogManager.getLogger(JwtApplication.class);
private static final Logger logger = LoggerFactory.getLogger(JwtApplication.class);
public static void main(String[] args) {
logger.info("Start JwtApplication");

View File

@ -1,14 +1,16 @@
package org.ccalm.jwt;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import org.ccalm.jwt.models.*;
import org.ccalm.jwt.tools.*;
import com.zaxxer.hikari.HikariDataSource;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.logicsquad.nanocaptcha.content.LatinContentProducer;
@ -20,10 +22,10 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Controller;
import org.springframework.lang.Nullable;
@ -36,16 +38,12 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.commons.text.RandomStringGenerator;
import redis.clients.jedis.Jedis;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import java.awt.*;
@ -53,14 +51,11 @@ import java.awt.image.BufferedImage;
import java.io.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.sql.*;
import java.sql.Date;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.io.InputStream;
import java.util.Properties;
@ -125,6 +120,7 @@ public class MainController implements ServletContextAware {
this.jdbcTemplate = jdbcTemplate;
}
//---------------------------------------------------------------------------
public String createStrJSONError(int code, String message, String setting, String marker) {
JSONObject json = new JSONObject();
try {
@ -137,24 +133,24 @@ public class MainController implements ServletContextAware {
}
return json.toString();
}
//---------------------------------------------------------------------------
public JSONObject createJSONError(int code, String message, String setting, String marker) {
JSONObject json = new JSONObject();
try {
json.put("error_code", code);
json.put("error_message", Arrays.asList(message));
json.put("error_setting", Arrays.asList(setting));
json.put("error_marker", Arrays.asList(setting));
json.put("error_marker", marker);
} catch (JSONException e) {
logger.error(e);
}
return json;
}
//---------------------------------------------------------------------------
public String createHTMLError(int code, String message) {
return "<!DOCTYPE html><html><head><meta http-equiv=\"refresh\" content=\"0; url='" + this.url_main + "?msg=" + message + "'\" /></head><body></body></html>";
}
//---------------------------------------------------------------------------
public static int countOccurrences(String str, char symbol) {
int count = 0;
@ -245,7 +241,6 @@ public class MainController implements ServletContextAware {
return true;
}
/**
* Create a Access Cookie
*/
@ -270,9 +265,10 @@ public class MainController implements ServletContextAware {
return true;
}
@RequestMapping(value = "/",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@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 String index(Model model,@RequestParam(required=false,name="lng",defaultValue = "1") String language_id) {
public ResponseEntity<String> index() {
JSONObject json = new JSONObject();
try {
json.put("error_code",0);
@ -299,13 +295,10 @@ public class MainController implements ServletContextAware {
} catch (JSONException e) {
throw new RuntimeException(e);
}
return json.toString();
return ResponseEntity.ok(json.toString());
}
/*
@RequestMapping(value = "/get_settings/",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ResponseBody
public String get_settings(Model model, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,@RequestBody ActionName action_name, @CookieValue(value = "lng", defaultValue = "1") String language_id) {
*/
@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")
@ResponseBody
public String get_settings(@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a, @RequestParam(required=false,name="lng",defaultValue = "1") String language_id) {
@ -432,30 +425,44 @@ public class MainController implements ServletContextAware {
return json.toString();
}
@RequestMapping(value = "/access",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@Operation(
summary = "Get list of permissions",
description = "Get list of permissions for user by Access token",
responses = {
@ApiResponse(
responseCode = "200",
description = "Успешный ответ",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ApiResponseData.class)
)
)
}
)
@RequestMapping(value = "/access",method = {RequestMethod.POST},produces = "application/json;charset=utf-8")
@ResponseBody
public String access(Model model, @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,@Nullable @RequestBody ActionName action_name,@CookieValue(value = "lng",defaultValue = "1") String language_id) {
public <T> ApiResponseData<T> access(
Model model,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@Nullable @RequestBody ActionNameModel action_name,
@CookieValue(value = "lng",defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
String result=createStrJSONError(10000,trt.trt("Request_not_processed"), (String)null, (String)null);
ApiResponseData<List<String>> result = null;
try {
if(jwt_a.equals("") || countOccurrences(jwt_a, '.')!=2)
{
result=createStrJSONError(10000,trt.trt("Please_log_in"), (String)null, (String)null);
return result;
return ApiResponseData.error(10000, trt.trt("Please_log_in"),null,null);
}
//Connection conn = getConnection();
//Проверяю подпись токена
Jws<Claims> claims = null;
//SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256");
try {
claims = Jwts.parserBuilder()
.setSigningKey(getPublicKey()) //.setSigningKey(key_a)
.setSigningKey(getPublicKey())
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
return createStrJSONError(10000, trt.trt("JWT_token_verification_error"),(String)null,(String)null);
return ApiResponseData.error(10000, trt.trt("JWT_token_verification_error"),null,null);
}
String sql = """
select
@ -474,24 +481,19 @@ public class MainController implements ServletContextAware {
if(action_name == null)
parameters.addValue("action_name", null);
else
parameters.addValue("action_name", action_name.getActionName());
parameters.addValue("action_name", action_name.getAction_name());
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
JSONObject json = new JSONObject();
json.put("error_code",0);
//json.put("error_message","");
//json.put("error_marker",(String)null);
JSONArray data = new JSONArray();
for (int i = 0; i < ret.size(); i++) {
data.put((new JSONObject(ret.get(i))).getString("name"));
List<String> data = new ArrayList<>();
for (String s : ret) {
data.add((new JSONObject(s)).getString("name"));
}
json.put("data",data);
result = json.toString();
result = ApiResponseData.success(data);
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(uuid,e);
result=createStrJSONError(10000,trt.trt("Internal_Server_Error"), (String)null, uuid);
return ApiResponseData.error(10000, trt.trt("Internal_Server_Error"),(String)null,uuid);
}
return result;
return (ApiResponseData<T>) result;
}
@RequestMapping(value = "/captcha",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@ -748,7 +750,8 @@ public class MainController implements ServletContextAware {
return json.toString();
}
@RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
@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) {

View File

@ -1,16 +0,0 @@
package org.ccalm.jwt.models;
//import jakarta.persistence.Column;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ActionName {
//@Column(name = "action_name", nullable = true)
@JsonProperty("action_name")
private String action_name;
public String getActionName() {
return action_name;
}
public void setActionName(String action_name) {
this.action_name = action_name;
}
}

View File

@ -0,0 +1,17 @@
package org.ccalm.jwt.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
@Schema(description = "Model for getting actions by name")
public class ActionNameModel {
@Schema(description = "Action name", example = "arm_")
@JsonProperty("action_name")
private String action_name;
}

View File

@ -0,0 +1,87 @@
package org.ccalm.jwt.models;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Arrays;
@Schema(
description = "Стандартный ответ API",
example = "{ \"error_code\": 0, \"error_message\": \"\", \"data\": [\"arm_accounting\", \"arm_carrier\", \"arm_hr\"] }"
)
public class ApiResponseData<T> {
@Schema(description = "Код ошибки", example = "0")
private int errorCode;
@Schema(description = "Сообщение об ошибке", example = "")
private String errorMessage;
@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;
this.data = data;
}
public static <T> ApiResponseData<T> success(T data) {
return new ApiResponseData<>(0, "","","", data);
}
public static <T> ApiResponseData<T> error(int code, String message, String setting, String marker) {
return new ApiResponseData<>(code, message, setting, marker, null);
}
// Геттеры и сеттеры
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(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;
}
}

View File

@ -1,14 +1,10 @@
package org.ccalm.jwt.models;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonProperty;
@Data
public class EmailModel {
@JsonProperty("email")
String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String email;
}

View File

@ -1,7 +1,9 @@
package org.ccalm.jwt.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class ErrorModel {
@JsonProperty("timestamp")
private String timestamp;

View File

@ -1,5 +1,8 @@
package org.ccalm.jwt.models;
import lombok.Data;
@Data
public class LoginModel {
//@JsonProperty("login")
private String login;
@ -8,29 +11,4 @@ public class LoginModel {
//@JsonProperty("appid")
private String totp;
private String appid;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTotp() { return totp; }
public void setTotp(String totp) {
this.totp = totp;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
}

View File

@ -1,25 +1,13 @@
package org.ccalm.jwt.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class RestoreModel {
@JsonProperty("code")
String code;
@JsonProperty("token")
String token;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

View File

@ -1,28 +1,13 @@
package org.ccalm.jwt.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class SettingModel {
@JsonProperty("identifier")
private String identifier;
@JsonProperty("value")
private String value;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

View File

@ -1,7 +1,9 @@
package org.ccalm.jwt.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class UserModel {
@JsonProperty("country_id")
private Long countryId;
@ -21,76 +23,4 @@ public class UserModel {
private String email;
@JsonProperty("password")
private String password;
public Long getCountryId() {
return countryId;
}
public void setCountryId(Long countryId) {
this.countryId = countryId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}