Первый
This commit is contained in:
20
src/main/java/org/ccalm/jwt/JwtApplication.java
Normal file
20
src/main/java/org/ccalm/jwt/JwtApplication.java
Normal file
@ -0,0 +1,20 @@
|
||||
package org.ccalm.jwt;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = {"org.ccalm.jwt"})
|
||||
public class JwtApplication {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(JwtApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.info("Start JwtApplication");
|
||||
SpringApplication.run(JwtApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
1478
src/main/java/org/ccalm/jwt/MainController.java
Normal file
1478
src/main/java/org/ccalm/jwt/MainController.java
Normal file
File diff suppressed because it is too large
Load Diff
60
src/main/java/org/ccalm/jwt/Translation.java
Normal file
60
src/main/java/org/ccalm/jwt/Translation.java
Normal file
@ -0,0 +1,60 @@
|
||||
package org.ccalm.jwt;
|
||||
|
||||
import org.ccalm.jwt.tools.DBTools;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Translation {
|
||||
public int language_id;
|
||||
public NamedParameterJdbcTemplate jdbcTemplate;
|
||||
Translation(String lng, NamedParameterJdbcTemplate jdbcTemplate){
|
||||
language_id=1;
|
||||
switch (lng) {
|
||||
case "kz":
|
||||
case "kk":
|
||||
language_id = 2;
|
||||
break;
|
||||
case "en":
|
||||
language_id = 3;
|
||||
break;
|
||||
case "uz":
|
||||
language_id = 4;
|
||||
break;
|
||||
case "ru":
|
||||
default:
|
||||
language_id = 1;
|
||||
break;
|
||||
}
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
String trt(String text){
|
||||
String sql = """
|
||||
select
|
||||
translation
|
||||
from
|
||||
main._translations
|
||||
where
|
||||
del=false
|
||||
and language_id=:language_id
|
||||
and identifier=:identifier;
|
||||
""";
|
||||
MapSqlParameterSource parameters = new MapSqlParameterSource();
|
||||
parameters.addValue("language_id", language_id);
|
||||
parameters.addValue("identifier", text);
|
||||
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||
int i = 0;
|
||||
for (i = 0; i < ret.size(); i++) {
|
||||
JSONObject json = new JSONObject(ret.get(i));
|
||||
text = json.getString("translation");
|
||||
}
|
||||
if(i==0){
|
||||
text = text.replace("_", " ");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
16
src/main/java/org/ccalm/jwt/models/ActionName.java
Normal file
16
src/main/java/org/ccalm/jwt/models/ActionName.java
Normal file
@ -0,0 +1,16 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
14
src/main/java/org/ccalm/jwt/models/EmailModel.java
Normal file
14
src/main/java/org/ccalm/jwt/models/EmailModel.java
Normal file
@ -0,0 +1,14 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class EmailModel {
|
||||
@JsonProperty("email")
|
||||
String email;
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
}
|
||||
19
src/main/java/org/ccalm/jwt/models/ErrorModel.java
Normal file
19
src/main/java/org/ccalm/jwt/models/ErrorModel.java
Normal file
@ -0,0 +1,19 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class ErrorModel {
|
||||
@JsonProperty("timestamp")
|
||||
private String timestamp;
|
||||
|
||||
@JsonProperty("status")
|
||||
private int status;
|
||||
|
||||
@JsonProperty("error")
|
||||
private String error;
|
||||
|
||||
@JsonProperty("path")
|
||||
private String path;
|
||||
|
||||
// Конструктор, геттеры и сеттеры
|
||||
}
|
||||
36
src/main/java/org/ccalm/jwt/models/LoginModel.java
Normal file
36
src/main/java/org/ccalm/jwt/models/LoginModel.java
Normal file
@ -0,0 +1,36 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
public class LoginModel {
|
||||
//@JsonProperty("login")
|
||||
private String login;
|
||||
//@JsonProperty("password")
|
||||
private String password;
|
||||
//@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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
47
src/main/java/org/ccalm/jwt/models/NewUserModel.java
Normal file
47
src/main/java/org/ccalm/jwt/models/NewUserModel.java
Normal file
@ -0,0 +1,47 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class NewUserModel {
|
||||
|
||||
@JsonProperty("name")
|
||||
private String name;
|
||||
@JsonProperty("email")
|
||||
private String email;
|
||||
@JsonProperty("code")
|
||||
private String code;
|
||||
@JsonProperty("token")
|
||||
private String token;
|
||||
|
||||
public String getName() {
|
||||
if(name==null) return "";
|
||||
else return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
if(email==null) return "";
|
||||
else return email;
|
||||
}
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
if(code==null) return "";
|
||||
else return code;
|
||||
}
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
if(token==null) return "";
|
||||
else return token;
|
||||
}
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
}
|
||||
25
src/main/java/org/ccalm/jwt/models/RestoreModel.java
Normal file
25
src/main/java/org/ccalm/jwt/models/RestoreModel.java
Normal file
@ -0,0 +1,25 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
28
src/main/java/org/ccalm/jwt/models/SettingModel.java
Normal file
28
src/main/java/org/ccalm/jwt/models/SettingModel.java
Normal file
@ -0,0 +1,28 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
42
src/main/java/org/ccalm/jwt/models/UpdateModel.java
Normal file
42
src/main/java/org/ccalm/jwt/models/UpdateModel.java
Normal file
@ -0,0 +1,42 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class UpdateModel {
|
||||
|
||||
@JsonProperty("login")
|
||||
private String login;
|
||||
@JsonProperty("password")
|
||||
private String password;
|
||||
@JsonProperty("password_new")
|
||||
private String passwordNew;
|
||||
|
||||
// Геттеры и сеттеры для полей
|
||||
|
||||
public String getLogin() {
|
||||
if(login==null) return "";
|
||||
else return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
if(password==null) return "";
|
||||
else return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPasswordNew() {
|
||||
if(passwordNew==null) return "";
|
||||
else return passwordNew;
|
||||
}
|
||||
|
||||
public void setPasswordNew(String passwordNew) {
|
||||
this.passwordNew = passwordNew;
|
||||
}
|
||||
}
|
||||
96
src/main/java/org/ccalm/jwt/models/UserModel.java
Normal file
96
src/main/java/org/ccalm/jwt/models/UserModel.java
Normal file
@ -0,0 +1,96 @@
|
||||
package org.ccalm.jwt.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class UserModel {
|
||||
@JsonProperty("country_id")
|
||||
private Long countryId;
|
||||
@JsonProperty("company_name")
|
||||
private String companyName;
|
||||
@JsonProperty("position")
|
||||
private String position;
|
||||
@JsonProperty("name")
|
||||
private String name;
|
||||
@JsonProperty("surname")
|
||||
private String surname;
|
||||
@JsonProperty("patronymic")
|
||||
private String patronymic;
|
||||
@JsonProperty("phone")
|
||||
private String phone;
|
||||
@JsonProperty("email")
|
||||
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;
|
||||
}
|
||||
}
|
||||
63
src/main/java/org/ccalm/jwt/tools/Cache.java
Normal file
63
src/main/java/org/ccalm/jwt/tools/Cache.java
Normal file
@ -0,0 +1,63 @@
|
||||
package org.ccalm.jwt.tools;
|
||||
|
||||
import org.ccalm.jwt.MainController;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import redis.clients.jedis.Jedis;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
|
||||
|
||||
public class Cache implements AutoCloseable {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(Cache.class);
|
||||
private Jedis jedis = null;
|
||||
|
||||
String host = null;
|
||||
int port = 0;
|
||||
String password = null;
|
||||
|
||||
public Cache(String host,int port,String password) {
|
||||
this.host=host;
|
||||
this.port=port;
|
||||
this.password=password;
|
||||
}
|
||||
|
||||
public boolean open(){
|
||||
try {
|
||||
jedis = new Jedis(host, port);
|
||||
jedis.auth(password);
|
||||
}catch (Exception e)
|
||||
{
|
||||
logger.error(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
if(jedis!=null)
|
||||
jedis.close();
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
return jedis.get(key);
|
||||
}
|
||||
|
||||
public boolean set(String key,String data,int ttl){
|
||||
jedis.set(key, data);
|
||||
long currentTimeMillis = System.currentTimeMillis();
|
||||
long expireTimeMillis = currentTimeMillis + ttl * 1000;
|
||||
jedis.expireAt(key, expireTimeMillis / 1000);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void delete(String key) {
|
||||
jedis.del(key.getBytes());
|
||||
}
|
||||
}
|
||||
30
src/main/java/org/ccalm/jwt/tools/CustomException.java
Normal file
30
src/main/java/org/ccalm/jwt/tools/CustomException.java
Normal file
@ -0,0 +1,30 @@
|
||||
package org.ccalm.jwt.tools;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class CustomException extends Exception {
|
||||
private int errorCode;
|
||||
private String marker;
|
||||
|
||||
public CustomException(int errorCode,String message,String marker) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
this.marker = marker;
|
||||
}
|
||||
|
||||
public int getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public String getErrorMarker() {
|
||||
return marker;
|
||||
}
|
||||
|
||||
public JSONObject getJson() {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("error_code", getErrorCode());
|
||||
json.put("error_message", getMessage());
|
||||
json.put("error_marker", getErrorMarker());
|
||||
return json;
|
||||
}
|
||||
}
|
||||
40
src/main/java/org/ccalm/jwt/tools/DBTools.java
Normal file
40
src/main/java/org/ccalm/jwt/tools/DBTools.java
Normal file
@ -0,0 +1,40 @@
|
||||
package org.ccalm.jwt.tools;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class DBTools {
|
||||
|
||||
public static class JsonRowMapper implements RowMapper<String> {
|
||||
|
||||
@Override
|
||||
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> resultMap = new HashMap<>();
|
||||
|
||||
// Получаем метаданные ResultSet для получения названий столбцов
|
||||
int columnCount = rs.getMetaData().getColumnCount();
|
||||
for (int i = 1; i <= columnCount; i++) {
|
||||
String columnName = rs.getMetaData().getColumnName(i);
|
||||
Object columnValue = rs.getObject(i);
|
||||
resultMap.put(columnName, columnValue);
|
||||
}
|
||||
|
||||
// Преобразовываем Map в JSON строку
|
||||
try {
|
||||
return objectMapper.writeValueAsString(resultMap);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to convert Map to JSON", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
65
src/main/java/org/ccalm/jwt/tools/EmailUtility.java
Normal file
65
src/main/java/org/ccalm/jwt/tools/EmailUtility.java
Normal file
@ -0,0 +1,65 @@
|
||||
//From: http://www.codejava.net/java-ee/jsp/sending-e-mail-with-jsp-servlet-and-javamail
|
||||
package org.ccalm.jwt.tools;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.mail.Authenticator;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.PasswordAuthentication;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.AddressException;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
|
||||
/**
|
||||
* A utility class for sending e-mail messages
|
||||
* @author www.codejava.net
|
||||
*
|
||||
*/
|
||||
public class EmailUtility {
|
||||
|
||||
public static void sendEmail(String host, String port,
|
||||
final String userName, final String password, String toAddress,
|
||||
String subject, String message) throws AddressException,
|
||||
MessagingException
|
||||
{
|
||||
// sets SMTP server properties
|
||||
Properties properties = new Properties();
|
||||
|
||||
properties.put("mail.smtp.host", host);
|
||||
properties.put("mail.smtp.port", port);
|
||||
properties.put("mail.smtp.auth", "true");
|
||||
//properties.put("mail.smtp.starttls.enable","true"); STARTTLS requested but already using SSL
|
||||
properties.put("mail.smtp.EnableSSL.enable","true");
|
||||
properties.put("mail.smtp.socketFactory.port", port);
|
||||
properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
|
||||
//properties.put("mail.debug", "true");
|
||||
|
||||
|
||||
// creates a new session with an authenticator
|
||||
Authenticator auth = new Authenticator() {
|
||||
public PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(userName, password);
|
||||
}
|
||||
};
|
||||
|
||||
Session session = Session.getInstance(properties, auth);
|
||||
|
||||
//creates a new e-mail message
|
||||
Message msg = new MimeMessage(session);
|
||||
|
||||
msg.setFrom(new InternetAddress(userName));
|
||||
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
|
||||
msg.setRecipients(Message.RecipientType.TO, toAddresses);
|
||||
msg.setSubject(subject);
|
||||
msg.setSentDate(new Date());
|
||||
//msg.setText(message);
|
||||
msg.setContent(message, "text/html; charset=utf-8");
|
||||
|
||||
// sends the e-mail
|
||||
Transport.send(msg);
|
||||
}
|
||||
}
|
||||
167
src/main/java/org/ccalm/jwt/tools/Storage.java
Normal file
167
src/main/java/org/ccalm/jwt/tools/Storage.java
Normal file
@ -0,0 +1,167 @@
|
||||
package org.ccalm.jwt.tools;
|
||||
|
||||
import org.ccalm.jwt.MainController;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
public class Storage implements AutoCloseable {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(Storage.class);
|
||||
private Connection conn = null;
|
||||
|
||||
public Storage(){
|
||||
String url = "jdbc:sqlite:temporary.sqlite";
|
||||
try {
|
||||
conn = DriverManager.getConnection(url);
|
||||
Statement stmt = conn.createStatement();
|
||||
String sql= """
|
||||
CREATE TABLE IF NOT EXISTS _users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT NOT NULL, --Email пользователя
|
||||
key TEXT NOT NULL, --Ключ для токена обновления (refresh token)
|
||||
jwt_r TEXT NOT NULL, --Сам ключ обновления
|
||||
jwt_a TEXT NOT NULL, --Сам ключ доступа
|
||||
time_r INTEGER, --Unix time в секундах, когда заканчивается токен обновления
|
||||
time_a INTEGER --Unix time в секундах, когда заканчивается токен доступа
|
||||
);
|
||||
""";
|
||||
stmt.execute(sql);
|
||||
stmt.close();
|
||||
} catch (SQLException e) {
|
||||
logger.error("Error connecting or executing SQL query in SQLite", e);
|
||||
}
|
||||
}
|
||||
|
||||
//Для выполнения: try-with-resources
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
if(conn!=null) {
|
||||
try {
|
||||
conn.close();
|
||||
conn=null;
|
||||
} catch (SQLException e) {
|
||||
logger.error("SQLite close error", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// В коде не надеюсь на finalize, использую try-with-resources из AutoCloseable
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
if(conn!=null) {
|
||||
try {
|
||||
conn.close();
|
||||
conn=null;
|
||||
} catch (SQLException e) {
|
||||
logger.error("SQLite close error", e);
|
||||
}
|
||||
}
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
//Получаю поля из базы email пользователя
|
||||
public JSONObject getJWT(String email){
|
||||
JSONObject result = new JSONObject();
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM _users WHERE email=?");
|
||||
pstmt.setString(1, email);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (rs.next()) {
|
||||
result.put("id", rs.getInt("id"));
|
||||
result.put("email", rs.getString("email"));
|
||||
result.put("key", rs.getString("key"));
|
||||
result.put("jwt_r", rs.getString("jwt_r"));
|
||||
result.put("jwt_a", rs.getString("jwt_a"));
|
||||
result.put("time_r", rs.getLong("time_r"));
|
||||
result.put("time_a", rs.getLong("time_a"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.error("An error occurred", e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//Сохранить либо обновить Refresh токен
|
||||
public boolean setJWT(String email,String key,String jwt_r,String jwt_a,long time_r,long time_a){
|
||||
try {
|
||||
// Проверка существует ли запись с данным email
|
||||
PreparedStatement selectStmt = conn.prepareStatement("SELECT * FROM _users WHERE email=?");
|
||||
selectStmt.setString(1, email);
|
||||
ResultSet rs = selectStmt.executeQuery();
|
||||
boolean exists = rs.next();
|
||||
selectStmt.close();
|
||||
if (exists) {
|
||||
String updateSql = "UPDATE _users SET key=?, jwt_r=?, jwt_a=?, time_r=?, time_a=? WHERE email=?";
|
||||
PreparedStatement updateStmt = conn.prepareStatement(updateSql);
|
||||
updateStmt.setString(1, key);
|
||||
updateStmt.setString(2, jwt_r);
|
||||
updateStmt.setString(3, jwt_a);
|
||||
updateStmt.setLong(4, time_r); // Время в секундах
|
||||
updateStmt.setLong(5, time_a); // Время в секундах
|
||||
updateStmt.setString(6, email);
|
||||
updateStmt.executeUpdate();
|
||||
updateStmt.close();
|
||||
} else {
|
||||
String insertSql = "INSERT INTO _users(email, key, jwt_r, jwt_a, time_r, time_a) VALUES (?, ?, ?, ?, ?, ?)";
|
||||
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
|
||||
insertStmt.setString(1, email);
|
||||
insertStmt.setString(2, key);
|
||||
insertStmt.setString(3, jwt_r);
|
||||
insertStmt.setString(4, jwt_a);
|
||||
insertStmt.setLong(5, time_r); // Время в секундах
|
||||
insertStmt.setLong(6, time_a); // Время в секундах
|
||||
insertStmt.executeUpdate();
|
||||
insertStmt.close();
|
||||
}
|
||||
return true;
|
||||
} catch (SQLException e) {
|
||||
logger.error("SQLite query execution error", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
//Получаю пароль для токена обновления из базы
|
||||
public String getKey(String email){
|
||||
String key="";
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT key FROM _users WHERE email=?");
|
||||
pstmt.setString(1, email);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (rs.next()) {
|
||||
key = rs.getString("key");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.error("SQLite query execution error", e);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
//Получаю время когда Refresh token "протухнет"
|
||||
public long getTime(String email){
|
||||
long time = 1;
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT time_r FROM _users WHERE email=?");
|
||||
pstmt.setString(1, email);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (rs.next()) {
|
||||
time = rs.getLong("time_r");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.error("SQLite query execution error", e);
|
||||
}
|
||||
return time;
|
||||
}
|
||||
//Удалить токен обновления из базы данных
|
||||
public boolean delToken(String email){
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("DELETE FROM _users WHERE email=?");
|
||||
pstmt.setString(1, email);
|
||||
pstmt.executeUpdate();
|
||||
return true;
|
||||
} catch (SQLException e) {
|
||||
logger.error("SQLite query execution error", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
148
src/main/java/org/ccalm/jwt/tools/Tools.java
Normal file
148
src/main/java/org/ccalm/jwt/tools/Tools.java
Normal file
@ -0,0 +1,148 @@
|
||||
package org.ccalm.jwt.tools;
|
||||
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import javax.crypto.*;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.util.Base64;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class Tools {
|
||||
|
||||
//Зашифровать
|
||||
public static String encryptText(String pass,String data){
|
||||
String encryptedBase64="";
|
||||
String encryptionIV = "jazz_tyt_net_111"; // Ваш вектор инициализации
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
|
||||
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(pass), "AES");
|
||||
IvParameterSpec iv = new IvParameterSpec(encryptionIV.getBytes()); // Создание объекта IvParameterSpec для вектора инициализации
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, iv); // Инициализация шифра с ключом и вектором инициализации
|
||||
byte[] encrypted = cipher.doFinal(data.getBytes()); // Шифрование строки
|
||||
encryptedBase64 = Base64.getEncoder().encodeToString(encrypted); // Преобразование зашифрованных данных в base64
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (BadPaddingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return encryptedBase64;
|
||||
}
|
||||
|
||||
public static String decryptText(String pass,String data){
|
||||
String encryptionIV = "jazz_tyt_net_111"; // Ваш вектор инициализации
|
||||
String decryptedText= "";
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
|
||||
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(pass), "AES");
|
||||
IvParameterSpec iv = new IvParameterSpec(encryptionIV.getBytes()); // Создание объекта IvParameterSpec для вектора инициализации
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, iv); // Инициализация шифра с ключом и вектором инициализации
|
||||
|
||||
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data)); // Расшифровка данных
|
||||
decryptedText = new String(decrypted); // Преобразование расшифрованных данных в строку
|
||||
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
|
||||
InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return decryptedText;
|
||||
}
|
||||
|
||||
public static String generateSignature(String pass,String input) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(pass), "HmacSHA256");
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] encodedInput = digest.digest(input.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] encodedKey = secretKey.getEncoded();
|
||||
|
||||
// Создание HMAC-подписи
|
||||
javax.crypto.spec.SecretKeySpec keySpec = new javax.crypto.spec.SecretKeySpec(encodedKey, "HmacSHA256");
|
||||
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(keySpec);
|
||||
byte[] rawHmac = mac.doFinal(encodedInput);
|
||||
|
||||
// Кодирование подписи в base64
|
||||
return Base64.getEncoder().encodeToString(rawHmac);
|
||||
} catch (NoSuchAlgorithmException | java.security.InvalidKeyException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isValidEmail(String email) {
|
||||
String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
|
||||
Pattern pattern = Pattern.compile(EMAIL_REGEX);
|
||||
Matcher matcher = pattern.matcher(email);
|
||||
return matcher.matches();
|
||||
}
|
||||
|
||||
public static boolean isInteger(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Integer.parseInt(str);
|
||||
return true;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String genKey(){
|
||||
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
|
||||
byte[] keyBytes = key.getEncoded();
|
||||
return Base64.getEncoder().encodeToString(keyBytes);
|
||||
}
|
||||
|
||||
public static String generatePassword(int length) {
|
||||
String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
SecureRandom random = new SecureRandom();
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int randomIndex = random.nextInt(CHARACTERS.length());
|
||||
sb.append(CHARACTERS.charAt(randomIndex));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// Метод для извлечения подписи из JWT токена
|
||||
public static String extractSignature(String jwtToken) {
|
||||
String[] jwtParts = jwtToken.split("\\.");
|
||||
if (jwtParts.length != 3) {
|
||||
return null;
|
||||
}
|
||||
return jwtParts[2];
|
||||
}
|
||||
|
||||
//Для извлечения содержимого токена
|
||||
public static JSONObject extractToken(String jwtToken) {
|
||||
String[] jwtParts = jwtToken.split("\\.");
|
||||
if (jwtParts.length != 3) {
|
||||
return null;
|
||||
}
|
||||
String payloadJson = new String(Base64.getUrlDecoder().decode(jwtParts[1]));
|
||||
JSONObject payload=null;
|
||||
try {
|
||||
payload = new JSONObject(payloadJson);
|
||||
} catch (JSONException e) {
|
||||
return null;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
33
src/main/resources/logback-spring.xml
Normal file
33
src/main/resources/logback-spring.xml
Normal file
@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<!-- Please check if the user has access to the directory from which the application is being executed -->
|
||||
<property name="LOGS" value="logs" />
|
||||
<springProperty scope="context" name="appName" source="spring.application.name"/>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOGS}/${appName}.log</file>
|
||||
<encoder>
|
||||
<pattern>{"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","marker":"%X{marker}","message":"%msg"}%n</pattern>
|
||||
</encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<maxFileSize>100MB</maxFileSize>
|
||||
</timeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'} | %level | %logger{36} | %X{marker} | %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="FILE" />
|
||||
<appender-ref ref="CONSOLE" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
13
src/test/java/com/geovizor/jwt/JwtApplicationTests.java
Normal file
13
src/test/java/com/geovizor/jwt/JwtApplicationTests.java
Normal file
@ -0,0 +1,13 @@
|
||||
package org.ccalm.jwt;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class JwtApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user