This commit is contained in:
EgorAnti
2026-10-19 18:13:43 +03:00
commit c324689cce
91 changed files with 5703 additions and 0 deletions
@@ -0,0 +1,157 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiExceptions;
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 jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
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.Enumeration;
import java.util.UUID;
@Service
public class AuthenticationService {
private static final String AUTHORIZATION = "Authorization";
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private final UserRepository users;
private final SessionRepository sessions;
private final PasswordEncoder passwordEncoder;
private final long ttlSeconds;
private final String dummyPasswordHash;
public AuthenticationService(
UserRepository users,
SessionRepository sessions,
PasswordEncoder passwordEncoder,
@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.passwordEncoder = passwordEncoder;
this.ttlSeconds = ttlSeconds;
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
}
public IssuedSession login(HttpServletRequest request) {
BasicCredentials credentials = parseBasic(singleAuthorizationHeader(request, true));
var stored = users.findCredentialsByUsername(credentials.username());
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
.filter(hash -> hash.startsWith("$argon2"))
.orElse(dummyPasswordHash);
boolean passwordMatches;
try {
passwordMatches = passwordEncoder.matches(credentials.password(), passwordHash);
} catch (IllegalArgumentException e) {
passwordMatches = false;
}
if (stored.isEmpty() || !passwordMatches) {
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
}
User user = stored.get().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 User requireBearer(HttpServletRequest request) {
String token = parseBearer(singleAuthorizationHeader(request, false));
UUID userId = sessions.findActiveUserId(hashToken(token))
.orElseThrow(() -> ApiExceptions.unauthorizedBearer("Invalid or expired session"));
return users.findById(userId)
.orElseThrow(() -> ApiExceptions.unauthorizedBearer("Invalid or expired session"));
}
public void logout(HttpServletRequest request) {
String token = parseBearer(singleAuthorizationHeader(request, false));
if (!sessions.revoke(hashToken(token))) {
throw ApiExceptions.unauthorizedBearer("Invalid or expired session");
}
}
private String singleAuthorizationHeader(HttpServletRequest request, boolean basic) {
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
if (values == null || !values.hasMoreElements()) {
throw basic
? ApiExceptions.unauthorizedBasic("Authentication required")
: ApiExceptions.unauthorizedBearer("Authentication required");
}
String value = values.nextElement();
if (values.hasMoreElements()) {
throw basic
? ApiExceptions.unauthorizedBasic("Invalid Authorization header")
: ApiExceptions.unauthorizedBearer("Invalid Authorization header");
}
return value;
}
private BasicCredentials parseBasic(String header) {
if (!header.startsWith("Basic ") || header.length() == 6) {
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
}
try {
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
String value = new String(decoded, StandardCharsets.UTF_8);
int separator = value.indexOf(':');
if (separator <= 0) {
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
}
return new BasicCredentials(value.substring(0, separator), value.substring(separator + 1));
} catch (IllegalArgumentException e) {
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
}
}
private String parseBearer(String header) {
if (!header.startsWith("Bearer ") || header.length() == 7) {
throw ApiExceptions.unauthorizedBearer("Invalid bearer token");
}
String token = header.substring(7);
if (!token.matches("[A-Za-z0-9_-]{43}")) {
throw ApiExceptions.unauthorizedBearer("Invalid bearer token");
}
return token;
}
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) {}
private record BasicCredentials(String username, String password) {}
}