|
| 1 | +package org.example.alfs.services; |
| 2 | + |
| 3 | +import org.example.alfs.entities.User; |
| 4 | +import org.example.alfs.repositories.UserRepository; |
| 5 | +import org.springframework.http.HttpStatus; |
| 6 | +import org.springframework.security.crypto.password.PasswordEncoder; |
| 7 | +import org.springframework.stereotype.Service; |
| 8 | +import org.springframework.web.server.ResponseStatusException; |
| 9 | + |
| 10 | +@Service |
| 11 | +public class AuthService { |
| 12 | + |
| 13 | + private final PasswordEncoder passwordEncoder; |
| 14 | + private final UserRepository userRepository; |
| 15 | + |
| 16 | + public AuthService(PasswordEncoder passwordEncoder, UserRepository userRepository) { |
| 17 | + this.passwordEncoder = passwordEncoder; |
| 18 | + this.userRepository = userRepository; |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Authenticates a user by verifying username and password. |
| 23 | + */ |
| 24 | + public User login(String username, String password) { |
| 25 | + |
| 26 | + User user = userRepository.findByUsername(username) |
| 27 | + .orElseThrow(() -> new ResponseStatusException( |
| 28 | + HttpStatus.UNAUTHORIZED, |
| 29 | + "Invalid username or password" |
| 30 | + )); |
| 31 | + if (!passwordEncoder.matches(password, user.getPasswordHash())) { |
| 32 | + throw new ResponseStatusException( |
| 33 | + HttpStatus.UNAUTHORIZED, |
| 34 | + "Invalid username or password" |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + return user; |
| 39 | + } |
| 40 | +} |
0 commit comments