Compare commits
2 Commits
d51161221c
...
refactor-a
| Author | SHA1 | Date | |
|---|---|---|---|
| 3355914c70 | |||
| 0f14c72fdd |
@@ -26,7 +26,7 @@ public class SecurityConfig {
|
|||||||
.cors(cors -> cors.configure(http))
|
.cors(cors -> cors.configure(http))
|
||||||
.csrf(AbstractHttpConfigurer::disable)
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.requestMatchers("/api/v1/auth/**", "/api/v1/payments/notification").permitAll()
|
.requestMatchers("/api/v1/auth/**").permitAll()
|
||||||
.anyRequest().authenticated())
|
.anyRequest().authenticated())
|
||||||
.sessionManagement(session -> session
|
.sessionManagement(session -> session
|
||||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||||
|
|||||||
@@ -1,70 +1,68 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.controller;
|
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.dto.*;
|
||||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
import _11.asktpk.artisanconnectbackend.service.AuthService;
|
||||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
|
||||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.*;
|
import org.springframework.http.*;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.client.HttpClientErrorException;
|
import org.springframework.web.client.HttpClientErrorException;
|
||||||
import org.springframework.web.client.RestTemplate;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/auth")
|
@RequestMapping("/api/v1/auth")
|
||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private final ClientService clientService;
|
private final AuthService authService;
|
||||||
private final JwtUtil jwtUtil;
|
|
||||||
|
|
||||||
public AuthController(ClientService clientService, JwtUtil jwtUtil) {
|
public AuthController(AuthService authService) {
|
||||||
this.clientService = clientService;
|
this.authService = authService;
|
||||||
this.jwtUtil = jwtUtil;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
public ResponseEntity<AuthResponseDTO> login(@RequestBody AuthRequestDTO authRequestDTO) {
|
public ResponseEntity<?> login(@RequestBody AuthRequestDTO authRequestDTO) {
|
||||||
if (clientService.checkClientCredentials(authRequestDTO)) {
|
if (authRequestDTO.getEmail() == null || authRequestDTO.getPassword() == null
|
||||||
Client client = clientService.getClientByEmail(authRequestDTO.getEmail());
|
|| authRequestDTO.getEmail().isEmpty() || authRequestDTO.getPassword().isEmpty()) {
|
||||||
Long userId = client.getId();
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Przekazano puste login lub hasło"));
|
||||||
String userRole = client.getRole().getRole();
|
}
|
||||||
|
|
||||||
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)
|
return ResponseEntity.status(HttpStatus.OK)
|
||||||
.body(new AuthResponseDTO(userId, userRole, token));
|
.body(responseDTO);
|
||||||
} else {
|
|
||||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
|
} 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")
|
@PostMapping("/register")
|
||||||
public ResponseEntity<AuthResponseDTO> register(@RequestBody ClientRegistrationDTO clientDTO) {
|
public ResponseEntity<?> register(@RequestBody ClientRegistrationDTO clientRegistrationDTO) {
|
||||||
if (clientService.getClientByEmail(clientDTO.getEmail()) != null) {
|
if (clientRegistrationDTO.getEmail() == null || clientRegistrationDTO.getPassword() == null
|
||||||
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
|| 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(
|
try {
|
||||||
savedClient.getEmail(),
|
AuthResponseDTO registrationData = authService.register(clientRegistrationDTO.getEmail(), clientRegistrationDTO.getPassword(), clientRegistrationDTO.getFirstName(), clientRegistrationDTO.getLastName());
|
||||||
savedClient.getRole(),
|
|
||||||
savedClient.getId()
|
|
||||||
);
|
|
||||||
|
|
||||||
log.info("New user registered with {}", savedClient.getEmail());
|
return ResponseEntity.status(HttpStatus.CREATED)
|
||||||
|
.body(registrationData);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED)
|
} catch (ClientAlreadyExistsException clientAlreadyExistsException) {
|
||||||
.body(new AuthResponseDTO(
|
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||||
savedClient.getId(),
|
.body(new RequestResponseDTO(clientAlreadyExistsException.getMessage()));
|
||||||
savedClient.getRole(),
|
} catch (Exception e) {
|
||||||
token
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
|
||||||
));
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/logout")
|
@PostMapping("/logout")
|
||||||
@@ -73,7 +71,7 @@ public class AuthController {
|
|||||||
|
|
||||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||||
String token = authHeader.substring(7);
|
String token = authHeader.substring(7);
|
||||||
jwtUtil.blacklistToken(token);
|
authService.logout(token);
|
||||||
return ResponseEntity.ok(new RequestResponseDTO("Successfully logged out"));
|
return ResponseEntity.ok(new RequestResponseDTO("Successfully logged out"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,43 +80,16 @@ public class AuthController {
|
|||||||
|
|
||||||
@PostMapping("/google")
|
@PostMapping("/google")
|
||||||
public ResponseEntity<?> authenticateWithGoogle(@RequestBody GoogleAuthRequestDTO dto) {
|
public ResponseEntity<?> authenticateWithGoogle(@RequestBody GoogleAuthRequestDTO dto) {
|
||||||
|
if(dto.getGoogleToken() == null){
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid or empty token"));
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
String accessToken = dto.getGoogleToken();
|
AuthResponseDTO response = authService.googleLogin(dto.getGoogleToken());
|
||||||
String googleUserInfoUrl = "https://www.googleapis.com/oauth2/v3/userinfo";
|
return ResponseEntity.status(HttpStatus.OK).body(response);
|
||||||
|
|
||||||
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));
|
|
||||||
} catch (HttpClientErrorException httpClientErrorException) {
|
} catch (HttpClientErrorException httpClientErrorException) {
|
||||||
log.error("Token is invalid or expired");
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Google access token is invalid or expired"));
|
||||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new RequestResponseDTO("Invalid access token"));
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error while checking Google access token", e);
|
|
||||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||||
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
|
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.controller;
|
package _11.asktpk.artisanconnectbackend.controller;
|
||||||
|
|
||||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
|
||||||
import _11.asktpk.artisanconnectbackend.entities.Order;
|
import _11.asktpk.artisanconnectbackend.entities.Order;
|
||||||
import _11.asktpk.artisanconnectbackend.entities.Payment;
|
|
||||||
import _11.asktpk.artisanconnectbackend.service.OrderService;
|
import _11.asktpk.artisanconnectbackend.service.OrderService;
|
||||||
import _11.asktpk.artisanconnectbackend.service.PaymentService;
|
import _11.asktpk.artisanconnectbackend.service.PaymentService;
|
||||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||||
@@ -13,8 +11,6 @@ import org.springframework.http.HttpStatus;
|
|||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/orders")
|
@RequestMapping("/api/v1/orders")
|
||||||
@@ -42,88 +38,21 @@ public class OrderController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/token")
|
@PostMapping("/token")
|
||||||
public ResponseEntity<?> fetchToken(HttpServletRequest request,@RequestParam Long orderId) {
|
public ResponseEntity<?> fetchToken() {
|
||||||
Order order = orderService.getOrderById(orderId);
|
Order order = orderService.getOrderById(1L);
|
||||||
Client client = order.getClient();
|
|
||||||
OAuthPaymentResponseDTO authPaymentDTO = paymentService.getOAuthToken();
|
OAuthPaymentResponseDTO authPaymentDTO = paymentService.getOAuthToken();
|
||||||
TransactionPaymentRequestDTO.Payer payer = new TransactionPaymentRequestDTO.Payer(
|
TransactionPaymentRequestDTO.Payer payer = new TransactionPaymentRequestDTO.Payer(
|
||||||
client.getEmail(), client.getFirstName()+' '+client.getLastName());
|
"patryk@test.pl", "Patryk Test");
|
||||||
|
|
||||||
String paymentDescription = order.getOrderType() == Enums.OrderType.ACTIVATION ? "Aktywacja ogłoszenia" : "Podbicie ogłoszenia";
|
String paymentDescription = order.getOrderType() == Enums.OrderType.ACTIVATION ? "Aktywacja ogłoszenia" : "Podbicie ogłoszenia";
|
||||||
paymentDescription += order.getNotice().getTitle();
|
paymentDescription += order.getNotice().getTitle();
|
||||||
TransactionPaymentRequestDTO paymentRequest = new TransactionPaymentRequestDTO(
|
TransactionPaymentRequestDTO request = new TransactionPaymentRequestDTO(
|
||||||
order.getAmount(), paymentDescription, payer);
|
order.getAmount(), paymentDescription, payer);
|
||||||
|
|
||||||
String response = paymentService.createTransaction(order, authPaymentDTO.getAccess_token(), paymentRequest);
|
String response = paymentService.createTransaction(order, authPaymentDTO.getAccess_token(), request);
|
||||||
|
System.out.println(response);
|
||||||
|
System.out.println(request);
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.OK).body(response);
|
return ResponseEntity.status(HttpStatus.OK).body(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/get/all")
|
|
||||||
public ResponseEntity<List<OrderWithPaymentsDTO>> getOrders(HttpServletRequest request) {
|
|
||||||
Long clientId = tools.getClientIdFromRequest(request);
|
|
||||||
List<Order> orders = orderService.getOrdersByClientId(clientId);
|
|
||||||
|
|
||||||
List<OrderWithPaymentsDTO> dtoList = orders.stream().map(order -> {
|
|
||||||
OrderWithPaymentsDTO dto = new OrderWithPaymentsDTO();
|
|
||||||
dto.setOrderId(order.getId());
|
|
||||||
dto.setOrderType(order.getOrderType().name());
|
|
||||||
dto.setStatus(order.getStatus().name());
|
|
||||||
dto.setAmount(order.getAmount());
|
|
||||||
dto.setCreatedAt(order.getCreatedAt());
|
|
||||||
|
|
||||||
List<Payment> payments = paymentService.getPaymentsByOrderId(order.getId());
|
|
||||||
|
|
||||||
List<PaymentDTO> paymentDTOs = payments.stream().map(payment -> {
|
|
||||||
PaymentDTO pDto = new PaymentDTO();
|
|
||||||
pDto.setPaymentId(payment.getIdPayment());
|
|
||||||
pDto.setAmount(payment.getAmount());
|
|
||||||
pDto.setStatus(payment.getStatus().name());
|
|
||||||
pDto.setTransactionPaymentUrl(payment.getTransactionPaymentUrl());
|
|
||||||
pDto.setTransactionId(payment.getTransactionId());
|
|
||||||
return pDto;
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
dto.setPayments(paymentDTOs);
|
|
||||||
return dto;
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
return ResponseEntity.ok(dtoList);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/get/{orderId}")
|
|
||||||
public ResponseEntity<OrderWithPaymentsDTO> getOrderById(HttpServletRequest request,
|
|
||||||
@PathVariable Long orderId) {
|
|
||||||
Long clientId = tools.getClientIdFromRequest(request);
|
|
||||||
|
|
||||||
Order order = orderService.getOrderById(orderId);
|
|
||||||
|
|
||||||
if (!order.getClient().getId().equals(clientId)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
OrderWithPaymentsDTO dto = new OrderWithPaymentsDTO();
|
|
||||||
dto.setOrderId(order.getId());
|
|
||||||
dto.setOrderType(order.getOrderType().name());
|
|
||||||
dto.setStatus(order.getStatus().name());
|
|
||||||
dto.setAmount(order.getAmount());
|
|
||||||
dto.setCreatedAt(order.getCreatedAt());
|
|
||||||
|
|
||||||
List<Payment> payments = paymentService.getPaymentsByOrderId(order.getId());
|
|
||||||
List<PaymentDTO> paymentDTOs = payments.stream().map(payment -> {
|
|
||||||
PaymentDTO pDto = new PaymentDTO();
|
|
||||||
pDto.setPaymentId(payment.getIdPayment());
|
|
||||||
pDto.setAmount(payment.getAmount());
|
|
||||||
pDto.setStatus(payment.getStatus().name());
|
|
||||||
pDto.setTransactionPaymentUrl(payment.getTransactionPaymentUrl());
|
|
||||||
pDto.setTransactionId(payment.getTransactionId());
|
|
||||||
return pDto;
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
dto.setPayments(paymentDTOs);
|
|
||||||
|
|
||||||
return ResponseEntity.ok(dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ public class PaymentController {
|
|||||||
|
|
||||||
@PostMapping(value = "/notification", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
@PostMapping(value = "/notification", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
||||||
public ResponseEntity<String> handleTpayNotification(@RequestParam Map<String, String> params) {
|
public ResponseEntity<String> handleTpayNotification(@RequestParam Map<String, String> params) {
|
||||||
|
log.info("=== ODEBRANO NOTYFIKACJĘ Tpay ===");
|
||||||
|
log.info("Parametry:\n{}", paramsToLogString(params));
|
||||||
|
|
||||||
String id = params.get("id");
|
String id = params.get("id");
|
||||||
String trId = params.get("tr_id");
|
String trId = params.get("tr_id");
|
||||||
String trAmount = params.get("tr_amount");
|
String trAmount = params.get("tr_amount");
|
||||||
@@ -51,6 +54,7 @@ public class PaymentController {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (!expectedMd5.equals(md5sum)) {
|
if (!expectedMd5.equals(md5sum)) {
|
||||||
|
log.warn("❌ Błędna suma kontrolna! Otrzymano: {}, Oczekiwano: {}", md5sum, expectedMd5);
|
||||||
return ResponseEntity.status(400).body("INVALID CHECKSUM");
|
return ResponseEntity.status(400).body("INVALID CHECKSUM");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +63,7 @@ public class PaymentController {
|
|||||||
Payment payment = optionalPayment.get();
|
Payment payment = optionalPayment.get();
|
||||||
|
|
||||||
if ("true".equalsIgnoreCase(trStatus) || "PAID".equalsIgnoreCase(trStatus)) {
|
if ("true".equalsIgnoreCase(trStatus) || "PAID".equalsIgnoreCase(trStatus)) {
|
||||||
|
log.info("✅ Transakcja opłacona: tr_id={}, kwota={}", trId, params.get("tr_paid"));
|
||||||
payment.setStatus(Enums.PaymentStatus.CORRECT);
|
payment.setStatus(Enums.PaymentStatus.CORRECT);
|
||||||
|
|
||||||
if (payment.getOrder() != null) {
|
if (payment.getOrder() != null) {
|
||||||
@@ -73,6 +78,7 @@ public class PaymentController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} else if ("false".equalsIgnoreCase(trStatus)) {
|
} else if ("false".equalsIgnoreCase(trStatus)) {
|
||||||
|
log.warn("❌ Transakcja nieudana: {}", trId);
|
||||||
payment.setStatus(Enums.PaymentStatus.INCORRECT);
|
payment.setStatus(Enums.PaymentStatus.INCORRECT);
|
||||||
|
|
||||||
if (payment.getOrder() != null) {
|
if (payment.getOrder() != null) {
|
||||||
@@ -81,7 +87,10 @@ public class PaymentController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
paymentRepository.save(payment);
|
paymentRepository.save(payment);
|
||||||
|
} else {
|
||||||
|
log.warn("⚠️ Brak płatności o tr_id={}", trId);
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResponseEntity.ok("TRUE");
|
return ResponseEntity.ok("TRUE");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package _11.asktpk.artisanconnectbackend.customExceptions;
|
||||||
|
|
||||||
|
public class ClientAlreadyExistsException extends Exception {
|
||||||
|
public ClientAlreadyExistsException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package _11.asktpk.artisanconnectbackend.customExceptions;
|
||||||
|
|
||||||
|
public class WrongLoginPasswordException extends Exception {
|
||||||
|
public WrongLoginPasswordException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,16 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.dto;
|
package _11.asktpk.artisanconnectbackend.dto;
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
import jakarta.validation.constraints.Email;
|
import jakarta.validation.constraints.Email;
|
||||||
|
|
||||||
@Getter @Setter
|
@Getter @Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
public class ClientDTO {
|
public class ClientDTO {
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.dto;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class OrderWithPaymentsDTO {
|
|
||||||
private Long orderId;
|
|
||||||
private String orderType;
|
|
||||||
private String status;
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.dto;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
public class PaymentDTO {
|
|
||||||
private Long paymentId;
|
|
||||||
private Double amount;
|
|
||||||
private String status;
|
|
||||||
private String transactionPaymentUrl;
|
|
||||||
private String transactionId;
|
|
||||||
|
|
||||||
public void setPaymentId(Long paymentId) {
|
|
||||||
this.paymentId = paymentId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAmount(Double amount) {
|
|
||||||
this.amount = amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStatus(String status) {
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTransactionPaymentUrl(String transactionPaymentUrl) {
|
|
||||||
this.transactionPaymentUrl = transactionPaymentUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTransactionId(String transactionId) {
|
|
||||||
this.transactionId = transactionId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,7 @@ package _11.asktpk.artisanconnectbackend.entities;
|
|||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.hibernate.annotations.CreationTimestamp;
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
@@ -11,7 +12,15 @@ import java.util.List;
|
|||||||
@Entity
|
@Entity
|
||||||
@Table(name = "clients")
|
@Table(name = "clients")
|
||||||
@Getter @Setter
|
@Getter @Setter
|
||||||
|
@NoArgsConstructor
|
||||||
public class Client {
|
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
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|||||||
@@ -4,10 +4,8 @@ import _11.asktpk.artisanconnectbackend.entities.Order;
|
|||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface OrderRepository extends JpaRepository<Order, Long> {
|
public interface OrderRepository extends JpaRepository<Order, Long> {
|
||||||
List<Order> findByClientId(Long clientId);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,9 @@ import _11.asktpk.artisanconnectbackend.entities.Payment;
|
|||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface PaymentRepository extends JpaRepository<Payment, Long> {
|
public interface PaymentRepository extends JpaRepository<Payment, Long> {
|
||||||
Optional<Payment> findByTransactionId(String transactionId);
|
Optional<Payment> findByTransactionId(String transactionId);
|
||||||
|
|
||||||
List<Payment> findAllByOrderId(Long id);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
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.bcrypt.BCryptPasswordEncoder;
|
||||||
|
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) {
|
||||||
|
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 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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.service;
|
package _11.asktpk.artisanconnectbackend.service;
|
||||||
|
|
||||||
import _11.asktpk.artisanconnectbackend.dto.AuthRequestDTO;
|
|
||||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||||
import _11.asktpk.artisanconnectbackend.dto.ClientRegistrationDTO;
|
import _11.asktpk.artisanconnectbackend.dto.ClientRegistrationDTO;
|
||||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||||
@@ -25,7 +24,7 @@ public class ClientService {
|
|||||||
this.rolesRepository = rolesRepository;
|
this.rolesRepository = rolesRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ClientDTO toDto(Client client) {
|
public ClientDTO toDto(Client client) {
|
||||||
if(client == null) {
|
if(client == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -42,7 +41,7 @@ public class ClientService {
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Client fromDto(ClientDTO dto) {
|
public Client fromDto(ClientDTO dto) {
|
||||||
Client client = new Client();
|
Client client = new Client();
|
||||||
Role rola;
|
Role rola;
|
||||||
|
|
||||||
@@ -86,6 +85,14 @@ public class ClientService {
|
|||||||
return toDto(clientRepository.findById(id).orElse(null));
|
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) {
|
public boolean clientExists(Long id) {
|
||||||
return clientRepository.existsById(id);
|
return clientRepository.existsById(id);
|
||||||
}
|
}
|
||||||
@@ -117,29 +124,9 @@ public class ClientService {
|
|||||||
clientRepository.deleteById(id);
|
clientRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// И замените метод checkClientCredentials на:
|
public ClientDTO registerClient(Client client) {
|
||||||
public boolean checkClientCredentials(AuthRequestDTO dto) {
|
client.setRole(getUserRole()); // ID 1 - USER role
|
||||||
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()));
|
client.setPassword(passwordEncoder.encode(client.getPassword()));
|
||||||
return toDto(clientRepository.save(client));
|
return toDto(clientRepository.save(client));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Client getClientByEmail(String email) {
|
|
||||||
return clientRepository.findByEmail(email);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Role getUserRole() {
|
|
||||||
return rolesRepository.findRoleByRole("USER");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import org.springframework.stereotype.Service;
|
|||||||
import _11.asktpk.artisanconnectbackend.entities.Order;
|
import _11.asktpk.artisanconnectbackend.entities.Order;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class OrderService {
|
public class OrderService {
|
||||||
@@ -76,8 +75,4 @@ public class OrderService {
|
|||||||
return orderRepository.findById(id)
|
return orderRepository.findById(id)
|
||||||
.orElseThrow(() -> new RuntimeException("Nie znaleziono zamówienia o ID: " + id));
|
.orElseThrow(() -> new RuntimeException("Nie znaleziono zamówienia o ID: " + id));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Order> getOrdersByClientId(Long clientId) {
|
|
||||||
return orderRepository.findByClientId(clientId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ import org.springframework.web.reactive.function.BodyInserters;
|
|||||||
import org.springframework.web.reactive.function.client.WebClient;
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class PaymentService {
|
public class PaymentService {
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
@@ -82,10 +80,4 @@ public class PaymentService {
|
|||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Payment> getPaymentsByOrderId(Long id) {
|
|
||||||
return paymentRepository.findAllByOrderId(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user