initial
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ArtisanConnectBackendApplication {
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
public ArtisanConnectBackendApplication(Environment environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
static void main(String[] args) {
|
||||
SpringApplication.run(ArtisanConnectBackendApplication.class, args);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void logDataSourceUrl() {
|
||||
System.out.println("Datasource URL: " + environment.getProperty("spring.datasource.url"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package _11.asktpk.artisanconnectbackend.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class AppConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package _11.asktpk.artisanconnectbackend.config;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.RequestResponseDTO;
|
||||
import org.springframework.boot.webmvc.error.ErrorController;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import jakarta.servlet.RequestDispatcher;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@Controller
|
||||
public class CustomErrorController implements ErrorController {
|
||||
|
||||
@RequestMapping("/error")
|
||||
public ResponseEntity<RequestResponseDTO> handleError(HttpServletRequest request) {
|
||||
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
|
||||
|
||||
if (status != null) {
|
||||
int statusCode = Integer.parseInt(status.toString());
|
||||
|
||||
if (statusCode == HttpStatus.NOT_FOUND.value()) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(new RequestResponseDTO("Nie znaleziono zasobu. Sprawdź URL i spróbuj ponownie."));
|
||||
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new RequestResponseDTO("Wystąpił wewnętrzny błąd serwera. Spróbuj ponownie później."));
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new RequestResponseDTO("Wystąpił nieoczekiwany błąd."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package _11.asktpk.artisanconnectbackend.config;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtRequestFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtRequestFilter jwtRequestFilter;
|
||||
|
||||
public SecurityConfig(JwtRequestFilter jwtRequestFilter) {
|
||||
this.jwtRequestFilter = jwtRequestFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(Arrays.asList(
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173"
|
||||
));
|
||||
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||
config.setAllowedHeaders(Collections.singletonList("*"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return source;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/v1/auth/**", "/api/v1/payments/notification").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.sessionManagement(session -> session
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
|
||||
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
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.security.JwtUtil;
|
||||
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;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
private final JwtUtil jwtUtil;
|
||||
public AuthController(AuthService authService, JwtUtil jwtUtil) {
|
||||
this.authService = authService;
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
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"));
|
||||
}
|
||||
|
||||
authRequestDTO.setEmail(authRequestDTO.getEmail().toLowerCase());
|
||||
|
||||
try {
|
||||
AuthResponseDTO responseDTO = authService.login(authRequestDTO.getEmail(), authRequestDTO.getPassword());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.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<?> 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"));
|
||||
}
|
||||
|
||||
clientRegistrationDTO.setEmail(clientRegistrationDTO.getEmail().toLowerCase());
|
||||
|
||||
try {
|
||||
AuthResponseDTO registrationData = authService.register(clientRegistrationDTO.getEmail(), clientRegistrationDTO.getPassword(), clientRegistrationDTO.getFirstName(), clientRegistrationDTO.getLastName());
|
||||
|
||||
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")
|
||||
public ResponseEntity<RequestResponseDTO> logout(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
authService.logout(token);
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Successfully logged out"));
|
||||
}
|
||||
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid token"));
|
||||
}
|
||||
|
||||
@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 {
|
||||
AuthResponseDTO response = authService.googleLogin(dto.getGoogleToken());
|
||||
return ResponseEntity.status(HttpStatus.OK).body(response);
|
||||
} catch (HttpClientErrorException httpClientErrorException) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Google access token is invalid or expired"));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<?> getMe(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(new AuthResponseDTO(jwtUtil.extractUserId(token), jwtUtil.extractRole(token), token));
|
||||
}
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid or empty token"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package _11.asktpk.artisanconnectbackend.controller;
|
||||
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/clients")
|
||||
public class ClientController {
|
||||
private final ClientService clientService;
|
||||
|
||||
public ClientController(ClientService clientService) {
|
||||
this.clientService = clientService;
|
||||
}
|
||||
|
||||
@GetMapping("/get/all")
|
||||
public List<ClientDTO> getAllClients() {
|
||||
return clientService.getAllClients();
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
public ResponseEntity<?> getClientById(@PathVariable long id) {
|
||||
if(clientService.getClientById(id) != null) {
|
||||
return new ResponseEntity<>(clientService.getClientByIdDTO(id), HttpStatus.OK);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/add")
|
||||
public ResponseEntity<?> addClient(@RequestBody ClientDTO clientDTO) {
|
||||
if(clientService.clientExists(clientDTO.getId())) {
|
||||
return new ResponseEntity<>(HttpStatus.CONFLICT);
|
||||
} else {
|
||||
return new ResponseEntity<>(clientService.addClient(clientDTO), HttpStatus.CREATED);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: do zrobienia walidacja danych
|
||||
@PutMapping("/edit/{id}")
|
||||
public ResponseEntity<?> updateClient(@PathVariable("id") long id, @RequestBody ClientDTO clientDTO) {
|
||||
if(clientService.clientExists(id)) {
|
||||
return new ResponseEntity<>(clientService.updateClient(id, clientDTO),HttpStatus.OK);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<?> deleteClient(@PathVariable("id") long id) {
|
||||
if(clientService.clientExists(id)) {
|
||||
clientService.deleteClient(id);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package _11.asktpk.artisanconnectbackend.controller;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.RequestResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.service.ImageService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/images")
|
||||
public class ImageController {
|
||||
|
||||
private final ImageService imageService;
|
||||
private final NoticeService noticeService;
|
||||
ImageController(ImageService imageService, NoticeService noticeService) {
|
||||
this.imageService = imageService;
|
||||
this.noticeService = noticeService;
|
||||
}
|
||||
|
||||
@Value("${file.upload-dir}")
|
||||
private String uploadDir;
|
||||
|
||||
@PostMapping("/upload/{id}")
|
||||
public ResponseEntity<RequestResponseDTO> uploadImage(@RequestParam("file") MultipartFile file, @PathVariable("id") Long noticeId, @Param("isMainImage") Boolean isMainImage) {
|
||||
try {
|
||||
if(file.isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(new RequestResponseDTO("File is empty"));
|
||||
}
|
||||
|
||||
if(!Objects.equals(file.getContentType(), "image/jpeg") && !Objects.equals(file.getContentType(), "image/png")) {
|
||||
return ResponseEntity.badRequest().body(new RequestResponseDTO("File must be a JPEG or PNG image."));
|
||||
}
|
||||
|
||||
if(noticeId == null || !noticeService.noticeExists(noticeId)) {
|
||||
return ResponseEntity.badRequest().body(new RequestResponseDTO("Notice ID is invalid or does not exist."));
|
||||
}
|
||||
|
||||
String newImageName = imageService.saveImageToStorage(uploadDir, file);
|
||||
imageService.addImageNameToDB(newImageName, noticeId, isMainImage);
|
||||
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Image uploaded successfully with new name: " + newImageName));
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/get/{filename}")
|
||||
public ResponseEntity<Resource> getImage(@PathVariable String filename) {
|
||||
try {
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.IMAGE_JPEG)
|
||||
.body(imageService.getImage(uploadDir, filename));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/list/{id}")
|
||||
public ResponseEntity<?> getImagesNamesList(@PathVariable("id") Long noticeId) {
|
||||
List<String> result;
|
||||
try {
|
||||
noticeService.getNoticeById(noticeId);
|
||||
result = imageService.getImagesList(noticeId);
|
||||
return ResponseEntity.ok(result);
|
||||
} catch (EntityNotFoundException e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{filename}")
|
||||
public ResponseEntity<RequestResponseDTO> deleteImage(@PathVariable("filename") String filename) {
|
||||
if(filename == null) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Filename is empty."));
|
||||
}
|
||||
|
||||
try {
|
||||
imageService.deleteImage(uploadDir, filename);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(new RequestResponseDTO("Image deleted successfully."));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package _11.asktpk.artisanconnectbackend.controller;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@RequestMapping("/api/v1/notices")
|
||||
@RestController
|
||||
public class NoticeController {
|
||||
private final NoticeService noticeService;
|
||||
private final ClientService clientService;
|
||||
private final Tools tools;
|
||||
|
||||
public NoticeController(NoticeService noticeService, ClientService clientService, Tools tools) {
|
||||
this.noticeService = noticeService;
|
||||
this.clientService = clientService;
|
||||
this.tools = tools;
|
||||
}
|
||||
|
||||
@GetMapping("/get/all")
|
||||
public List<NoticeResponseDTO> getAllNotices() {
|
||||
return noticeService.getAllNotices();
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
public ResponseEntity<?> getNoticeById(@PathVariable long id) {
|
||||
if (noticeService.noticeExists(id)) {
|
||||
return ResponseEntity.ok(noticeService.getNoticeById(id));
|
||||
} else {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/add")
|
||||
public ResponseEntity<NoticeAdditionDTO> addNotice(@RequestBody NoticeRequestDTO dto, HttpServletRequest request) {
|
||||
Long clientId = tools.getClientIdFromRequest(request);
|
||||
if (!clientService.clientExists(clientId)) {
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.body(new NoticeAdditionDTO("Nie znaleziono klienta o ID: " + clientId));
|
||||
}
|
||||
|
||||
dto.setClientId(clientId);
|
||||
|
||||
if (dto.getCategory() == null || !Arrays.asList(Enums.Category.values()).contains(dto.getCategory())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new NoticeAdditionDTO("Nie ma takiej kategorii"));
|
||||
}
|
||||
|
||||
Long newNoticeId = noticeService.addNotice(dto);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(new NoticeAdditionDTO(newNoticeId ,"Dodano ogłoszenie."));
|
||||
}
|
||||
|
||||
@PutMapping("/edit/{id}")
|
||||
public ResponseEntity<Object> editNotice(@PathVariable("id") long id, @RequestBody NoticeRequestDTO dto, HttpServletRequest request) {
|
||||
Long clientIdFromToken = tools.getClientIdFromRequest(request);
|
||||
if (noticeService.noticeExists(id)) {
|
||||
if (!noticeService.isNoticeOwnedByClient(id, clientIdFromToken)) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new RequestResponseDTO("Nie masz uprawnień do edycji tego ogłoszenia."));
|
||||
}
|
||||
try {
|
||||
return ResponseEntity.status(HttpStatus.OK).body(noticeService.updateNotice(id, dto));
|
||||
} catch (EntityNotFoundException e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
|
||||
}
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Nie znaleziono ogłoszenia o ID: " + id);
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<RequestResponseDTO> deleteNotice(@PathVariable("id") long id, HttpServletRequest request) {
|
||||
Long clientIdFromToken = tools.getClientIdFromRequest(request);
|
||||
if (noticeService.noticeExists(id)) {
|
||||
if (!noticeService.isNoticeOwnedByClient(id, clientIdFromToken)) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new RequestResponseDTO("Nie masz uprawnień do usunięcia tego ogłoszenia."));
|
||||
}
|
||||
|
||||
noticeService.deleteNotice(id);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(new RequestResponseDTO("Pomyślnie usunięto ogłoszenie o ID: " + id));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new RequestResponseDTO("Nie znaleziono ogłoszenia o ID: " + id));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/boost")
|
||||
public ResponseEntity<RequestResponseDTO> boostNotice(@RequestBody NoticeBoostDTO dto, HttpServletRequest request) {
|
||||
Long clientId = tools.getClientIdFromRequest(request);
|
||||
if (noticeService.isNoticeOwnedByClient(dto.getNoticeId(), clientId)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new RequestResponseDTO("Ogłoszenie nie istnieje lub nie należy do zalogowanego klienta."));
|
||||
}
|
||||
noticeService.boostNotice(dto.getNoticeId());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(new RequestResponseDTO("Ogłoszenie zostało pomyślnie wypromowane."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package _11.asktpk.artisanconnectbackend.controller;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.CategoriesDTO;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/vars")
|
||||
public class VariablesController {
|
||||
@GetMapping("/categories")
|
||||
public List<CategoriesDTO> getAllVariables() {
|
||||
List<CategoriesDTO> categoriesDTOList = new ArrayList<>();
|
||||
for (Map.Entry<Enums.Category, String> entry : Enums.categoryPL.entrySet()) {
|
||||
CategoriesDTO categoriesDTO = new CategoriesDTO();
|
||||
categoriesDTO.setLabel(entry.getValue());
|
||||
categoriesDTO.setValue(entry.getKey().toString());
|
||||
categoriesDTOList.add(categoriesDTO);
|
||||
}
|
||||
|
||||
return categoriesDTOList;
|
||||
}
|
||||
|
||||
@GetMapping("/statuses")
|
||||
public List<Enums.Status> getAllStatuses() {
|
||||
return List.of(Enums.Status.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package _11.asktpk.artisanconnectbackend.controller;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.RequestResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/wishlist")
|
||||
public class WishlistController {
|
||||
private final WishlistService wishlistService;
|
||||
private final ClientService clientService;
|
||||
private final NoticeService noticeService;
|
||||
private final Tools tools;
|
||||
|
||||
public WishlistController(WishlistService wishlistService, ClientService clientService, NoticeService noticeService, Tools tools) {
|
||||
this.wishlistService = wishlistService;
|
||||
this.clientService = clientService;
|
||||
this.noticeService = noticeService;
|
||||
this.tools = tools;
|
||||
}
|
||||
|
||||
@PostMapping("/toggle/{noticeId}")
|
||||
public ResponseEntity<RequestResponseDTO> toggleWishlist(@PathVariable Long noticeId, HttpServletRequest request) {
|
||||
Long clientId = tools.getClientIdFromRequest(request);
|
||||
NoticeResponseDTO noticeResponseDTO = noticeService.getNoticeById(noticeId);
|
||||
if (noticeResponseDTO == null) {
|
||||
return ResponseEntity.badRequest().body(new RequestResponseDTO("Notice not found"));
|
||||
}
|
||||
boolean added = wishlistService.toggleWishlist(
|
||||
clientService.getClientById(clientId),
|
||||
noticeService.getNoticeByIdEntity(noticeId)
|
||||
);
|
||||
|
||||
if (added) {
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Wishlist entry added"));
|
||||
} else {
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Wishlist entry removed"));
|
||||
}
|
||||
}
|
||||
|
||||
// @GetMapping("/{clientId}")
|
||||
// public ResponseEntity<List<WishlistDTO>> getWishlist(@PathVariable Long clientId) {
|
||||
// List<WishlistDTO> wishlist = wishlistService.getWishlistForClientId(clientId);
|
||||
// return ResponseEntity.ok(wishlist);
|
||||
// }
|
||||
|
||||
@GetMapping("/")
|
||||
public List<NoticeResponseDTO> getWishlistForClient(HttpServletRequest request) {
|
||||
Long clientId = tools.getClientIdFromRequest(request);
|
||||
return wishlistService.getNoticesInWishlist(clientId);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package _11.asktpk.artisanconnectbackend.customExceptions;
|
||||
|
||||
public class ClientAlreadyExistsException extends Exception {
|
||||
public ClientAlreadyExistsException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package _11.asktpk.artisanconnectbackend.customExceptions;
|
||||
|
||||
public class WrongLoginPasswordException extends Exception {
|
||||
public WrongLoginPasswordException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class AttributeDto {
|
||||
private String name;
|
||||
private String value;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class AuthRequestDTO {
|
||||
private String email;
|
||||
private String password;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter @AllArgsConstructor
|
||||
public class AuthResponseDTO {
|
||||
private Long user_id;
|
||||
private String user_role;
|
||||
private String token;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
//[
|
||||
// { "label": "Meble", "value": "Furniture" },
|
||||
// { "label": "Biżuteria", "value": "Jewelry" },
|
||||
// { "label": "Ceramika", "value": "Ceramics" }
|
||||
//]
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class CategoriesDTO {
|
||||
String label;
|
||||
String value;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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;
|
||||
|
||||
@Email
|
||||
@NotBlank
|
||||
private String email;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String image;
|
||||
private String role;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class ClientRegistrationDTO {
|
||||
@Email
|
||||
@NotBlank
|
||||
private String email;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String password;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class GoogleAuthRequestDTO {
|
||||
private String googleToken;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class NoticeAdditionDTO {
|
||||
public Long noticeId;
|
||||
public String message;
|
||||
|
||||
public NoticeAdditionDTO(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public NoticeAdditionDTO(Long noticeId, String message) {
|
||||
this.noticeId = noticeId;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class NoticeBoostDTO {
|
||||
private Long noticeId;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import java.util.List;
|
||||
|
||||
@Getter @Setter
|
||||
public class NoticeRequestDTO {
|
||||
private String title;
|
||||
|
||||
private Long clientId;
|
||||
|
||||
private String description;
|
||||
|
||||
private Double price;
|
||||
|
||||
private Enums.Category category;
|
||||
|
||||
private Enums.Status status;
|
||||
|
||||
private List<AttributeDto> attributes;
|
||||
|
||||
public NoticeRequestDTO() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Getter @Setter
|
||||
public class NoticeResponseDTO {
|
||||
private long noticeId;
|
||||
|
||||
private String title;
|
||||
|
||||
private Long clientId;
|
||||
|
||||
private String description;
|
||||
|
||||
private Double price;
|
||||
|
||||
private Enums.Category category;
|
||||
|
||||
private Enums.Status status;
|
||||
|
||||
private LocalDateTime publishDate;
|
||||
|
||||
private List<AttributeDto> attributes;
|
||||
|
||||
public NoticeResponseDTO() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
public class RequestResponseDTO {
|
||||
public String message;
|
||||
|
||||
public RequestResponseDTO(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String toJSON() {
|
||||
return "{\"message\":\"" + message + "\"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class WishlistDTO {
|
||||
private Long id;
|
||||
private Long clientId;
|
||||
private Long noticeId;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attribute_values")
|
||||
@Getter @Setter
|
||||
public class AttributeValues {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "id_attribute")
|
||||
private Attributes attribute;
|
||||
|
||||
private String value;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Setter;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attributes")
|
||||
@Getter @Setter
|
||||
public class Attributes {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long idAttribute;
|
||||
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "attribute")
|
||||
private List<AttributeValues> attributeValues;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Setter;
|
||||
import lombok.Getter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attributes_notice")
|
||||
@Getter @Setter
|
||||
public class AttributesNotice {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private Long notice_id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "id_value")
|
||||
private AttributeValues attributeValue;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@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;
|
||||
|
||||
private String email;
|
||||
|
||||
private String password;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String image;
|
||||
|
||||
@ManyToOne(cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "role_id", referencedColumnName = "id")
|
||||
private Role role;
|
||||
|
||||
@CreationTimestamp
|
||||
private Date createdAt;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jdk.jfr.BooleanFlag;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "images")
|
||||
@Getter @Setter
|
||||
public class Image {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private Long noticeId;
|
||||
|
||||
private String imageName;
|
||||
|
||||
@BooleanFlag
|
||||
private boolean isMainImage;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "notice")
|
||||
@Getter @Setter
|
||||
public class Notice {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long idNotice;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "client_id")
|
||||
private Client client;
|
||||
|
||||
private String description;
|
||||
|
||||
private Double price;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Category category;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Status status;
|
||||
|
||||
private LocalDateTime publishDate;
|
||||
|
||||
@OneToMany(mappedBy = "notice_id")
|
||||
private List<AttributesNotice> attributesNotices;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "roles")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Role {
|
||||
@Id
|
||||
private Long id;
|
||||
@Column(name="rolename")
|
||||
private String role;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "wishlist")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Wishlist {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "client_id", nullable = false)
|
||||
private Client client;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "notice_id", nullable = false)
|
||||
private Notice notice;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.AttributeValues;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Attributes;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AttributeValuesRepository extends JpaRepository<AttributeValues, Long> {
|
||||
|
||||
Optional<AttributeValues> findByAttributeAndValue(Attributes attribute, String value);
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.AttributesNotice;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface AttributesNoticeRepository extends JpaRepository<AttributesNotice, Long> {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Attributes;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AttributesRepository extends JpaRepository<Attributes, Long> {
|
||||
Optional<Attributes> findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface ClientRepository extends JpaRepository<Client, Long> {
|
||||
Client findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Image;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ImageRepository extends JpaRepository<Image, Long> {
|
||||
List<Image> findByNoticeId(Long noticeId);
|
||||
|
||||
boolean existsImageByImageNameEqualsIgnoreCase(String imageName);
|
||||
|
||||
void deleteByImageNameEquals(String imageName);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface NoticeRepository extends JpaRepository<Notice, Long> {
|
||||
|
||||
boolean existsByIdNoticeAndClientId(long noticeId, long clientId);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||
|
||||
@Repository
|
||||
public interface RolesRepository extends JpaRepository<Role, String> {
|
||||
Role findRoleByRole(String role);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Wishlist;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface WishlistRepository extends JpaRepository<Wishlist, Long> {
|
||||
|
||||
List<Wishlist> findAllByClientId(Long clientId);
|
||||
|
||||
Optional<Wishlist> findByClientAndNotice(Client client, Notice notice);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package _11.asktpk.artisanconnectbackend.security;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.RequestResponseDTO;
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
|
||||
@Component
|
||||
public class JwtRequestFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
public JwtRequestFilter(JwtUtil jwtUtil) {
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
final String authorizationHeader = request.getHeader("Authorization");
|
||||
|
||||
String email = null;
|
||||
String jwt = null;
|
||||
|
||||
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
|
||||
jwt = authorizationHeader.substring(7);
|
||||
|
||||
try {
|
||||
if (jwtUtil.isBlacklisted(jwt) || !jwtUtil.isLatestToken(jwt)) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
String jsonResponse = "{\"error\": \"Token is invalid. Please login again.\"}";
|
||||
response.getWriter().write(jsonResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
email = jwtUtil.extractEmail(jwt);
|
||||
} catch (ExpiredJwtException expiredJwtException) {
|
||||
logger.error(expiredJwtException.getMessage());
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.getWriter().write(new RequestResponseDTO("Authentication token is expired. Please login again.").toJSON());
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.getWriter().write(new RequestResponseDTO(e.getMessage()).toJSON());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
String role = jwtUtil.extractRole(jwt);
|
||||
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
email, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role)));
|
||||
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
|
||||
// logger.info("Token of user " + jwtUtil.extractEmail(jwt) + (jwtUtil.isTokenExpired(jwt) ? " is expired" : " is not expired"));
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package _11.asktpk.artisanconnectbackend.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Component
|
||||
public class JwtUtil {
|
||||
|
||||
@Value("${jwt.secret:defaultSecretKeyNeedsToBeAtLeast32BytesLong}")
|
||||
private String secret;
|
||||
|
||||
@Value("${jwt.expiration}")
|
||||
private long expiration;
|
||||
|
||||
// sterowanie tokenami wygasnietymi
|
||||
private final Set<String> blacklistedTokens = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public void blacklistToken(String token) {
|
||||
blacklistedTokens.add(token);
|
||||
}
|
||||
|
||||
public boolean isBlacklisted(String token) {
|
||||
return blacklistedTokens.contains(token);
|
||||
}
|
||||
|
||||
|
||||
private SecretKey getSigningKey() {
|
||||
return Keys.hmacShaKeyFor(secret.getBytes());
|
||||
}
|
||||
|
||||
private final Map<String, String> userActiveTokens = new ConcurrentHashMap<>();
|
||||
|
||||
public boolean isLatestToken(String token) {
|
||||
String email = extractEmail(token);
|
||||
String tokenId = extractTokenId(token);
|
||||
String latestTokenId = userActiveTokens.get(email);
|
||||
|
||||
return latestTokenId != null && latestTokenId.equals(tokenId);
|
||||
}
|
||||
|
||||
public String generateToken(String email, String role, Long userId) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("role", role);
|
||||
claims.put("userId", userId);
|
||||
claims.put("tokenId", UUID.randomUUID().toString());
|
||||
|
||||
String token = createToken(claims, email);
|
||||
|
||||
userActiveTokens.put(email, extractTokenId(token));
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
private String createToken(Map<String, Object> claims, String subject) {
|
||||
return Jwts.builder().claims(claims).subject(subject).issuedAt(new Date()).expiration(new Date(System.currentTimeMillis() + expiration))
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String extractTokenId(String token) {
|
||||
return extractAllClaims(token).get("tokenId", String.class);
|
||||
}
|
||||
|
||||
public String extractEmail(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
public String extractRole(String token) {
|
||||
return extractAllClaims(token).get("role", String.class);
|
||||
}
|
||||
|
||||
public Long extractUserId(String token) {
|
||||
return extractAllClaims(token).get("userId", Long.class);
|
||||
}
|
||||
|
||||
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
final Claims claims = extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientRegistrationDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
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.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class ClientService {
|
||||
private final ClientRepository clientRepository;
|
||||
private final RolesRepository rolesRepository;
|
||||
|
||||
public ClientService(ClientRepository clientRepository, RolesRepository rolesRepository) {
|
||||
this.clientRepository = clientRepository;
|
||||
this.rolesRepository = rolesRepository;
|
||||
}
|
||||
|
||||
public ClientDTO toDto(Client client) {
|
||||
if(client == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ClientDTO dto = new ClientDTO();
|
||||
|
||||
dto.setId(client.getId());
|
||||
dto.setFirstName(client.getFirstName());
|
||||
dto.setLastName(client.getLastName());
|
||||
dto.setEmail(client.getEmail());
|
||||
dto.setRole(client.getRole().getRole());
|
||||
dto.setImage(client.getImage());
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
public Client fromDto(ClientDTO dto) {
|
||||
Client client = new Client();
|
||||
Role rola;
|
||||
|
||||
if (clientRepository.findById(dto.getId()).isPresent()) {
|
||||
rola = clientRepository.findById(dto.getId()).get().getRole();
|
||||
} else {
|
||||
rola = new Role();
|
||||
rola.setRole("USER");
|
||||
}
|
||||
|
||||
client.setId(dto.getId());
|
||||
client.setFirstName(dto.getFirstName());
|
||||
client.setLastName(dto.getLastName());
|
||||
client.setEmail(dto.getEmail());
|
||||
client.setRole(rola);
|
||||
client.setImage(dto.getImage());
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
private Client fromDto(ClientRegistrationDTO dto) {
|
||||
Client client = new Client();
|
||||
|
||||
client.setFirstName(dto.getFirstName());
|
||||
client.setLastName(dto.getLastName());
|
||||
client.setEmail(dto.getEmail());
|
||||
client.setPassword(dto.getPassword());
|
||||
return client;
|
||||
}
|
||||
|
||||
public List<ClientDTO> getAllClients() {
|
||||
List<Client> clients = clientRepository.findAll();
|
||||
return clients.stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
public Client getClientById(Long id) {
|
||||
return clientRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public ClientDTO getClientByIdDTO(Long id) {
|
||||
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);
|
||||
}
|
||||
|
||||
public ClientDTO addClient(ClientDTO clientDTO) {
|
||||
return toDto(clientRepository.save(fromDto(clientDTO)));
|
||||
}
|
||||
|
||||
public Client saveClientToDB(Client client) {
|
||||
return clientRepository.save(client);
|
||||
}
|
||||
|
||||
public ClientDTO updateClient(long id, ClientDTO clientDTO) {
|
||||
Client existingClient = clientRepository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id));
|
||||
|
||||
Role newRole = rolesRepository.findRoleByRole(clientDTO.getRole());
|
||||
|
||||
existingClient.setEmail(clientDTO.getEmail());
|
||||
existingClient.setFirstName(clientDTO.getFirstName());
|
||||
existingClient.setLastName(clientDTO.getLastName());
|
||||
existingClient.setImage(clientDTO.getImage());
|
||||
existingClient.setRole(newRole);
|
||||
|
||||
return toDto(clientRepository.save(existingClient));
|
||||
}
|
||||
|
||||
public void deleteClient(Long id) {
|
||||
clientRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public ClientDTO registerClient(Client client) {
|
||||
client.setRole(getUserRole()); // ID 1 - USER role
|
||||
return toDto(clientRepository.save(client));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Image;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ImageRepository;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class ImageService {
|
||||
private final ImageRepository imageRepository;
|
||||
|
||||
ImageService(ImageRepository imageRepository) {
|
||||
this.imageRepository = imageRepository;
|
||||
}
|
||||
|
||||
public String saveImageToStorage(String uploadDirectory, MultipartFile imageFile) throws IOException {
|
||||
String uniqueFileName = UUID.randomUUID() + imageFile.getOriginalFilename();
|
||||
|
||||
Path uploadPath = Path.of(uploadDirectory);
|
||||
Path filePath = uploadPath.resolve(uniqueFileName);
|
||||
|
||||
if (!Files.exists(uploadPath)) {
|
||||
Files.createDirectories(uploadPath);
|
||||
}
|
||||
|
||||
Files.copy(imageFile.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
|
||||
return uniqueFileName;
|
||||
}
|
||||
|
||||
public void addImageNameToDB(String filename, Long noticeId, boolean isMainImage) {
|
||||
Image image = new Image();
|
||||
image.setImageName(filename);
|
||||
image.setNoticeId(noticeId);
|
||||
image.setMainImage(isMainImage);
|
||||
imageRepository.save(image);
|
||||
}
|
||||
|
||||
public Resource getImage(String imageDirectory, String imageName) throws IOException {
|
||||
Path filePath = Paths.get(imageDirectory).resolve(imageName);
|
||||
Resource resource = new UrlResource(filePath.toUri());
|
||||
|
||||
if(imageName.isEmpty() || imageDirectory.isEmpty()) {
|
||||
throw new IOException("Filename or folder is empty. Please check your request and try again.");
|
||||
}
|
||||
|
||||
if (!resource.exists()) {
|
||||
throw new IOException("File not found");
|
||||
}
|
||||
|
||||
return resource;
|
||||
}
|
||||
|
||||
public void deleteImage(String imageDirectory, String imageName) throws IOException {
|
||||
Path imagePath = Path.of(imageDirectory, imageName);
|
||||
|
||||
deleteImageRecordFromDB(imageName);
|
||||
|
||||
if (Files.exists(imagePath)) {
|
||||
Files.delete(imagePath);
|
||||
} else {
|
||||
throw new IOException("File not found");
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getImagesList(Long noticeID) throws Exception {
|
||||
List<Image> images = imageRepository.findByNoticeId(noticeID);
|
||||
if (images.isEmpty()) {
|
||||
throw new Exception("There is no images for this notice");
|
||||
}
|
||||
|
||||
return images.stream()
|
||||
.map(Image::getImageName)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void deleteImageRecordFromDB(String imageName) {
|
||||
if(imageRepository.existsImageByImageNameEqualsIgnoreCase(imageName)) {
|
||||
imageRepository.deleteByImageNameEquals(imageName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.AttributeDto;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeRequestDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.*;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class NoticeService {
|
||||
private static final Logger logger = LogManager.getLogger(NoticeService.class);
|
||||
|
||||
@Value("${file.upload-dir}")
|
||||
private String uploadDir;
|
||||
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final ClientRepository clientRepository;
|
||||
private final ImageService imageService;
|
||||
private final AttributesRepository attributesRepository;
|
||||
private final AttributeValuesRepository attributeValuesRepository;
|
||||
private final AttributesNoticeRepository attributesNoticeRepository;
|
||||
|
||||
public NoticeService(NoticeRepository noticeRepository,
|
||||
ClientRepository clientRepository,
|
||||
ImageService imageService,
|
||||
AttributesRepository attributesRepository,
|
||||
AttributeValuesRepository attributeValuesRepository,
|
||||
AttributesNoticeRepository attributesNoticeRepository) {
|
||||
this.noticeRepository = noticeRepository;
|
||||
this.clientRepository = clientRepository;
|
||||
this.imageService = imageService;
|
||||
this.attributesRepository = attributesRepository;
|
||||
this.attributeValuesRepository = attributeValuesRepository;
|
||||
this.attributesNoticeRepository = attributesNoticeRepository;
|
||||
}
|
||||
|
||||
public Notice fromDTO(NoticeRequestDTO dto) {
|
||||
Notice notice = new Notice();
|
||||
notice.setTitle(dto.getTitle());
|
||||
notice.setDescription(dto.getDescription());
|
||||
notice.setPrice(dto.getPrice());
|
||||
notice.setCategory(dto.getCategory());
|
||||
notice.setStatus(dto.getStatus());
|
||||
|
||||
Client client = clientRepository.findById(dto.getClientId())
|
||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono klienta o ID: " + dto.getClientId()));
|
||||
notice.setClient(client);
|
||||
|
||||
return notice;
|
||||
}
|
||||
|
||||
private NoticeResponseDTO toDTO(Notice notice) {
|
||||
NoticeResponseDTO dto = new NoticeResponseDTO();
|
||||
dto.setNoticeId(notice.getIdNotice());
|
||||
dto.setTitle(notice.getTitle());
|
||||
dto.setClientId(notice.getClient().getId());
|
||||
dto.setDescription(notice.getDescription());
|
||||
dto.setPrice(notice.getPrice());
|
||||
dto.setCategory(notice.getCategory());
|
||||
dto.setStatus(notice.getStatus());
|
||||
dto.setPublishDate(notice.getPublishDate());
|
||||
|
||||
List<AttributeDto> attributes = new ArrayList<>();
|
||||
if (notice.getAttributesNotices() != null) {
|
||||
for (AttributesNotice an : notice.getAttributesNotices()) {
|
||||
AttributeDto attr = new AttributeDto();
|
||||
attr.setName(an.getAttributeValue().getAttribute().getName());
|
||||
attr.setValue(an.getAttributeValue().getValue());
|
||||
attributes.add(attr);
|
||||
}
|
||||
}
|
||||
dto.setAttributes(attributes);
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<NoticeResponseDTO> getAllNotices() {
|
||||
List<NoticeResponseDTO> result = new ArrayList<>();
|
||||
for (Notice notice : noticeRepository.findAll()) {
|
||||
result.add(toDTO(notice));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public NoticeResponseDTO getNoticeById(Long id) {
|
||||
Notice notice = noticeRepository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id));
|
||||
return toDTO(notice);
|
||||
}
|
||||
|
||||
public Notice getNoticeByIdEntity(Long id) {
|
||||
return noticeRepository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id));
|
||||
}
|
||||
|
||||
public Long addNotice(NoticeRequestDTO dto) {
|
||||
Notice notice = fromDTO(dto);
|
||||
notice.setPublishDate(LocalDateTime.now());
|
||||
Notice savedNotice = noticeRepository.save(notice);
|
||||
|
||||
if (dto.getAttributes() != null && !dto.getAttributes().isEmpty()) {
|
||||
saveAttributes(savedNotice.getIdNotice(), dto.getAttributes());
|
||||
}
|
||||
|
||||
return savedNotice.getIdNotice();
|
||||
}
|
||||
|
||||
private void saveAttributes(Long noticeId, List<AttributeDto> attributeDtos) {
|
||||
for (AttributeDto attributeDto : attributeDtos) {
|
||||
Attributes attribute = attributesRepository.findByName(attributeDto.getName())
|
||||
.orElseGet(() -> {
|
||||
Attributes newAttribute = new Attributes();
|
||||
newAttribute.setName(attributeDto.getName());
|
||||
return attributesRepository.save(newAttribute);
|
||||
});
|
||||
|
||||
AttributeValues attributeValue = attributeValuesRepository
|
||||
.findByAttributeAndValue(attribute, attributeDto.getValue())
|
||||
.orElseGet(() -> {
|
||||
AttributeValues newValue = new AttributeValues();
|
||||
newValue.setAttribute(attribute);
|
||||
newValue.setValue(attributeDto.getValue());
|
||||
return attributeValuesRepository.save(newValue);
|
||||
});
|
||||
|
||||
AttributesNotice attributesNotice = new AttributesNotice();
|
||||
attributesNotice.setNotice_id(noticeId);
|
||||
attributesNotice.setAttributeValue(attributeValue);
|
||||
attributesNoticeRepository.save(attributesNotice);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean noticeExists(Long id) {
|
||||
return noticeRepository.existsById(id);
|
||||
}
|
||||
|
||||
public NoticeResponseDTO updateNotice(Long id, NoticeRequestDTO dto) {
|
||||
Notice existingNotice = noticeRepository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id));
|
||||
|
||||
existingNotice.setTitle(dto.getTitle());
|
||||
existingNotice.setDescription(dto.getDescription());
|
||||
existingNotice.setPrice(dto.getPrice());
|
||||
existingNotice.setCategory(dto.getCategory());
|
||||
existingNotice.setStatus(dto.getStatus());
|
||||
|
||||
if (dto.getClientId() != null && !dto.getClientId().equals(existingNotice.getClient().getId())) {
|
||||
Client client = clientRepository.findById(dto.getClientId())
|
||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono klienta o ID: " + dto.getClientId()));
|
||||
existingNotice.setClient(client);
|
||||
}
|
||||
|
||||
return toDTO(noticeRepository.save(existingNotice));
|
||||
}
|
||||
|
||||
public void deleteNotice(Long id) {
|
||||
if (noticeExists(id)) {
|
||||
noticeRepository.deleteById(id);
|
||||
|
||||
List<String> imagesList = new ArrayList<>();
|
||||
|
||||
try {
|
||||
imagesList = imageService.getImagesList(id);
|
||||
} catch (Exception e) {
|
||||
logger.info("There weren't any images for notice with ID: " + id + ". Skipping deletion of images. Message: " + e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
for (String imageName : imagesList) {
|
||||
imageService.deleteImage(uploadDir, imageName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.info("There were some issues while deleting images for notice with ID: " + id + ". Message: " + e.getMessage());
|
||||
}
|
||||
} else {
|
||||
throw new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isNoticeOwnedByClient(long noticeId, long clientId) {
|
||||
return noticeRepository.existsByIdNoticeAndClientId(noticeId, clientId);
|
||||
}
|
||||
|
||||
public void boostNotice(long noticeId) {
|
||||
Notice notice = noticeRepository.findById(noticeId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Ogłoszenie o ID " + noticeId + " nie istnieje."));
|
||||
|
||||
notice.setPublishDate(LocalDateTime.now());
|
||||
|
||||
noticeRepository.save(notice);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.WishlistDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Wishlist;
|
||||
import _11.asktpk.artisanconnectbackend.repository.WishlistRepository;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class WishlistService {
|
||||
|
||||
private final WishlistRepository wishlistRepository;
|
||||
private final NoticeService noticeService;
|
||||
|
||||
public WishlistService(WishlistRepository wishlistRepository, @Lazy NoticeService noticeService) {
|
||||
this.wishlistRepository = wishlistRepository;
|
||||
this.noticeService = noticeService;
|
||||
}
|
||||
|
||||
public List<WishlistDTO> getWishlistForClientId(Long clientId) {
|
||||
List<Wishlist> wishlistEntities = wishlistRepository.findAllByClientId(clientId);
|
||||
return wishlistEntities.stream()
|
||||
.map(this::toDTO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public boolean toggleWishlist(Client client, Notice notice) {
|
||||
Optional<Wishlist> existingEntry = wishlistRepository.findByClientAndNotice(client, notice);
|
||||
|
||||
if (existingEntry.isPresent()) {
|
||||
wishlistRepository.delete(existingEntry.get());
|
||||
return false;
|
||||
} else {
|
||||
Wishlist wishlist = new Wishlist();
|
||||
wishlist.setClient(client);
|
||||
wishlist.setNotice(notice);
|
||||
wishlistRepository.save(wishlist);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private WishlistDTO toDTO(Wishlist wishlist) {
|
||||
WishlistDTO dto = new WishlistDTO();
|
||||
dto.setId(wishlist.getId());
|
||||
dto.setClientId(wishlist.getClient().getId());
|
||||
dto.setNoticeId(wishlist.getNotice().getIdNotice());
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<NoticeResponseDTO> getNoticesInWishlist(Long clientId) {
|
||||
List<Wishlist> wishlistEntries = wishlistRepository.findAllByClientId(clientId);
|
||||
|
||||
return wishlistEntries.stream()
|
||||
.map(wishlist -> noticeService.getNoticeById(wishlist.getNotice().getIdNotice()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package _11.asktpk.artisanconnectbackend.utils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class Enums {
|
||||
public enum Role {
|
||||
ADMIN, USER
|
||||
}
|
||||
|
||||
public enum Category {
|
||||
Handmade, Woodworking, Metalworking, Ceramics,
|
||||
Textiles, Jewelry, Leatherwork, Painting, Sculpture,
|
||||
Glasswork, Furniture, Restoration, Tailoring, Weaving,
|
||||
Calligraphy, Pottery, Blacksmithing, Basketry, Embroidery,
|
||||
Knitting, Carpentry, Other
|
||||
}
|
||||
|
||||
public static final Map<Category, String> categoryPL = Map.ofEntries(
|
||||
Map.entry(Category.Handmade, "Rękodzieło"),
|
||||
Map.entry(Category.Woodworking, "Stolarstwo"),
|
||||
Map.entry(Category.Metalworking, "Obróbka metalu"),
|
||||
Map.entry(Category.Ceramics, "Ceramika"),
|
||||
Map.entry(Category.Textiles, "Tekstylia"),
|
||||
Map.entry(Category.Jewelry, "Biżuteria"),
|
||||
Map.entry(Category.Leatherwork, "Wyroby skórzane"),
|
||||
Map.entry(Category.Painting, "Malarstwo"),
|
||||
Map.entry(Category.Sculpture, "Rzeźbiarstwo"),
|
||||
Map.entry(Category.Glasswork, "Szklarstwo"),
|
||||
Map.entry(Category.Furniture, "Meble"),
|
||||
Map.entry(Category.Restoration, "Renowacja"),
|
||||
Map.entry(Category.Tailoring, "Krawiectwo"),
|
||||
Map.entry(Category.Weaving, "Tkactwo"),
|
||||
Map.entry(Category.Calligraphy, "Kaligrafia"),
|
||||
Map.entry(Category.Pottery, "Garncarstwo"),
|
||||
Map.entry(Category.Blacksmithing, "Kowalstwo"),
|
||||
Map.entry(Category.Basketry, "Koszykarstwo"),
|
||||
Map.entry(Category.Embroidery, "Hafciarstwo"),
|
||||
Map.entry(Category.Knitting, "Dzierganie"),
|
||||
Map.entry(Category.Carpentry, "Ciesielstwo"),
|
||||
Map.entry(Category.Other, "Inne")
|
||||
);
|
||||
|
||||
public enum Status {
|
||||
ACTIVE, INACTIVE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package _11.asktpk.artisanconnectbackend.utils;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class Tools {
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
public Tools(JwtUtil jwtUtil) {
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
public Long getClientIdFromRequest(HttpServletRequest request) {
|
||||
String authorizationHeader = request.getHeader("Authorization");
|
||||
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
|
||||
return jwtUtil.extractUserId(authorizationHeader.substring(7));
|
||||
} else {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user