Добавил запрос проверить есть ли в системе такой пользователь и получить его данные.

И тесты добавил.

Все тесты проходят
This commit is contained in:
AidarKC
2026-01-28 20:33:06 +03:00
parent 43b0efb4d3
commit ebf7c9f18e
13 changed files with 621 additions and 67 deletions
@@ -28,6 +28,9 @@ import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_R
import server.logic.ws_protocol.JSON.handlers.tempToTest.Net_AddUser_Handler;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_AddUser_Request;
import server.logic.ws_protocol.JSON.handlers.tempToTest.Net_GetUser_Handler;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_GetUser_Request;
import server.logic.ws_protocol.JSON.handlers.userParams.Net_GetUserParam_Handler;
import server.logic.ws_protocol.JSON.handlers.userParams.Net_ListUserParams_Handler;
import server.logic.ws_protocol.JSON.handlers.userParams.Net_UpsertUserParam_Handler;
@@ -50,6 +53,7 @@ public final class JsonHandlerRegistry {
// Map.of(...) поддерживает максимум 10 пар => используем Map.ofEntries(...)
private static final Map<String, JsonMessageHandler> HANDLERS = Map.ofEntries(
Map.entry("AddUser", new Net_AddUser_Handler()),
Map.entry("GetUser", new Net_GetUser_Handler()),
// --- auth ---
Map.entry("AuthChallenge", new Net_AuthChallenge_Handler()),
@@ -75,6 +79,7 @@ public final class JsonHandlerRegistry {
private static final Map<String, Class<? extends Net_Request>> REQUEST_TYPES = Map.ofEntries(
Map.entry("AddUser", Net_AddUser_Request.class),
Map.entry("GetUser", Net_GetUser_Request.class),
// --- auth ---
Map.entry("AuthChallenge", Net_AuthChallenge_Request.class),
@@ -61,6 +61,17 @@ public class Net_AddUser_Handler implements JsonMessageHandler {
: req.getBchLimit();
try {
// базовая валидация форматов ключей: Base64(32 bytes)
byte[] solanaKey32 = Base64.getDecoder().decode(req.getSolanaKey());
if (solanaKey32.length != 32) {
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.BAD_REQUEST,
"BAD_SOLANA_KEY",
"solanaKey должен быть Base64(32 bytes)"
);
}
byte[] blockchainKey32 = Base64.getDecoder().decode(req.getBlockchainKey());
if (blockchainKey32.length != 32) {
return NetExceptionResponseFactory.error(
@@ -71,6 +82,16 @@ public class Net_AddUser_Handler implements JsonMessageHandler {
);
}
byte[] deviceKey32 = Base64.getDecoder().decode(req.getDeviceKey());
if (deviceKey32.length != 32) {
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.BAD_REQUEST,
"BAD_DEVICE_KEY",
"deviceKey должен быть Base64(32 bytes)"
);
}
SolanaUsersDAO usersDAO = SolanaUsersDAO.getInstance();
BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
@@ -79,8 +100,8 @@ public class Net_AddUser_Handler implements JsonMessageHandler {
try (Connection c = db.getConnection()) {
c.setAutoCommit(false);
// 1. Проверяем, что пользователя нет
if (usersDAO.getByLogin(req.getLogin()) != null) {
// 1. Проверяем, что пользователя нет (case-insensitive)
if (usersDAO.getByLogin(c, req.getLogin()) != null) {
return NetExceptionResponseFactory.error(
req,
409,
@@ -89,26 +110,38 @@ public class Net_AddUser_Handler implements JsonMessageHandler {
);
}
// 2. Проверяем, что blockchain_state ещё нет
if (stateDAO.getByBlockchainName(req.getBlockchainName()) != null) {
// 2. Проверяем, что blockchainName ещё нет (case-sensitive, как в БД)
if (usersDAO.existsByBlockchainName(c, req.getBlockchainName())) {
return NetExceptionResponseFactory.error(
req,
409,
"BLOCKCHAIN_ALREADY_EXISTS",
"Пользователь с таким blockchainName уже существует"
);
}
// 3. На всякий случай оставляем старую проверку blockchain_state,
// потому что эта таблица нужна серверу (состояние цепочки/лимиты).
if (stateDAO.getByBlockchainName(c, req.getBlockchainName()) != null) {
return NetExceptionResponseFactory.error(
req,
409,
"BLOCKCHAIN_STATE_ALREADY_EXISTS",
"blockchain_state уже существует"
);
}
// 3. Создаём пользователя (solanaKey + deviceKey)
SolanaUserEntry user = new SolanaUserEntry(
req.getLogin(),
req.getSolanaKey(),
req.getDeviceKey()
);
// 4. Создаём пользователя (все поля теперь лежат в solana_users)
SolanaUserEntry user = new SolanaUserEntry();
user.setLogin(req.getLogin());
user.setBlockchainName(req.getBlockchainName());
user.setSolanaKey(req.getSolanaKey());
user.setBlockchainKey(req.getBlockchainKey());
user.setDeviceKey(req.getDeviceKey());
usersDAO.insert(c, user);
// 4. Создаём INITIAL blockchain_state (blockchainKey)
// 5. Создаём INITIAL blockchain_state (для работы сервера)
BlockchainStateEntry st = new BlockchainStateEntry();
st.setBlockchainName(req.getBlockchainName());
st.setLogin(req.getLogin());
@@ -0,0 +1,84 @@
package server.logic.ws_protocol.JSON.handlers.tempToTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_GetUser_Request;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_GetUser_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.SolanaUsersDAO;
import shine.db.entities.SolanaUserEntry;
import java.sql.SQLException;
public class Net_GetUser_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetUser_Handler.class);
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_GetUser_Request req = (Net_GetUser_Request) baseRequest;
if (req.getLogin() == null || req.getLogin().isBlank()) {
// тут логичнее BAD_REQUEST, но ты просил: "нет пользователя" тоже 200.
// Поэтому BAD_REQUEST оставляем только на реально пустой login.
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.BAD_REQUEST,
"BAD_FIELDS",
"Некорректные поля: login"
);
}
SolanaUsersDAO usersDAO = SolanaUsersDAO.getInstance();
try {
SolanaUserEntry u = usersDAO.getByLogin(req.getLogin());
Net_GetUser_Response resp = new Net_GetUser_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
if (u == null) {
resp.setExists(false);
log.info("️ GetUser: not found for login={}", req.getLogin());
return resp;
}
// ВАЖНО:
// - Поиск по login был case-insensitive,
// - а тут возвращаем login/blockchainName как в БД (с исходным регистром).
resp.setExists(true);
resp.setLogin(u.getLogin());
resp.setBlockchainName(u.getBlockchainName());
resp.setSolanaKey(u.getSolanaKey());
resp.setBlockchainKey(u.getBlockchainKey());
resp.setDeviceKey(u.getDeviceKey());
log.info("✅ GetUser: found login={}, blockchainName={}", u.getLogin(), u.getBlockchainName());
return resp;
} catch (SQLException e) {
log.error("❌ DB error GetUser", e);
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.SERVER_DATA_ERROR,
"DB_ERROR",
"Ошибка БД"
);
} catch (Exception e) {
log.error("❌ Internal error GetUser", e);
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.INTERNAL_ERROR,
"INTERNAL_ERROR",
"Внутренняя ошибка сервера"
);
}
}
}
@@ -1,3 +1,4 @@
// file: server/logic/ws_protocol/JSON/handlers/tempToTest/entyties/Net_AddUser_Response.java
package server.logic.ws_protocol.JSON.handlers.tempToTest.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
@@ -0,0 +1,27 @@
package server.logic.ws_protocol.JSON.handlers.tempToTest.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/**
* Запрос GetUser — проверка/получение пользователя по login.
*
* Клиент отправляет:
*
* {
* "op": "GetUser",
* "requestId": "u-1",
* "payload": {
* "login": "AnYa"
* }
* }
*
* Поиск по login выполняется без учёта регистра.
* В ответе возвращаем login/blockchainName с тем регистром, как в БД.
*/
public class Net_GetUser_Request extends Net_Request {
private String login;
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
}
@@ -0,0 +1,60 @@
package server.logic.ws_protocol.JSON.handlers.tempToTest.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
/**
* Ответ GetUser.
*
* Всегда status=200.
*
* Пример (нет пользователя):
* {
* "op": "GetUser",
* "requestId": "u-1",
* "status": 200,
* "payload": { "exists": false }
* }
*
* Пример (есть пользователь):
* {
* "op": "GetUser",
* "requestId": "u-1",
* "status": 200,
* "payload": {
* "exists": true,
* "login": "Anya",
* "blockchainName": "anya-001",
* "solanaKey": "...",
* "blockchainKey": "...",
* "deviceKey": "..."
* }
* }
*/
public class Net_GetUser_Response extends Net_Response {
private Boolean exists;
private String login;
private String blockchainName;
private String solanaKey;
private String blockchainKey;
private String deviceKey;
public Boolean getExists() { return exists; }
public void setExists(Boolean exists) { this.exists = exists; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getBlockchainName() { return blockchainName; }
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
public String getSolanaKey() { return solanaKey; }
public void setSolanaKey(String solanaKey) { this.solanaKey = solanaKey; }
public String getBlockchainKey() { return blockchainKey; }
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
public String getDeviceKey() { return deviceKey; }
public void setDeviceKey(String deviceKey) { this.deviceKey = deviceKey; }
}