login endpoint refactored

This commit is contained in:
2025-06-09 19:57:27 +02:00
parent 2589c6010e
commit 0f14c72fdd
4 changed files with 68 additions and 31 deletions

View File

@@ -3,6 +3,7 @@ package _11.asktpk.artisanconnectbackend.controller;
import _11.asktpk.artisanconnectbackend.dto.*;
import _11.asktpk.artisanconnectbackend.entities.Client;
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
import _11.asktpk.artisanconnectbackend.service.AuthService;
import _11.asktpk.artisanconnectbackend.service.ClientService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
@@ -19,27 +20,32 @@ import java.util.Map;
public class AuthController {
private final ClientService clientService;
private final AuthService authService;
private final JwtUtil jwtUtil;
public AuthController(ClientService clientService, JwtUtil jwtUtil) {
public AuthController(ClientService clientService, JwtUtil jwtUtil, AuthService authService) {
this.clientService = clientService;
this.authService = authService;
this.jwtUtil = jwtUtil;
}
@PostMapping("/login")
public ResponseEntity<AuthResponseDTO> login(@RequestBody AuthRequestDTO authRequestDTO) {
if (clientService.checkClientCredentials(authRequestDTO)) {
Client client = clientService.getClientByEmail(authRequestDTO.getEmail());
Long userId = client.getId();
String userRole = client.getRole().getRole();
public ResponseEntity<?> login(@RequestBody AuthRequestDTO authRequestDTO) {
if (authRequestDTO.getEmail() == null || authRequestDTO.getPassword() == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Przekazano puste login lub hasło"));
}
String token = jwtUtil.generateToken(client.getEmail(), userRole, userId);
authRequestDTO.setEmail(authRequestDTO.getEmail().toLowerCase());
authRequestDTO.setPassword(authRequestDTO.getPassword());
try {
AuthResponseDTO responseDTO = authService.login(authRequestDTO.getEmail(), authRequestDTO.getPassword());
log.info("User logged in with {}", client.getEmail());
return ResponseEntity.status(HttpStatus.OK)
.body(new AuthResponseDTO(userId, userRole, token));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
.body(responseDTO);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
}
}

View File

@@ -0,0 +1,4 @@
package _11.asktpk.artisanconnectbackend.customExceptions;
public class WrongLoginPasswordException {
}

View File

@@ -0,0 +1,39 @@
package _11.asktpk.artisanconnectbackend.service;
import _11.asktpk.artisanconnectbackend.dto.AuthResponseDTO;
import _11.asktpk.artisanconnectbackend.entities.Client;
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class AuthService {
private final ClientService clientService;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
public AuthService(ClientService clientService, JwtUtil jwtUtil) {
this.clientService = clientService;
this.jwtUtil = jwtUtil;
this.passwordEncoder = new BCryptPasswordEncoder();
}
public AuthResponseDTO login(String email, String password) throws Exception {
Client client = clientService.getClientByEmail(email);
if (client == null) {
throw new Exception("Klient o podanym adresie nie istnieje!");
}
if(passwordEncoder.matches(password, client.getPassword())) {
String token = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
log.info("User logged in with {}", client.getEmail());
return new AuthResponseDTO(client.getId(), client.getRole().getRole(), token);
}
throw new Exception("Login lub hasło jest niepoprawny!");
}
}

View File

@@ -1,6 +1,5 @@
package _11.asktpk.artisanconnectbackend.service;
import _11.asktpk.artisanconnectbackend.dto.AuthRequestDTO;
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
import _11.asktpk.artisanconnectbackend.dto.ClientRegistrationDTO;
import _11.asktpk.artisanconnectbackend.entities.Client;
@@ -86,6 +85,14 @@ public class ClientService {
return toDto(clientRepository.findById(id).orElse(null));
}
public Client getClientByEmail(String email) {
return clientRepository.findByEmail(email);
}
public Role getUserRole() {
return rolesRepository.findRoleByRole("USER");
}
public boolean clientExists(Long id) {
return clientRepository.existsById(id);
}
@@ -117,29 +124,10 @@ public class ClientService {
clientRepository.deleteById(id);
}
// И замените метод checkClientCredentials на:
public boolean checkClientCredentials(AuthRequestDTO dto) {
Client cl = clientRepository.findByEmail(dto.getEmail());
if (cl == null) {
return false;
}
return passwordEncoder.matches(dto.getPassword(), cl.getPassword());
}
// При создании нового пользователя не забудьте шифровать пароль:
public ClientDTO registerClient(ClientRegistrationDTO clientDTO) {
Client client = fromDto(clientDTO);
client.setRole(rolesRepository.findRoleById(1L));
client.setPassword(passwordEncoder.encode(client.getPassword()));
return toDto(clientRepository.save(client));
}
public Client getClientByEmail(String email) {
return clientRepository.findByEmail(email);
}
public Role getUserRole() {
return rolesRepository.findRoleByRole("USER");
}
}