package com.example.mtusi_messenger.security; import com.example.mtusi_messenger.repository.UserRepository; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.dao.DataAccessException; import java.util.List; @Component public class DatabaseAuthenticationProvider implements AuthenticationProvider { private final UserRepository users; private final PasswordEncoder passwordEncoder; private final String dummyPasswordHash; public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) { this.users = users; this.passwordEncoder = passwordEncoder; this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing"); } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = String.valueOf(authentication.getCredentials()); final java.util.Optional stored; try { stored = users.findCredentialsByUsername(username); } catch (DataAccessException e) { throw new AuthenticationServiceException("Authentication database is unavailable", e); } String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash) .filter(hash -> hash.startsWith("$argon2")) .orElse(dummyPasswordHash); boolean matches; try { matches = passwordEncoder.matches(password, passwordHash); } catch (IllegalArgumentException e) { matches = false; } if (stored.isEmpty() || !matches) { throw new BadCredentialsException("Invalid credentials"); } return UsernamePasswordAuthenticationToken.authenticated( stored.get().user(), null, List.of()); } @Override public boolean supports(Class authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } }