package com.example.mtusi_messenger.service; import com.example.mtusi_messenger.model.Session; import com.example.mtusi_messenger.model.User; import com.example.mtusi_messenger.repository.SessionRepository; import com.example.mtusi_messenger.repository.UserRepository; import com.example.mtusi_messenger.security.SessionPrincipal; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Service; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.Instant; import java.util.Base64; import java.util.UUID; @Service public class AuthenticationService { private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private final UserRepository users; private final SessionRepository sessions; private final long ttlSeconds; public AuthenticationService( UserRepository users, SessionRepository sessions, @Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds ) { if (ttlSeconds <= 0) { throw new IllegalArgumentException("Session TTL must be positive"); } this.users = users; this.sessions = sessions; this.ttlSeconds = ttlSeconds; } public IssuedSession issueSession(User user) { String token = newToken(); Instant createdAt = Instant.now(); Instant expiresAt = createdAt.plusSeconds(ttlSeconds); sessions.save(new Session( UUID.randomUUID(), user.id(), hashToken(token), createdAt, expiresAt)); return new IssuedSession(token, expiresAt, user); } public SessionPrincipal authenticateBearer(String token) { byte[] tokenHash = hashToken(token); UUID userId = sessions.findActiveUserId(tokenHash) .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); User user = users.findById(userId) .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); return new SessionPrincipal(user, tokenHash); } public void revoke(SessionPrincipal principal) { if (!sessions.revoke(principal.tokenHash())) { throw new BadCredentialsException("Invalid or expired session"); } } private String newToken() { byte[] bytes = new byte[32]; SECURE_RANDOM.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } private byte[] hashToken(String token) { try { return MessageDigest.getInstance("SHA-256") .digest(token.getBytes(StandardCharsets.US_ASCII)); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA-256 is unavailable", e); } } public record IssuedSession(String token, Instant expiresAt, User user) {} }