fix problems

This commit is contained in:
2026-10-30 11:07:02 +03:00
parent e3a6372e91
commit b94b07654f
7 changed files with 71 additions and 12 deletions
+3 -1
View File
@@ -35,7 +35,9 @@ final class Input {
if (node == null || !node.isTextual()) throw ApiException.invalid("Пароль должен быть строкой");
String value = node.textValue();
int length = value.codePointCount(0, value.length());
if (length < 12 || length > 128) throw ApiException.invalid("Пароль должен содержать от 12 до 128 символов");
if (length < 12 || length > 128 || value.codePoints().allMatch(Input::isUnicodeWhitespace)) {
throw ApiException.invalid("Пароль должен содержать от 12 до 128 непробельных символов");
}
return value;
}
@@ -30,7 +30,10 @@ public class MessengerController {
@PostMapping(value = "/auth/sessions", consumes = "*/*")
@ResponseStatus(HttpStatus.CREATED)
Session login(HttpServletRequest request) {
Session login(HttpServletRequest request) throws java.io.IOException {
if (request.getInputStream().read() != -1) {
throw ApiException.invalid("Вход не принимает тело запроса");
}
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Basic ")) throw ApiException.unauthorized();
try {
@@ -1,15 +1,22 @@
package ru.mtusi.messenger;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static ru.mtusi.messenger.Models.*;
@@ -21,16 +28,22 @@ public class SessionService {
private final SCryptPasswordEncoder passwords = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8();
private final SecureRandom random = new SecureRandom();
private final long ttlSeconds;
private final long databaseTimeoutMillis;
private final ExecutorService databaseExecutor = Executors.newFixedThreadPool(4);
public SessionService(MessengerStore store, StringRedisTemplate redis,
@Value("${SESSION_TTL_SECONDS:3600}") long ttlSeconds) {
this.store = store; this.redis = redis; this.ttlSeconds = Math.max(2, ttlSeconds);
@Value("${SESSION_TTL_SECONDS:3600}") long ttlSeconds,
@Value("${DB_REQUEST_TIMEOUT_MS:2000}") long databaseTimeoutMillis) {
this.store = store;
this.redis = redis;
this.ttlSeconds = Math.max(2, ttlSeconds);
this.databaseTimeoutMillis = Math.max(250, databaseTimeoutMillis);
}
public String hash(String password) { return passwords.encode(password); }
public Session login(String username, String password) {
Credentials credentials = store.credentials(username);
Credentials credentials = database(() -> store.credentials(username));
if (credentials == null || !passwords.matches(password, credentials.passwordHash())) throw ApiException.unauthorized();
byte[] bytes = new byte[32];
random.nextBytes(bytes);
@@ -50,7 +63,7 @@ public class SessionService {
try { value = redis.opsForValue().get(key(token)); }
catch (RuntimeException exception) { throw new ApiException(503, "unavailable", "Сервис сессий недоступен"); }
if (value == null) throw ApiException.unauthorized();
User user = store.findUser(java.util.UUID.fromString(value));
User user = database(() -> store.findUser(UUID.fromString(value)));
if (user == null) throw ApiException.unauthorized();
return user;
}
@@ -64,4 +77,26 @@ public class SessionService {
public void check() { redis.opsForValue().get("messenger:readiness"); }
private String key(String token) { return "messenger:session:" + token; }
private <T> T database(java.util.concurrent.Callable<T> operation) {
Future<T> future = databaseExecutor.submit(operation);
try {
return future.get(databaseTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException exception) {
future.cancel(true);
throw new ApiException(503, "unavailable", "Хранилище данных недоступно");
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new ApiException(503, "unavailable", "Хранилище данных недоступно");
} catch (ExecutionException exception) {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException runtime) throw runtime;
throw new IllegalStateException(cause);
}
}
@PreDestroy
void shutdownDatabaseExecutor() {
databaseExecutor.shutdownNow();
}
}