Compare commits
9 Commits
MailSender
...
3d064e0496
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d064e0496 | |||
| 501121f235 | |||
| 5262749e2d | |||
| 5f548de73a | |||
| ffbd8d220c | |||
| 0d32b4a495 | |||
| 293be1d46e | |||
| 3b9b0769d1 | |||
| 3e5baa34d1 |
31
pom.xml
31
pom.xml
@@ -44,6 +44,11 @@
|
|||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
<optional>true</optional>
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||||
|
<version>2.4.12</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.postgresql</groupId>
|
<groupId>org.postgresql</groupId>
|
||||||
<artifactId>postgresql</artifactId>
|
<artifactId>postgresql</artifactId>
|
||||||
@@ -83,6 +88,32 @@
|
|||||||
<version>3.3.4</version>
|
<version>3.3.4</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-api</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-impl</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-jackson</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -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,38 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
public class SecurityConfig {
|
||||||
|
|
||||||
|
private final JwtRequestFilter jwtRequestFilter;
|
||||||
|
|
||||||
|
public SecurityConfig(JwtRequestFilter jwtRequestFilter) {
|
||||||
|
this.jwtRequestFilter = jwtRequestFilter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.cors(cors -> cors.configure(http))
|
||||||
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
.requestMatchers("/api/v1/auth/**").permitAll()
|
||||||
|
.anyRequest().authenticated())
|
||||||
|
.sessionManagement(session -> session
|
||||||
|
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||||
|
|
||||||
|
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package _11.asktpk.artisanconnectbackend.controller;
|
||||||
|
|
||||||
|
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||||
|
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||||
|
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||||
|
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.client.HttpClientErrorException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/v1/auth")
|
||||||
|
public class AuthController {
|
||||||
|
|
||||||
|
private final ClientService clientService;
|
||||||
|
private final JwtUtil jwtUtil;
|
||||||
|
|
||||||
|
public AuthController(ClientService clientService, JwtUtil jwtUtil) {
|
||||||
|
this.clientService = clientService;
|
||||||
|
this.jwtUtil = jwtUtil;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ResponseEntity<AuthResponseDTO> login(@RequestBody AuthRequestDTO authRequestDTO) {
|
||||||
|
if (clientService.checkClientCredentials(authRequestDTO)) {
|
||||||
|
Client client = clientService.getClientByEmail(authRequestDTO.getEmail());
|
||||||
|
Long userId = client.getId();
|
||||||
|
String userRole = client.getRole().getRole();
|
||||||
|
|
||||||
|
String token = jwtUtil.generateToken(client.getEmail(), userRole, userId);
|
||||||
|
|
||||||
|
log.info("User logged in with {}", client.getEmail());
|
||||||
|
return ResponseEntity.status(HttpStatus.OK)
|
||||||
|
.body(new AuthResponseDTO(userId, userRole, token));
|
||||||
|
} else {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/register")
|
||||||
|
public ResponseEntity<AuthResponseDTO> register(@RequestBody ClientRegistrationDTO clientDTO) {
|
||||||
|
if (clientService.getClientByEmail(clientDTO.getEmail()) != null) {
|
||||||
|
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
ClientDTO savedClient = clientService.registerClient(clientDTO);
|
||||||
|
|
||||||
|
String token = jwtUtil.generateToken(
|
||||||
|
savedClient.getEmail(),
|
||||||
|
savedClient.getRole(),
|
||||||
|
savedClient.getId()
|
||||||
|
);
|
||||||
|
|
||||||
|
log.info("New user registered with {}", savedClient.getEmail());
|
||||||
|
|
||||||
|
return ResponseEntity.status(HttpStatus.CREATED)
|
||||||
|
.body(new AuthResponseDTO(
|
||||||
|
savedClient.getId(),
|
||||||
|
savedClient.getRole(),
|
||||||
|
token
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/logout")
|
||||||
|
public ResponseEntity<RequestResponseDTO> logout(HttpServletRequest request) {
|
||||||
|
String authHeader = request.getHeader("Authorization");
|
||||||
|
|
||||||
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
jwtUtil.blacklistToken(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) {
|
||||||
|
try {
|
||||||
|
String accessToken = dto.getGoogleToken();
|
||||||
|
String googleUserInfoUrl = "https://www.googleapis.com/oauth2/v3/userinfo";
|
||||||
|
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setBearerAuth(accessToken);
|
||||||
|
HttpEntity<String> entity = new HttpEntity<>(headers);
|
||||||
|
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
ResponseEntity<Map> response = restTemplate.exchange(
|
||||||
|
googleUserInfoUrl, HttpMethod.GET, entity, Map.class);
|
||||||
|
|
||||||
|
Map<String, Object> userInfo = response.getBody();
|
||||||
|
|
||||||
|
// String googleId = (String) userInfo.get("sub"); Potencjalnie możemy używać googlowskiego ID, ale to ma konflikt z naszym generowanym
|
||||||
|
assert userInfo != null;
|
||||||
|
String email = (String) userInfo.get("email");
|
||||||
|
String name = (String) userInfo.get("name");
|
||||||
|
|
||||||
|
Client client = clientService.getClientByEmail(email);
|
||||||
|
if (client == null) {
|
||||||
|
client = new Client();
|
||||||
|
client.setEmail(email);
|
||||||
|
client.setFirstName(name);
|
||||||
|
client.setRole(clientService.getUserRole()); // to pobiera po prostu role "USER" z tabeli w bazie
|
||||||
|
clientService.saveClientToDB(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
String jwt = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
|
||||||
|
|
||||||
|
log.info("User authenticated with google: {}", email);
|
||||||
|
return ResponseEntity.ok(new AuthResponseDTO(client.getId(), client.getRole().getRole(), jwt));
|
||||||
|
} catch (HttpClientErrorException httpClientErrorException) {
|
||||||
|
log.error("Token is invalid or expired");
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new RequestResponseDTO("Invalid access token"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error while checking Google access token", e);
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||||
|
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,16 +24,16 @@ public class ClientController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/get/{id}")
|
@GetMapping("/get/{id}")
|
||||||
public ResponseEntity getClientById(@PathVariable long id) {
|
public ResponseEntity<?> getClientById(@PathVariable long id) {
|
||||||
if(clientService.getClientById(id) != null) {
|
if(clientService.getClientById(id) != null) {
|
||||||
return new ResponseEntity(clientService.getClientById(id), HttpStatus.OK);
|
return new ResponseEntity<>(clientService.getClientByIdDTO(id), HttpStatus.OK);
|
||||||
} else {
|
} else {
|
||||||
return new ResponseEntity(HttpStatus.NOT_FOUND);
|
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/add")
|
@PostMapping("/add")
|
||||||
public ResponseEntity addClient(@RequestBody ClientDTO clientDTO) {
|
public ResponseEntity<?> addClient(@RequestBody ClientDTO clientDTO) {
|
||||||
if(clientService.clientExists(clientDTO.getId())) {
|
if(clientService.clientExists(clientDTO.getId())) {
|
||||||
return new ResponseEntity<>(HttpStatus.CONFLICT);
|
return new ResponseEntity<>(HttpStatus.CONFLICT);
|
||||||
} else {
|
} else {
|
||||||
@@ -43,7 +43,7 @@ public class ClientController {
|
|||||||
|
|
||||||
// TODO: do zrobienia walidacja danych
|
// TODO: do zrobienia walidacja danych
|
||||||
@PutMapping("/edit/{id}")
|
@PutMapping("/edit/{id}")
|
||||||
public ResponseEntity updateClient(@PathVariable("id") long id, @RequestBody ClientDTO clientDTO) {
|
public ResponseEntity<?> updateClient(@PathVariable("id") long id, @RequestBody ClientDTO clientDTO) {
|
||||||
if(clientService.clientExists(id)) {
|
if(clientService.clientExists(id)) {
|
||||||
return new ResponseEntity<>(clientService.updateClient(id, clientDTO),HttpStatus.OK);
|
return new ResponseEntity<>(clientService.updateClient(id, clientDTO),HttpStatus.OK);
|
||||||
} else {
|
} else {
|
||||||
@@ -52,7 +52,7 @@ public class ClientController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/delete/{id}")
|
@DeleteMapping("/delete/{id}")
|
||||||
public ResponseEntity deleteClient(@PathVariable("id") long id) {
|
public ResponseEntity<?> deleteClient(@PathVariable("id") long id) {
|
||||||
if(clientService.clientExists(id)) {
|
if(clientService.clientExists(id)) {
|
||||||
clientService.deleteClient(id);
|
clientService.deleteClient(id);
|
||||||
return new ResponseEntity<>(HttpStatus.OK);
|
return new ResponseEntity<>(HttpStatus.OK);
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import java.util.Map;
|
|||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/vars")
|
@RequestMapping("/api/v1/vars")
|
||||||
public class VariablesController {
|
public class VariablesController {
|
||||||
|
|
||||||
@GetMapping("/categories")
|
@GetMapping("/categories")
|
||||||
public List<CategoriesDTO> getAllVariables() {
|
public List<CategoriesDTO> getAllVariables() {
|
||||||
List<CategoriesDTO> categoriesDTOList = new ArrayList<>();
|
List<CategoriesDTO> categoriesDTOList = new ArrayList<>();
|
||||||
@@ -31,10 +30,4 @@ public class VariablesController {
|
|||||||
public List<Enums.Status> getAllStatuses() {
|
public List<Enums.Status> getAllStatuses() {
|
||||||
return List.of(Enums.Status.values());
|
return List.of(Enums.Status.values());
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/roles")
|
|
||||||
public List<Enums.Role> getAllRoles() {
|
|
||||||
return List.of(Enums.Role.values());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -6,8 +6,6 @@ import lombok.Setter;
|
|||||||
|
|
||||||
import jakarta.validation.constraints.Email;
|
import jakarta.validation.constraints.Email;
|
||||||
|
|
||||||
import _11.asktpk.artisanconnectbackend.utils.Enums.Role;
|
|
||||||
|
|
||||||
@Getter @Setter
|
@Getter @Setter
|
||||||
public class ClientDTO {
|
public class ClientDTO {
|
||||||
private Long id;
|
private Long id;
|
||||||
@@ -18,5 +16,5 @@ public class ClientDTO {
|
|||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
private String image;
|
private String image;
|
||||||
private Role role;
|
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;
|
||||||
|
}
|
||||||
@@ -10,4 +10,8 @@ public class RequestResponseDTO {
|
|||||||
public RequestResponseDTO(String message) {
|
public RequestResponseDTO(String message) {
|
||||||
this.message = message;
|
this.message = message;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String toJSON() {
|
||||||
|
return "{\"message\":\"" + message + "\"}";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.entities;
|
package _11.asktpk.artisanconnectbackend.entities;
|
||||||
|
|
||||||
import _11.asktpk.artisanconnectbackend.utils.Enums.Role;
|
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@@ -24,14 +24,15 @@ public class Client {
|
|||||||
|
|
||||||
private String lastName;
|
private String lastName;
|
||||||
|
|
||||||
private String image; // Optional field
|
private String image;
|
||||||
|
|
||||||
@Enumerated(EnumType.STRING)
|
@ManyToOne(cascade = CascadeType.ALL)
|
||||||
|
@JoinColumn(name = "role_id", referencedColumnName = "id")
|
||||||
private Role role;
|
private Role role;
|
||||||
|
|
||||||
// @OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
|
|
||||||
// private List<Notice> notices;
|
|
||||||
|
|
||||||
@OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
|
@OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
|
||||||
private List<Order> orders;
|
private List<Order> orders;
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
private Date createdAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.entities;
|
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "global_variables")
|
|
||||||
public class GlobalVariables {
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
private Long id;
|
|
||||||
|
|
||||||
private String name;
|
|
||||||
private String value;
|
|
||||||
|
|
||||||
// Getters, setters, and constructors
|
|
||||||
}
|
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
package _11.asktpk.artisanconnectbackend.repository;
|
package _11.asktpk.artisanconnectbackend.repository;
|
||||||
|
|
||||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||||
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
public interface ClientRepository extends JpaRepository<Client, Long> {
|
public interface ClientRepository extends JpaRepository<Client, Long> {
|
||||||
|
Client findByEmail(String email);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
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 findRoleById(Long id);
|
||||||
|
|
||||||
|
Role findRoleByRole(String role);
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
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 or expired. Please login again.\"}";
|
||||||
|
response.getWriter().write(jsonResponse);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
email = jwtUtil.extractEmail(jwt);
|
||||||
|
} catch (ExpiredJwtException expiredJwtException) {
|
||||||
|
logger.error(expiredJwtException.getMessage());
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
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()
|
||||||
|
.setClaims(claims)
|
||||||
|
.setSubject(subject)
|
||||||
|
.setIssuedAt(new Date())
|
||||||
|
.setExpiration(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 <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.parserBuilder()
|
||||||
|
.setSigningKey(getSigningKey())
|
||||||
|
.build()
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
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.entities.Client;
|
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||||
|
import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||||
|
import _11.asktpk.artisanconnectbackend.repository.RolesRepository;
|
||||||
import jakarta.persistence.EntityNotFoundException;
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -11,19 +16,27 @@ import java.util.List;
|
|||||||
@Service
|
@Service
|
||||||
public class ClientService {
|
public class ClientService {
|
||||||
private final ClientRepository clientRepository;
|
private final ClientRepository clientRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final RolesRepository rolesRepository;
|
||||||
|
|
||||||
public ClientService(ClientRepository clientRepository) {
|
public ClientService(ClientRepository clientRepository, PasswordEncoder passwordEncoder, RolesRepository rolesRepository) {
|
||||||
this.clientRepository = clientRepository;
|
this.clientRepository = clientRepository;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.rolesRepository = rolesRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ClientDTO toDto(Client client) {
|
private ClientDTO toDto(Client client) {
|
||||||
|
if(client == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
ClientDTO dto = new ClientDTO();
|
ClientDTO dto = new ClientDTO();
|
||||||
|
|
||||||
dto.setId(client.getId());
|
dto.setId(client.getId());
|
||||||
dto.setFirstName(client.getFirstName());
|
dto.setFirstName(client.getFirstName());
|
||||||
dto.setLastName(client.getLastName());
|
dto.setLastName(client.getLastName());
|
||||||
dto.setEmail(client.getEmail());
|
dto.setEmail(client.getEmail());
|
||||||
dto.setRole(client.getRole());
|
dto.setRole(client.getRole().getRole());
|
||||||
dto.setImage(client.getImage());
|
dto.setImage(client.getImage());
|
||||||
|
|
||||||
return dto;
|
return dto;
|
||||||
@@ -31,17 +44,35 @@ public class ClientService {
|
|||||||
|
|
||||||
private Client fromDto(ClientDTO dto) {
|
private Client fromDto(ClientDTO dto) {
|
||||||
Client client = new Client();
|
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.setId(dto.getId());
|
||||||
client.setFirstName(dto.getFirstName());
|
client.setFirstName(dto.getFirstName());
|
||||||
client.setLastName(dto.getLastName());
|
client.setLastName(dto.getLastName());
|
||||||
client.setEmail(dto.getEmail());
|
client.setEmail(dto.getEmail());
|
||||||
client.setRole(dto.getRole());
|
client.setRole(rola);
|
||||||
client.setImage(dto.getImage());
|
client.setImage(dto.getImage());
|
||||||
|
|
||||||
return client;
|
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() {
|
public List<ClientDTO> getAllClients() {
|
||||||
List<Client> clients = clientRepository.findAll();
|
List<Client> clients = clientRepository.findAll();
|
||||||
return clients.stream().map(this::toDto).toList();
|
return clients.stream().map(this::toDto).toList();
|
||||||
@@ -51,6 +82,10 @@ public class ClientService {
|
|||||||
return clientRepository.findById(id).orElse(null);
|
return clientRepository.findById(id).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ClientDTO getClientByIdDTO(Long id) {
|
||||||
|
return toDto(clientRepository.findById(id).orElse(null));
|
||||||
|
}
|
||||||
|
|
||||||
public boolean clientExists(Long id) {
|
public boolean clientExists(Long id) {
|
||||||
return clientRepository.existsById(id);
|
return clientRepository.existsById(id);
|
||||||
}
|
}
|
||||||
@@ -59,15 +94,21 @@ public class ClientService {
|
|||||||
return toDto(clientRepository.save(fromDto(clientDTO)));
|
return toDto(clientRepository.save(fromDto(clientDTO)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Client saveClientToDB(Client client) {
|
||||||
|
return clientRepository.save(client);
|
||||||
|
}
|
||||||
|
|
||||||
public ClientDTO updateClient(long id, ClientDTO clientDTO) {
|
public ClientDTO updateClient(long id, ClientDTO clientDTO) {
|
||||||
Client existingClient = clientRepository.findById(id)
|
Client existingClient = clientRepository.findById(id)
|
||||||
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id));
|
.orElseThrow(() -> new EntityNotFoundException("Nie znaleziono ogłoszenia o ID: " + id));
|
||||||
|
|
||||||
|
Role newRole = rolesRepository.findRoleByRole(clientDTO.getRole());
|
||||||
|
|
||||||
existingClient.setEmail(clientDTO.getEmail());
|
existingClient.setEmail(clientDTO.getEmail());
|
||||||
existingClient.setFirstName(clientDTO.getFirstName());
|
existingClient.setFirstName(clientDTO.getFirstName());
|
||||||
existingClient.setLastName(clientDTO.getLastName());
|
existingClient.setLastName(clientDTO.getLastName());
|
||||||
existingClient.setImage(clientDTO.getImage());
|
existingClient.setImage(clientDTO.getImage());
|
||||||
existingClient.setRole(clientDTO.getRole());
|
existingClient.setRole(newRole);
|
||||||
|
|
||||||
return toDto(clientRepository.save(existingClient));
|
return toDto(clientRepository.save(existingClient));
|
||||||
}
|
}
|
||||||
@@ -75,4 +116,30 @@ public class ClientService {
|
|||||||
public void deleteClient(Long id) {
|
public void deleteClient(Long id) {
|
||||||
clientRepository.deleteById(id);
|
clientRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// И замените метод checkClientCredentials на:
|
||||||
|
public boolean checkClientCredentials(AuthRequestDTO dto) {
|
||||||
|
Client cl = clientRepository.findByEmail(dto.getEmail());
|
||||||
|
if (cl == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return passwordEncoder.matches(dto.getPassword(), cl.getPassword());
|
||||||
|
}
|
||||||
|
|
||||||
|
// При создании нового пользователя не забудьте шифровать пароль:
|
||||||
|
public ClientDTO registerClient(ClientRegistrationDTO clientDTO) {
|
||||||
|
Client client = fromDto(clientDTO);
|
||||||
|
client.setRole(rolesRepository.findRoleById(1L));
|
||||||
|
client.setPassword(passwordEncoder.encode(client.getPassword()));
|
||||||
|
return toDto(clientRepository.save(client));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Client getClientByEmail(String email) {
|
||||||
|
return clientRepository.findByEmail(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Role getUserRole() {
|
||||||
|
return rolesRepository.findRoleByRole("USER");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,5 +31,9 @@ tpay.authUrl = https://openapi.sandbox.tpay.com/oauth/auth
|
|||||||
tpay.transactionUrl = https://openapi.sandbox.tpay.com/transactions
|
tpay.transactionUrl = https://openapi.sandbox.tpay.com/transactions
|
||||||
tpay.securityCode = )IY7E)YSM!A)Q6O-GN#U7U_33s9qObk8
|
tpay.securityCode = )IY7E)YSM!A)Q6O-GN#U7U_33s9qObk8
|
||||||
|
|
||||||
|
#jwt settings
|
||||||
|
jwt.secret=DIXLsOs3FKmCAQwISd0SKsHMXJrPl3IKIRkVlkOvYW7kEcdUTbxh8zFe1B3eZWkY
|
||||||
|
jwt.expiration=300000
|
||||||
|
|
||||||
logging.file.name=logs/payment-notifications.log
|
logging.file.name=logs/payment-notifications.log
|
||||||
logging.level.TpayLogger=INFO
|
logging.level.TpayLogger=INFO
|
||||||
@@ -1,10 +1,15 @@
|
|||||||
INSERT INTO clients (email, first_name, image, last_name, password, role)
|
INSERT INTO roles (id, rolename)
|
||||||
VALUES
|
VALUES
|
||||||
('dignissim.tempor.arcu@aol.ca', 'Diana', 'null', 'Harrison', 'password', 'USER'),
|
(1, 'USER'),
|
||||||
('john.doe@example.com', 'John', 'null', 'Doe', 'password123', 'ADMIN'),
|
(2, 'ADMIN');
|
||||||
('jane.smith@example.com', 'Jane', 'null', 'Smith', 'securepass', 'USER'),
|
|
||||||
('michael.brown@example.com', 'Michael', 'null', 'Brown', 'mypassword', 'USER'),
|
INSERT INTO clients (email, first_name, last_name, password, role_id)
|
||||||
('emily.jones@example.com', 'Emily', 'null', 'Jones', 'passw0rd', 'USER');
|
VALUES
|
||||||
|
('dignissim.tempor.arcu@aol.ca', 'Diana', 'Harrison', 'password', 1),
|
||||||
|
('john.doe@example.com', 'John', 'Doe', 'password123', 2),
|
||||||
|
('jane.smith@example.com', 'Jane', 'Smith', 'securepass', 1),
|
||||||
|
('michael.brown@example.com', 'Michael', 'Brown', 'mypassword', 1),
|
||||||
|
('emily.jones@example.com', 'Emily', 'Jones', 'passw0rd', 1);
|
||||||
|
|
||||||
|
|
||||||
INSERT INTO notice (title, description, client_id, price, category, status, publish_date) VALUES
|
INSERT INTO notice (title, description, client_id, price, category, status, publish_date) VALUES
|
||||||
|
|||||||
@@ -1,33 +1,591 @@
|
|||||||
package _11.asktpk.artisanconnectbackend;
|
package _11.asktpk.artisanconnectbackend;
|
||||||
|
|
||||||
|
import _11.asktpk.artisanconnectbackend.dto.CategoriesDTO;
|
||||||
|
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||||
|
import _11.asktpk.artisanconnectbackend.dto.NoticeDTO;
|
||||||
|
import _11.asktpk.artisanconnectbackend.dto.WishlistDTO;
|
||||||
|
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||||
|
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||||
|
import _11.asktpk.artisanconnectbackend.entities.Wishlist;
|
||||||
|
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||||
|
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||||
|
import _11.asktpk.artisanconnectbackend.repository.WishlistRepository;
|
||||||
|
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||||
|
import _11.asktpk.artisanconnectbackend.service.ImageService;
|
||||||
|
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||||
|
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||||
|
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||||
|
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import _11.asktpk.artisanconnectbackend.entities.Image;
|
||||||
|
import _11.asktpk.artisanconnectbackend.repository.ImageRepository;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.UrlResource;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
@SpringBootTest
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
|
||||||
|
import static _11.asktpk.artisanconnectbackend.utils.Enums.Role.USER;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Testy dla funkcjonalności klienta w backendzie.
|
||||||
|
*/
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
class ArtisanConnectBackendApplicationTests {
|
class ArtisanConnectBackendApplicationTests {
|
||||||
|
|
||||||
private static final Logger logger = LogManager.getLogger(ArtisanConnectBackendApplicationTests.class);
|
private static final Logger logger = LogManager.getLogger(ArtisanConnectBackendApplicationTests.class);
|
||||||
|
|
||||||
// @Test
|
@LocalServerPort
|
||||||
// void testPostgresDatabase() {
|
private final int port;
|
||||||
// postgresDatabase.add(new Notice("Test Notice", "Username", "Test Description"));
|
|
||||||
// Boolean isRecordAvailable = postgresDatabase.get().size() > 0;
|
private final ClientService clientService;
|
||||||
// if(isRecordAvailable) {
|
private final TestRestTemplate restTemplate;
|
||||||
// logger.info("The record is available in the database");
|
|
||||||
// } else {
|
@Autowired
|
||||||
// logger.error("The record is not available in the database");
|
public ArtisanConnectBackendApplicationTests(ClientService clientService, @LocalServerPort int port) {
|
||||||
// }
|
this.clientService = clientService;
|
||||||
// assert isRecordAvailable;
|
this.port = port;
|
||||||
// }
|
this.restTemplate = new TestRestTemplate();
|
||||||
//
|
}
|
||||||
// @Test
|
|
||||||
// void getAllNotices() throws IOException {
|
|
||||||
// OkHttpClient client = new OkHttpClient().newBuilder()
|
@Nested
|
||||||
// .build();
|
@DisplayName("Testy jednostkowe ClientService")
|
||||||
// MediaType mediaType = MediaType.parse("text/plain");
|
class ClientServiceTest {
|
||||||
// Request request = new Request.Builder()
|
|
||||||
// .url("http://localhost:8080/api/v1/notices/all")
|
private final ClientRepository clientRepository;
|
||||||
// .build();
|
private final ClientService clientService;
|
||||||
// Response response = client.newCall(request).execute();
|
|
||||||
// }
|
ClientServiceTest() {
|
||||||
}
|
logger.info("Inicjalizacja mocków dla ClientService");
|
||||||
|
this.clientRepository = mock(ClientRepository.class);
|
||||||
|
this.clientService = new ClientService(clientRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie mapować klientów na ClientDTO")
|
||||||
|
void testClientMappingToDTO() {
|
||||||
|
logger.info("Tworzenie danych klientów...");
|
||||||
|
Client client = createTestClient("Jan", "Kowalski");
|
||||||
|
when(clientRepository.findAll()).thenReturn(List.of(client));
|
||||||
|
|
||||||
|
logger.info("Wywołanie metody getAllClients...");
|
||||||
|
List<ClientDTO> clientDTOList = clientService.getAllClients();
|
||||||
|
|
||||||
|
assertThat(clientDTOList).hasSize(1);
|
||||||
|
assertThat(clientDTOList.get(0).getFirstName()).isEqualTo("Jan");
|
||||||
|
verify(clientRepository, times(1)).findAll();
|
||||||
|
logger.info("Test zakończony poprawnie");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Client createTestClient(String firstName, String lastName) {
|
||||||
|
Client client = new Client();
|
||||||
|
client.setFirstName(firstName);
|
||||||
|
client.setLastName(lastName);
|
||||||
|
client.setEmail(firstName.toLowerCase() + "." + lastName.toLowerCase() + "@example.com");
|
||||||
|
client.setRole(USER);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("Testy integracyjne ClientController")
|
||||||
|
class ClientControllerTest {
|
||||||
|
|
||||||
|
private final int port;
|
||||||
|
private final TestRestTemplate restTemplate;
|
||||||
|
private final ClientService clientService;
|
||||||
|
private final NoticeService noticeService;
|
||||||
|
private final NoticeRepository noticeRepository;
|
||||||
|
private final Logger logger = LogManager.getLogger(ClientControllerTest.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public ClientControllerTest(
|
||||||
|
@LocalServerPort int port,
|
||||||
|
TestRestTemplate restTemplate,
|
||||||
|
ClientService clientService,
|
||||||
|
NoticeService noticeService,
|
||||||
|
NoticeRepository noticeRepository) {
|
||||||
|
this.port = port;
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.clientService = clientService;
|
||||||
|
this.noticeService = noticeService;
|
||||||
|
this.noticeRepository = noticeRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void cleanDatabase() {
|
||||||
|
|
||||||
|
noticeRepository.deleteAll();
|
||||||
|
|
||||||
|
clientService.getAllClients().forEach(client -> {
|
||||||
|
try {
|
||||||
|
clientService.deleteClient(client.getId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Błąd podczas usuwania klienta: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasNotices(Long clientId) {
|
||||||
|
return noticeService.getAllNotices().stream()
|
||||||
|
.anyMatch(notice -> notice.getClientId().equals(clientId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie usunąć klienta z powiązanymi ogłoszeniami")
|
||||||
|
void shouldDeleteClientWithNotices() {
|
||||||
|
ClientDTO client = clientService.addClient(createTestDTO("client@example.com", "Jan", "Kowalski"));
|
||||||
|
|
||||||
|
NoticeDTO notice = new NoticeDTO();
|
||||||
|
notice.setClientId(client.getId());
|
||||||
|
notice.setTitle("Test Notice");
|
||||||
|
Long noticeId = noticeService.addNotice(notice);
|
||||||
|
|
||||||
|
ResponseEntity<Void> deleteNoticeResponse = restTemplate.exchange(
|
||||||
|
createURLWithPort("/api/v1/notices/delete/" + noticeId),
|
||||||
|
HttpMethod.DELETE,
|
||||||
|
null,
|
||||||
|
Void.class
|
||||||
|
);
|
||||||
|
assertThat(deleteNoticeResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
|
||||||
|
ResponseEntity<Void> deleteClientResponse = restTemplate.exchange(
|
||||||
|
createURLWithPort("/api/v1/clients/delete/" + client.getId()),
|
||||||
|
HttpMethod.DELETE,
|
||||||
|
null,
|
||||||
|
Void.class
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThat(deleteClientResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
assertThat(clientService.clientExists(client.getId())).isFalse();
|
||||||
|
assertThat(noticeService.noticeExists(noticeId)).isFalse();
|
||||||
|
}
|
||||||
|
@Autowired
|
||||||
|
private ClientRepository clientRepository;
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwracać wszystkich klientów")
|
||||||
|
void shouldReturnAllClients() {
|
||||||
|
ClientDTO client1 = clientService.addClient(createTestDTO("client1@example.com", "Anna", "Nowak"));
|
||||||
|
ClientDTO client2 = clientService.addClient(createTestDTO("client2@example.com", "Adam", "Kowalski"));
|
||||||
|
|
||||||
|
ResponseEntity<ClientDTO[]> response = restTemplate.getForEntity(
|
||||||
|
createURLWithPort("/api/v1/clients/get/all"),
|
||||||
|
ClientDTO[].class
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
assertThat(response.getBody()).isNotNull();
|
||||||
|
assertThat(response.getBody()).hasSize(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwrócić błąd przy próbie usunięcia klienta z powiązanymi ogłoszeniami bez kaskady")
|
||||||
|
void shouldFailWhenDeletingClientWithNoticesWithoutCascade() {
|
||||||
|
noticeService.getAllNotices().forEach(n -> noticeService.deleteNotice(n.getNoticeId()));
|
||||||
|
clientService.getAllClients().forEach(c -> clientService.deleteClient(c.getId()));
|
||||||
|
|
||||||
|
ClientDTO client = clientService.addClient(createTestDTO("client@example.com", "Jan", "Kowalski"));
|
||||||
|
|
||||||
|
NoticeDTO notice = new NoticeDTO();
|
||||||
|
notice.setClientId(client.getId());
|
||||||
|
notice.setTitle("Test Notice");
|
||||||
|
noticeService.addNotice(notice);
|
||||||
|
|
||||||
|
try {
|
||||||
|
clientService.deleteClient(client.getId());
|
||||||
|
fail("Powinien zostać rzucony wyjątek DataIntegrityViolationException");
|
||||||
|
} catch (DataIntegrityViolationException e) {
|
||||||
|
// Oczekiwany wyjątek
|
||||||
|
assertThat(e.getMessage()).contains("could not execute statement");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie usunąć klienta bez powiązanych ogłoszeń")
|
||||||
|
void shouldDeleteClientWithoutNotices() {
|
||||||
|
ClientDTO client = clientService.addClient(createTestDTO("client@example.com", "Jan", "Kowalski"));
|
||||||
|
|
||||||
|
ResponseEntity<Void> deleteResponse = restTemplate.exchange(
|
||||||
|
createURLWithPort("/api/v1/clients/delete/" + client.getId()),
|
||||||
|
HttpMethod.DELETE,
|
||||||
|
null,
|
||||||
|
Void.class
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
assertThat(clientService.clientExists(client.getId())).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClientDTO createTestDTO(String email, String firstName, String lastName) {
|
||||||
|
ClientDTO clientDTO = new ClientDTO();
|
||||||
|
clientDTO.setEmail(email);
|
||||||
|
clientDTO.setFirstName(firstName);
|
||||||
|
clientDTO.setLastName(lastName);
|
||||||
|
clientDTO.setRole(USER);
|
||||||
|
return clientDTO;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createURLWithPort(String uri) {
|
||||||
|
return "http://localhost:" + port + uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("Testy jednostkowe NoticeService")
|
||||||
|
class NoticeServiceUnitTest {
|
||||||
|
|
||||||
|
private final NoticeRepository noticeRepository;
|
||||||
|
private final ClientRepository clientRepository;
|
||||||
|
private final NoticeService noticeService;
|
||||||
|
|
||||||
|
NoticeServiceUnitTest() {
|
||||||
|
this.noticeRepository = mock(NoticeRepository.class);
|
||||||
|
this.clientRepository = mock(ClientRepository.class);
|
||||||
|
this.noticeService = new NoticeService(
|
||||||
|
noticeRepository,
|
||||||
|
clientRepository,
|
||||||
|
null,
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie dodać ogłoszenie")
|
||||||
|
void shouldAddNoticeSuccessfully() {
|
||||||
|
Client client = createTestClient("test@example.com", "Anna", "Kowalska");
|
||||||
|
when(clientRepository.findById(1L)).thenReturn(Optional.of(client));
|
||||||
|
|
||||||
|
NoticeDTO noticeDTO = new NoticeDTO();
|
||||||
|
noticeDTO.setClientId(1L);
|
||||||
|
noticeDTO.setTitle("Test Notice");
|
||||||
|
noticeDTO.setDescription("Opis ogłoszenia");
|
||||||
|
noticeDTO.setPrice(100.0);
|
||||||
|
|
||||||
|
Notice notice = new Notice();
|
||||||
|
notice.setIdNotice(1L);
|
||||||
|
|
||||||
|
when(noticeRepository.save(any(Notice.class))).thenReturn(notice);
|
||||||
|
|
||||||
|
Long savedNoticeId = noticeService.addNotice(noticeDTO);
|
||||||
|
|
||||||
|
assertThat(savedNoticeId).isEqualTo(1L);
|
||||||
|
verify(noticeRepository, times(1)).save(any(Notice.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwrócić wyjątek, gdy klient dla ogłoszenia nie istnieje")
|
||||||
|
void shouldThrowExceptionWhenClientNotFound() {
|
||||||
|
NoticeDTO noticeDTO = new NoticeDTO();
|
||||||
|
noticeDTO.setClientId(1L);
|
||||||
|
|
||||||
|
when(clientRepository.findById(1L)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
assertThrows(EntityNotFoundException.class, () -> noticeService.addNotice(noticeDTO));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Client createTestClient(String email, String firstName, String lastName) {
|
||||||
|
Client client = new Client();
|
||||||
|
client.setId(1L);
|
||||||
|
client.setEmail(email);
|
||||||
|
client.setFirstName(firstName);
|
||||||
|
client.setLastName(lastName);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("Testy integracyjne ImageService")
|
||||||
|
class ImageServiceTest {
|
||||||
|
|
||||||
|
private final ImageRepository imageRepository;
|
||||||
|
private final ImageService imageService;
|
||||||
|
|
||||||
|
ImageServiceTest() throws Exception {
|
||||||
|
this.imageRepository = mock(ImageRepository.class);
|
||||||
|
Constructor<ImageService> constructor = ImageService.class.getDeclaredConstructor(ImageRepository.class);
|
||||||
|
constructor.setAccessible(true);
|
||||||
|
this.imageService = constructor.newInstance(imageRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie zapisać obraz w magazynie plików")
|
||||||
|
void shouldSaveImageToStorage() throws IOException {
|
||||||
|
MultipartFile file = mock(MultipartFile.class);
|
||||||
|
when(file.getOriginalFilename()).thenReturn("test.jpg");
|
||||||
|
when(file.getInputStream()).thenReturn(Files.newInputStream(Path.of("src/test/resources/test.jpg")));
|
||||||
|
|
||||||
|
String uploadDirectory = "upload_dir";
|
||||||
|
Path uploadPath = Path.of(uploadDirectory);
|
||||||
|
Files.createDirectories(uploadPath);
|
||||||
|
|
||||||
|
String savedFileName = imageService.saveImageToStorage(uploadDirectory, file);
|
||||||
|
|
||||||
|
assertTrue(savedFileName.contains(".jpg"));
|
||||||
|
assertTrue(Files.exists(uploadPath.resolve(savedFileName)));
|
||||||
|
|
||||||
|
Files.deleteIfExists(uploadPath.resolve(savedFileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie zapisać nazwę obrazu do bazy danych")
|
||||||
|
void shouldAddImageNameToDB() {
|
||||||
|
String filename = UUID.randomUUID() + "test.jpg";
|
||||||
|
Long noticeId = 1L;
|
||||||
|
|
||||||
|
imageService.addImageNameToDB(filename, noticeId);
|
||||||
|
|
||||||
|
verify(imageRepository, times(1)).save(Mockito.any(Image.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie pobrać obraz")
|
||||||
|
void shouldGetImage() throws IOException {
|
||||||
|
Path imagePath = Path.of("src/test/resources/test.jpg");
|
||||||
|
Resource resource = imageService.getImage("src/test/resources", "test.jpg");
|
||||||
|
|
||||||
|
assertNotNull(resource);
|
||||||
|
assertTrue(resource instanceof UrlResource);
|
||||||
|
assertTrue(Files.exists(imagePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zgłosić błąd, gdy obraz nie zostanie znaleziony")
|
||||||
|
void shouldThrowExceptionWhenImageNotFound() {
|
||||||
|
Exception exception = assertThrows(IOException.class, () -> {
|
||||||
|
imageService.getImage("invalid/path", "missing.jpg");
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(exception).hasMessageContaining("File not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie usuwać obraz z magazynu plików i bazy danych")
|
||||||
|
void shouldDeleteImage() throws IOException {
|
||||||
|
Path imagePath = Files.createTempFile("temp-dir", "temp-image.jpg");
|
||||||
|
String imageName = imagePath.getFileName().toString();
|
||||||
|
String imageDirectory = imagePath.getParent().toString();
|
||||||
|
|
||||||
|
Image image = new Image();
|
||||||
|
image.setImageName(imageName);
|
||||||
|
when(imageRepository.existsImageByImageNameEqualsIgnoreCase(imageName)).thenReturn(true);
|
||||||
|
|
||||||
|
imageService.deleteImage(imageDirectory, imageName);
|
||||||
|
|
||||||
|
assertFalse(Files.exists(imagePath));
|
||||||
|
verify(imageRepository, times(1)).deleteByImageNameEquals(imageName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie zwrócić listę nazw obrazów dla podanego ogłoszenia")
|
||||||
|
void shouldGetImagesListForNotice() throws Exception {
|
||||||
|
Long noticeId = 1L;
|
||||||
|
List<Image> images = List.of(
|
||||||
|
createTestImage(1L, noticeId, "image1.jpg"),
|
||||||
|
createTestImage(2L, noticeId, "image2.jpg")
|
||||||
|
);
|
||||||
|
when(imageRepository.findByNoticeId(noticeId)).thenReturn(images);
|
||||||
|
|
||||||
|
List<String> imageNames = imageService.getImagesList(noticeId);
|
||||||
|
|
||||||
|
assertThat(imageNames).hasSize(2);
|
||||||
|
assertThat(imageNames).containsExactly("image1.jpg", "image2.jpg");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Image createTestImage(Long id, Long noticeId, String imageName) {
|
||||||
|
Image image = new Image();
|
||||||
|
image.setId(id);
|
||||||
|
image.setNoticeId(noticeId);
|
||||||
|
image.setImageName(imageName);
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("Testy integracyjne WishlistService")
|
||||||
|
class WishlistServiceTest {
|
||||||
|
|
||||||
|
private final WishlistRepository wishlistRepository;
|
||||||
|
private final NoticeService noticeService;
|
||||||
|
private final WishlistService wishlistService;
|
||||||
|
|
||||||
|
WishlistServiceTest() {
|
||||||
|
this.wishlistRepository = mock(WishlistRepository.class);
|
||||||
|
this.noticeService = mock(NoticeService.class);
|
||||||
|
this.wishlistService = new WishlistService(wishlistRepository, noticeService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie zwrócić wishlist dla klienta")
|
||||||
|
void shouldGetWishlistForClient() {
|
||||||
|
Long clientId = 1L;
|
||||||
|
Wishlist wishlist1 = createTestWishlist(1L, clientId, 10L);
|
||||||
|
Wishlist wishlist2 = createTestWishlist(2L, clientId, 20L);
|
||||||
|
|
||||||
|
when(wishlistRepository.findAllByClientId(clientId)).thenReturn(List.of(wishlist1, wishlist2));
|
||||||
|
|
||||||
|
List<WishlistDTO> result = wishlistService.getWishlistForClientId(clientId);
|
||||||
|
|
||||||
|
assertThat(result).hasSize(2);
|
||||||
|
assertThat(result.get(0).getNoticeId()).isEqualTo(10L);
|
||||||
|
verify(wishlistRepository, times(1)).findAllByClientId(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien poprawnie dodać lub usunąć element z wishlist")
|
||||||
|
void shouldToggleWishlist() {
|
||||||
|
Client client = createTestClient(1L, "test@example.com");
|
||||||
|
Notice notice = createTestNotice(10L);
|
||||||
|
|
||||||
|
// Scenariusz 1: Element istnieje i powinien zostać usunięty
|
||||||
|
when(wishlistRepository.findByClientAndNotice(client, notice)).thenReturn(Optional.of(new Wishlist()));
|
||||||
|
|
||||||
|
boolean removed = wishlistService.toggleWishlist(client, notice);
|
||||||
|
|
||||||
|
assertThat(removed).isFalse();
|
||||||
|
verify(wishlistRepository, times(1)).delete(any(Wishlist.class));
|
||||||
|
|
||||||
|
// Scenariusz 2: Element nie istnieje i powinien zostać dodany
|
||||||
|
when(wishlistRepository.findByClientAndNotice(client, notice)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
boolean added = wishlistService.toggleWishlist(client, notice);
|
||||||
|
|
||||||
|
assertThat(added).isTrue();
|
||||||
|
verify(wishlistRepository, times(1)).save(any(Wishlist.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwrócić listę ogłoszeń w wishlist klienta")
|
||||||
|
void shouldGetNoticesInWishlist() {
|
||||||
|
Long clientId = 1L;
|
||||||
|
Wishlist wishlist1 = createTestWishlist(1L, clientId, 10L);
|
||||||
|
Wishlist wishlist2 = createTestWishlist(2L, clientId, 20L);
|
||||||
|
|
||||||
|
when(wishlistRepository.findAllByClientId(clientId)).thenReturn(List.of(wishlist1, wishlist2));
|
||||||
|
when(noticeService.getNoticeById(10L)).thenReturn(createNoticeDTO(10L, "Ogłoszenie 1"));
|
||||||
|
when(noticeService.getNoticeById(20L)).thenReturn(createNoticeDTO(20L, "Ogłoszenie 2"));
|
||||||
|
|
||||||
|
List<NoticeDTO> result = wishlistService.getNoticesInWishlist(clientId);
|
||||||
|
|
||||||
|
assertThat(result).hasSize(2);
|
||||||
|
assertThat(result.get(0).getNoticeId()).isEqualTo(10L);
|
||||||
|
assertThat(result.get(1).getNoticeId()).isEqualTo(20L);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Wishlist createTestWishlist(Long id, Long clientId, Long noticeId) {
|
||||||
|
Wishlist wishlist = new Wishlist();
|
||||||
|
wishlist.setId(id);
|
||||||
|
|
||||||
|
Client client = new Client();
|
||||||
|
client.setId(clientId);
|
||||||
|
wishlist.setClient(client);
|
||||||
|
|
||||||
|
Notice notice = new Notice();
|
||||||
|
notice.setIdNotice(noticeId);
|
||||||
|
wishlist.setNotice(notice);
|
||||||
|
|
||||||
|
return wishlist;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Client createTestClient(Long id, String email) {
|
||||||
|
Client client = new Client();
|
||||||
|
client.setId(id);
|
||||||
|
client.setEmail(email);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Notice createTestNotice(Long noticeId) {
|
||||||
|
Notice notice = new Notice();
|
||||||
|
notice.setIdNotice(noticeId);
|
||||||
|
return notice;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NoticeDTO createNoticeDTO(Long noticeId, String title) {
|
||||||
|
NoticeDTO noticeDTO = new NoticeDTO();
|
||||||
|
noticeDTO.setNoticeId(noticeId);
|
||||||
|
noticeDTO.setTitle(title);
|
||||||
|
return noticeDTO;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("Testy dla VariablesController")
|
||||||
|
class VariablesControllerTest {
|
||||||
|
|
||||||
|
private final int port;
|
||||||
|
private final TestRestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public VariablesControllerTest(@LocalServerPort int port, TestRestTemplate restTemplate) {
|
||||||
|
this.port = port;
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwrócić kategorie")
|
||||||
|
void shouldGetCategories() {
|
||||||
|
String url = createURLWithPort("/api/v1/vars/categories");
|
||||||
|
|
||||||
|
ResponseEntity<CategoriesDTO[]> response = restTemplate.getForEntity(url, CategoriesDTO[].class);
|
||||||
|
|
||||||
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwrócić statusy")
|
||||||
|
void shouldGetStatuses() {
|
||||||
|
String url = createURLWithPort("/api/v1/vars/statuses");
|
||||||
|
|
||||||
|
ResponseEntity<Enums.Status[]> response = restTemplate.getForEntity(url, Enums.Status[].class);
|
||||||
|
|
||||||
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Powinien zwrócić role")
|
||||||
|
void shouldGetRoles() {
|
||||||
|
String url = createURLWithPort("/api/v1/vars/roles");
|
||||||
|
|
||||||
|
ResponseEntity<Enums.Role[]> response = restTemplate.getForEntity(url, Enums.Role[].class);
|
||||||
|
|
||||||
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createURLWithPort(String uri) {
|
||||||
|
return "http://localhost:" + port + uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
BIN
src/test/resources/test.jpeg
Normal file
BIN
src/test/resources/test.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
BIN
src/test/resources/test.jpg
Normal file
BIN
src/test/resources/test.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
BIN
src/test/resources/test.png
Normal file
BIN
src/test/resources/test.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 435 KiB |
Reference in New Issue
Block a user