Merge remote-tracking branch 'refs/remotes/origin/main' into tests

This commit is contained in:
2025-06-10 22:23:37 +02:00
12 changed files with 235 additions and 158 deletions

View File

@@ -1,70 +1,68 @@
package _11.asktpk.artisanconnectbackend.controller;
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
import _11.asktpk.artisanconnectbackend.dto.*;
import _11.asktpk.artisanconnectbackend.entities.Client;
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
import _11.asktpk.artisanconnectbackend.service.ClientService;
import _11.asktpk.artisanconnectbackend.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
private final ClientService clientService;
private final JwtUtil jwtUtil;
private final AuthService authService;
public AuthController(ClientService clientService, JwtUtil jwtUtil) {
this.clientService = clientService;
this.jwtUtil = jwtUtil;
public AuthController(AuthService authService) {
this.authService = authService;
}
@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
|| authRequestDTO.getEmail().isEmpty() || authRequestDTO.getPassword().isEmpty()) {
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());
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 (WrongLoginPasswordException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new RequestResponseDTO(e.getMessage()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
}
}
@PostMapping("/register")
public ResponseEntity<AuthResponseDTO> register(@RequestBody ClientRegistrationDTO clientDTO) {
if (clientService.getClientByEmail(clientDTO.getEmail()) != null) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
public ResponseEntity<?> register(@RequestBody ClientRegistrationDTO clientRegistrationDTO) {
if (clientRegistrationDTO.getEmail() == null || clientRegistrationDTO.getPassword() == null
|| clientRegistrationDTO.getEmail().isEmpty() || clientRegistrationDTO.getPassword().isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Przekazano puste login lub hasło"));
}
ClientDTO savedClient = clientService.registerClient(clientDTO);
clientRegistrationDTO.setEmail(clientRegistrationDTO.getEmail().toLowerCase());
String token = jwtUtil.generateToken(
savedClient.getEmail(),
savedClient.getRole(),
savedClient.getId()
);
try {
AuthResponseDTO registrationData = authService.register(clientRegistrationDTO.getEmail(), clientRegistrationDTO.getPassword(), clientRegistrationDTO.getFirstName(), clientRegistrationDTO.getLastName());
log.info("New user registered with {}", savedClient.getEmail());
return ResponseEntity.status(HttpStatus.CREATED)
.body(new AuthResponseDTO(
savedClient.getId(),
savedClient.getRole(),
token
));
return ResponseEntity.status(HttpStatus.CREATED)
.body(registrationData);
} catch (ClientAlreadyExistsException clientAlreadyExistsException) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(new RequestResponseDTO(clientAlreadyExistsException.getMessage()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
}
}
@PostMapping("/logout")
@@ -73,7 +71,7 @@ public class AuthController {
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
jwtUtil.blacklistToken(token);
authService.logout(token);
return ResponseEntity.ok(new RequestResponseDTO("Successfully logged out"));
}
@@ -82,43 +80,16 @@ public class AuthController {
@PostMapping("/google")
public ResponseEntity<?> authenticateWithGoogle(@RequestBody GoogleAuthRequestDTO dto) {
if(dto.getGoogleToken() == null){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid or empty token"));
}
try {
String accessToken = dto.getGoogleToken();
String googleUserInfoUrl = "https://www.googleapis.com/oauth2/v3/userinfo";
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
HttpEntity<String> entity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Map> response = restTemplate.exchange(
googleUserInfoUrl, HttpMethod.GET, entity, Map.class);
Map<String, Object> userInfo = response.getBody();
// String googleId = (String) userInfo.get("sub"); Potencjalnie możemy używać googlowskiego ID, ale to ma konflikt z naszym generowanym
assert userInfo != null;
String email = (String) userInfo.get("email");
String name = (String) userInfo.get("name");
Client client = clientService.getClientByEmail(email);
if (client == null) {
client = new Client();
client.setEmail(email);
client.setFirstName(name);
client.setRole(clientService.getUserRole()); // to pobiera po prostu role "USER" z tabeli w bazie
clientService.saveClientToDB(client);
}
String jwt = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
log.info("User authenticated with google: {}", email);
return ResponseEntity.ok(new AuthResponseDTO(client.getId(), client.getRole().getRole(), jwt));
AuthResponseDTO response = authService.googleLogin(dto.getGoogleToken());
return ResponseEntity.status(HttpStatus.OK).body(response);
} catch (HttpClientErrorException httpClientErrorException) {
log.error("Token is invalid or expired");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new RequestResponseDTO("Invalid access token"));
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Google access token is invalid or expired"));
} catch (Exception e) {
log.error("Error while checking Google access token", e);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
}

View File

@@ -42,7 +42,7 @@ public class OrderController {
}
@PostMapping("/token")
public ResponseEntity<?> fetchToken(HttpServletRequest request,@RequestParam Long orderId) {
public ResponseEntity<?> fetchToken(@RequestParam Long orderId) {
Order order = orderService.getOrderById(orderId);
Client client = order.getClient();
OAuthPaymentResponseDTO authPaymentDTO = paymentService.getOAuthToken();
@@ -51,8 +51,15 @@ public class OrderController {
String paymentDescription = order.getOrderType() == Enums.OrderType.ACTIVATION ? "Aktywacja ogłoszenia" : "Podbicie ogłoszenia";
paymentDescription += order.getNotice().getTitle();
TransactionPaymentRequestDTO.Callbacks callbacks = new TransactionPaymentRequestDTO.Callbacks();
TransactionPaymentRequestDTO.PayerUrls payerUrls = new TransactionPaymentRequestDTO.PayerUrls();
payerUrls.setSuccess("com.hamx.artisanconnect://dashboard/userNotices");
payerUrls.setError("com.hamx.artisanconnect://dashboard/userNotices");
callbacks.setPayerUrls(payerUrls);
TransactionPaymentRequestDTO paymentRequest = new TransactionPaymentRequestDTO(
order.getAmount(), paymentDescription, payer);
order.getAmount(), paymentDescription, payer, callbacks);
String response = paymentService.createTransaction(order, authPaymentDTO.getAccess_token(), paymentRequest);

View File

@@ -0,0 +1,7 @@
package _11.asktpk.artisanconnectbackend.customExceptions;
public class ClientAlreadyExistsException extends Exception {
public ClientAlreadyExistsException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package _11.asktpk.artisanconnectbackend.customExceptions;
public class WrongLoginPasswordException extends Exception {
public WrongLoginPasswordException(String message) {
super(message);
}
}

View File

@@ -1,12 +1,16 @@
package _11.asktpk.artisanconnectbackend.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import jakarta.validation.constraints.Email;
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
public class ClientDTO {
private Long id;

View File

@@ -1,8 +1,12 @@
package _11.asktpk.artisanconnectbackend.dto;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.List;
@Getter @Setter
public class OrderWithPaymentsDTO {
private Long orderId;
private String orderType;
@@ -10,53 +14,4 @@ public class OrderWithPaymentsDTO {
private Double amount;
private LocalDateTime createdAt;
private List<PaymentDTO> payments;
// Gettery i settery
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public List<PaymentDTO> getPayments() {
return payments;
}
public void setPayments(List<PaymentDTO> payments) {
this.payments = payments;
}
}

View File

@@ -11,6 +11,7 @@ public class TransactionPaymentRequestDTO {
private double amount;
private String description;
private Payer payer;
private Callbacks callbacks;
@Getter
@Setter
@@ -20,4 +21,21 @@ public class TransactionPaymentRequestDTO {
private String email;
private String name;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class Callbacks {
private PayerUrls payerUrls;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class PayerUrls {
private String success;
private String error;
}
}

View File

@@ -2,6 +2,7 @@ package _11.asktpk.artisanconnectbackend.entities;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
@@ -11,7 +12,15 @@ import java.util.List;
@Entity
@Table(name = "clients")
@Getter @Setter
@NoArgsConstructor
public class Client {
public Client(String email, String password, String firstName, String lastName) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

View File

@@ -0,0 +1,116 @@
package _11.asktpk.artisanconnectbackend.service;
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
import _11.asktpk.artisanconnectbackend.dto.AuthResponseDTO;
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
import _11.asktpk.artisanconnectbackend.entities.Client;
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
import org.springframework.http.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Slf4j
@Service
public class AuthService {
private final ClientService clientService;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
public AuthService(ClientService clientService, JwtUtil jwtUtil, PasswordEncoder passwordEncoder) {
this.clientService = clientService;
this.jwtUtil = jwtUtil;
this.passwordEncoder = passwordEncoder;
}
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 WrongLoginPasswordException("Login lub hasło jest niepoprawny!");
}
public AuthResponseDTO register(String email, String password, String firstName, String lastName) throws Exception {
if (clientService.getClientByEmail(email) != null) {
throw new ClientAlreadyExistsException("Klient o podanym adresie email już istnieje!");
}
Client newClient = new Client();
newClient.setEmail(email);
newClient.setPassword(passwordEncoder.encode(password));
newClient.setFirstName(firstName);
newClient.setLastName(lastName);
ClientDTO savedClient = clientService.registerClient(newClient);
if (savedClient != null) {
log.info("New user registered with {}", savedClient.getEmail());
String token = jwtUtil.generateToken(
savedClient.getEmail(),
savedClient.getRole(),
savedClient.getId()
);
return new AuthResponseDTO(savedClient.getId(), savedClient.getRole(), token);
} else {
throw new Exception("Rejestracja nie powiodła się!");
}
}
public void logout(String token) {
jwtUtil.blacklistToken(token);
}
public AuthResponseDTO googleLogin(String googleAccessToken) throws Exception {
String googleUserInfoUrl = "https://www.googleapis.com/oauth2/v3/userinfo";
ResponseEntity<Map> response;
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(googleAccessToken);
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.exchange(
googleUserInfoUrl, HttpMethod.GET, new HttpEntity<>(headers), Map.class);
Map<String, Object> userInfo = response.getBody();
// String googleId = (String) userInfo.get("sub"); Potencjalnie możemy używać googlowskiego ID, ale to ma konflikt z naszym generowanym
if (userInfo == null) {
throw new Exception("Pobrany użytkownik jest pusty! Może to być spowodowane niepoprawnym tokenem lub brakiem dostępu do Google API.");
}
String email = (String) userInfo.get("email");
String name = (String) userInfo.get("name");
Client client = clientService.getClientByEmail(email);
if (client == null) {
client = new Client();
client.setEmail(email);
client.setFirstName(name);
client.setRole(clientService.getUserRole()); // to pobiera po prostu role "USER" z tabeli w bazie
clientService.saveClientToDB(client);
}
String jwt = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
log.info("User authenticated with google: {}", client.getEmail());
return new AuthResponseDTO(
client.getId(),
client.getRole().getRole(),
jwt
);
}
}

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;
@@ -8,7 +7,6 @@ import _11.asktpk.artisanconnectbackend.entities.Role;
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
import _11.asktpk.artisanconnectbackend.repository.RolesRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -16,16 +14,14 @@ import java.util.List;
@Service
public class ClientService {
private final ClientRepository clientRepository;
private final PasswordEncoder passwordEncoder;
private final RolesRepository rolesRepository;
public ClientService(ClientRepository clientRepository, PasswordEncoder passwordEncoder, RolesRepository rolesRepository) {
public ClientService(ClientRepository clientRepository, RolesRepository rolesRepository) {
this.clientRepository = clientRepository;
this.passwordEncoder = passwordEncoder;
this.rolesRepository = rolesRepository;
}
private ClientDTO toDto(Client client) {
public ClientDTO toDto(Client client) {
if(client == null) {
return null;
}
@@ -42,7 +38,7 @@ public class ClientService {
return dto;
}
private Client fromDto(ClientDTO dto) {
public Client fromDto(ClientDTO dto) {
Client client = new Client();
Role rola;
@@ -86,6 +82,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 +121,8 @@ 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()));
public ClientDTO registerClient(Client client) {
client.setRole(getUserRole()); // ID 1 - USER role
return toDto(clientRepository.save(client));
}
public Client getClientByEmail(String email) {
return clientRepository.findByEmail(email);
}
public Role getUserRole() {
return rolesRepository.findRoleByRole("USER");
}
}

View File

@@ -15,10 +15,10 @@ public class EmailService {
public void sendEmail(EmailDTO email) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("noreply@zikor.pl");
message.setTo(email.getTo());
message.setSubject(email.getSubject());
message.setText(email.getBody());
message.setFrom("patryk.kania001@gmail.com");
mailSender.send(message);
}
}

View File

@@ -18,10 +18,10 @@ file.upload-dir=/Users/andsol/Desktop/uploads
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.mail.host=smtp.gmail.com
spring.mail.host=smtp.sendgrid.net
spring.mail.port=587
spring.mail.username=patryk.kania001@gmail.com
spring.mail.password=pmyd ylwg mbsn hcpp
spring.mail.username=apikey
spring.mail.password=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
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true