Исправление валидации и обеспечение консинстентности кэша после падения редис
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Исправление security context утечки
This commit is contained in:
@@ -2,10 +2,7 @@ package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.config.properties.SessionProperties;
|
||||
import ru.mtusi.messenger.dto.SessionDTO;
|
||||
@@ -20,22 +17,17 @@ import ru.mtusi.messenger.util.TokenHasher;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SessionService {
|
||||
private static final String SESSIONS = "sessions";
|
||||
|
||||
private final TokenGenerator tokenGenerator;
|
||||
private final TokenHasher tokenHasher;
|
||||
private final SessionProperties sessionProperties;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final SessionMapper sessionMapper;
|
||||
private final CacheManager cacheManager;
|
||||
private final ExecutorService cacheEvictExecutor;
|
||||
|
||||
private final SessionCacheService sessionCacheService;
|
||||
|
||||
@Transactional
|
||||
public SessionDTO createSession(UserDTO userDTO) {
|
||||
@@ -44,43 +36,46 @@ public class SessionService {
|
||||
return sessionMapper.toSessionDTO(session, token, userDTO);
|
||||
}
|
||||
|
||||
@Cacheable(value = SESSIONS, key = "@tokenHasher.hash(#token)")
|
||||
@Transactional(readOnly = true)
|
||||
public SessionRecord requireActive(String token) {
|
||||
Session s = sessionRepository.findByTokenHash(tokenHasher.sha256(token))
|
||||
.filter(x -> x.getRevokedAt() == null)
|
||||
.filter(x -> x.getExpiresAt().isAfter(Instant.now()))
|
||||
.orElseThrow(() -> new UnauthorizedException("Invalid or expired session"));
|
||||
return new SessionRecord(s.getId(), s.getUserId());
|
||||
sessionCacheService.dropCacheIfStale();
|
||||
String hex = tokenHasher.hash(token);
|
||||
SessionRecord record = sessionCacheService.lookupByHash(hex);
|
||||
requireNotExpired(record, hex);
|
||||
return record;
|
||||
}
|
||||
|
||||
private void requireNotExpired(SessionRecord record, String hex) {
|
||||
if (record == null || isExpired(record)) {
|
||||
sessionCacheService.evict(hex);
|
||||
throw new UnauthorizedException("Invalid or expired session");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isExpired(SessionRecord record) {
|
||||
return record.expiresAt().isBefore(Instant.now());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void revoke(UUID sessionId) {
|
||||
sessionRepository.findById(sessionId).ifPresent(s -> {
|
||||
if (s.getRevokedAt() == null) {
|
||||
s.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
||||
}
|
||||
String key = tokenHasher.hash(s.getTokenHash());
|
||||
cacheEvictExecutor.submit(() -> {
|
||||
try {
|
||||
Cache cache = cacheManager.getCache(SESSIONS);
|
||||
if (cache != null) {
|
||||
cache.evict(key);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Cache EVICT failed (sessions): {}", e.getMessage());
|
||||
}
|
||||
});
|
||||
});
|
||||
sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict);
|
||||
}
|
||||
|
||||
private void markRevokedAndEvict(Session session) {
|
||||
if (session.getRevokedAt() == null) {
|
||||
session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
||||
}
|
||||
sessionCacheService.evict(tokenHasher.hash(session.getTokenHash()));
|
||||
}
|
||||
|
||||
private Session buildSession(UserDTO userDTO, String token) {
|
||||
Session session = new Session();
|
||||
session.setUserId(userDTO.getId());
|
||||
session.setTokenHash(tokenHasher.sha256(token));
|
||||
session.setExpiresAt(Instant.now().plus(sessionProperties.ttl()).truncatedTo(ChronoUnit.MILLIS));
|
||||
session.setExpiresAt(Instant.now()
|
||||
.plus(sessionProperties.ttl())
|
||||
.truncatedTo(ChronoUnit.MILLIS));
|
||||
return session;
|
||||
}
|
||||
|
||||
public record SessionRecord(UUID sessionId, UUID userId) {}
|
||||
public record SessionRecord(UUID sessionId, UUID userId, Instant expiresAt) {}
|
||||
}
|
||||
Reference in New Issue
Block a user