forked from mtusi2026/mtusi2026lab3
lab3 gusak
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
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.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.*;
|
||||
|
||||
@Service
|
||||
public class SessionService {
|
||||
private static final Base64.Encoder TOKEN_ENCODER = Base64.getUrlEncoder().withoutPadding();
|
||||
private final MessengerStore store;
|
||||
private final StringRedisTemplate redis;
|
||||
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,
|
||||
@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 = database(() -> store.credentials(username));
|
||||
if (credentials == null || !passwords.matches(password, credentials.passwordHash())) throw ApiException.unauthorized();
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
String token = TOKEN_ENCODER.encodeToString(bytes);
|
||||
Instant expires = Instant.now().plusSeconds(ttlSeconds);
|
||||
try {
|
||||
redis.opsForValue().set(key(token), credentials.user().id().toString(), Duration.ofSeconds(ttlSeconds));
|
||||
} catch (RuntimeException exception) {
|
||||
throw new ApiException(503, "unavailable", "Сервис сессий недоступен");
|
||||
}
|
||||
return new Session(token, "Bearer", expires, credentials.user());
|
||||
}
|
||||
|
||||
public User authenticate(String token) {
|
||||
if (token == null || token.isBlank()) throw ApiException.unauthorized();
|
||||
String value;
|
||||
try { value = redis.opsForValue().get(key(token)); }
|
||||
catch (RuntimeException exception) { throw new ApiException(503, "unavailable", "Сервис сессий недоступен"); }
|
||||
if (value == null) throw ApiException.unauthorized();
|
||||
User user = database(() -> store.findUser(UUID.fromString(value)));
|
||||
if (user == null) throw ApiException.unauthorized();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void revoke(String token) {
|
||||
if (token == null) throw ApiException.unauthorized();
|
||||
try { redis.delete(key(token)); }
|
||||
catch (RuntimeException exception) { throw new ApiException(503, "unavailable", "Сервис сессий недоступен"); }
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user