Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -23,4 +24,9 @@ public Page<ReviewDTO> findAllByComponent(@PathVariable long id, Pageable pageab
return reviewsService.findAllByComponent(id, pageable).map(reviewsService::toDTO);
}

@DeleteMapping("/{reviewId}")
public void deleteReview(@PathVariable long id, @PathVariable long reviewId) {
reviewsService.delete(id, reviewId);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,14 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) {
.exceptionHandling(handling -> handling.authenticationEntryPoint(unauthorizedHandlerJwt));

http.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.POST, "/api/v1/components/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/api/v1/components/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/api/v1/components/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/api/v1/components/*/reviews/*").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.GET, "/api/v1/users/me").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.POST, "/api/v1/users/*/image").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.DELETE, "/api/v1/users/**").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.PUT, "/api/v1/users/**").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.POST, "/api/v1/components/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/api/v1/components/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/api/v1/components/**").hasRole("ADMIN")
.anyRequest().permitAll());

http.formLogin(formLogin -> formLogin.disable());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package es.codeurjcstudents.pcmod.service;

import java.util.NoSuchElementException;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

Expand Down Expand Up @@ -51,6 +55,30 @@ public Page<Review> findAllByComponent(long id, Pageable pageable) {
return reviewRepository.findAllByComponentId(id, pageable);
}

@PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)")
public void delete(long componentId, long reviewId) {

Optional<Review> reviewToDelete = reviewRepository.findById(reviewId);

if ((reviewToDelete.isPresent()) && (reviewToDelete.get().getComponent().getId() != componentId)) {
throw new NoSuchElementException("La reseña no pertenece a ese componente.");
}

if (reviewToDelete.isPresent()) {

reviewRepository.deleteById(reviewId);

}

}

public boolean isOwner(long reviewId, String usernameId) {

Optional<Review> review = reviewRepository.findById(reviewId);

return review.isPresent() && (review.get().getUser().getId().equals(Long.valueOf(usernameId)));
}

public ReviewDTO toDTO(Review review) {
return reviewMapper.toDTO(review);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,38 @@
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

@Tag("server-system")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ReviewsSystemTests {

@LocalServerPort
private int port;

@BeforeEach
public void setup() {
RestAssured.port = port;
RestAssured.baseURI = "https://localhost";
RestAssured.basePath = "/api/v1/components";
RestAssured.basePath = "/api/v1/";
RestAssured.useRelaxedHTTPSValidation();
}

@Test
public void getReviewsByComponentId(){
given().header("Content-Type", "application/json")
.when().get("/2/reviews/")
@Test
@Order(1)
public void getReviewsByComponentId() {
given().header("Content-Type", "application/json")
.when().get("components/2/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
// Global checks
.body("totalElements", equalTo(2))
Expand All @@ -42,14 +47,159 @@ public void getReviewsByComponentId(){
.body("content[0].user.username", equalTo("user_example"));
}

@Test
public void getZeroReviewsByComponentId(){
given().header("Content-Type", "application/json")
.when().get("/1/reviews/")
@Test
@Order(2)
public void getZeroReviewsByComponentId() {
given().header("Content-Type", "application/json")
.when().get("components/1/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
// Global checks
.body("content", empty())
.body("totalElements", equalTo(0))
.body("totalPages", equalTo(0));
}

@Test
@Order(3)
public void deleteReviewAsNotLoggedIn() {

given()
.when().delete("components/2/reviews/1")
.then().statusCode(401).contentType(ContentType.JSON)
.body("status", equalTo(401))
.body("error", equalTo("Unauthorized"));
}

@Test
@Order(4)
public void deleteOwnReview() {

given().header("Content-Type", "application/json")
.when().get("components/2/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
.body("totalElements", equalTo(2));

String authToken = given()
.header("Content-Type", "application/json")
.body("""
{
"username": "user@example.com",
"password": "userpass"
}
""")
.when().post("auth/login")
.then().statusCode(200).contentType(ContentType.JSON)
.extract().cookie("AuthToken");

given()
.header("Content-Type", "application/json")
.cookie("AuthToken", authToken)
.when().delete("components/2/reviews/1")
.then().statusCode(200);

given().header("Content-Type", "application/json")
.when().get("components/2/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
.body("totalElements", equalTo(1));

}

@Test
@Order(5)
public void deleteOtherReviewAsNoAdmin() {
String authToken = given()
.header("Content-Type", "application/json")
.body("""
{
"username": "user@example.com",
"password": "userpass"
}
""")
.when().post("auth/login")
.then().statusCode(200).contentType(ContentType.JSON)
.extract().cookie("AuthToken");

given()
.header("Content-Type", "application/json")
.cookie("AuthToken", authToken)
.when().delete("components/2/reviews/2")
.then().statusCode(403).contentType(ContentType.JSON)
.body("error", equalTo("Forbidden"));
}

@Test
@Order(6)
public void deleteReviewsAsAdmin() {

given().header("Content-Type", "application/json")
.when().get("components/2/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
.body("totalElements", equalTo(1));

given().header("Content-Type", "application/json")
.when().get("components/3/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
.body("totalElements", equalTo(1));

String authToken = given()
.header("Content-Type", "application/json")
.body("""
{
"username": "admin@example.com",
"password": "adminpass"
}
""")
.when().post("auth/login")
.then().statusCode(200).contentType(ContentType.JSON)
.extract().cookie("AuthToken");

given()
.header("Content-Type", "application/json")
.cookie("AuthToken", authToken)
.when().delete("components/2/reviews/2")
.then().statusCode(200);

given()
.header("Content-Type", "application/json")
.cookie("AuthToken", authToken)
.when().delete("components/3/reviews/3")
.then().statusCode(200);

given().header("Content-Type", "application/json")
.when().get("components/2/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
.body("totalElements", equalTo(0));

given().header("Content-Type", "application/json")
.when().get("components/3/reviews/")
.then().statusCode(200).contentType(ContentType.JSON)
.body("totalElements", equalTo(0));

}

@Test
@Order(7)
public void deleteReviewWithWrongComponentId() {

String authToken = given()
.header("Content-Type", "application/json")
.body("""
{
"username": "admin@example.com",
"password": "adminpass"
}
""")
.when().post("auth/login")
.then().statusCode(200).contentType(ContentType.JSON)
.extract().cookie("AuthToken");

given()
.header("Content-Type", "application/json")
.cookie("AuthToken", authToken)
.when().delete("components/2/reviews/4")
.then().statusCode(500).contentType(ContentType.JSON)
.body("message", equalTo("La reseña no pertenece a ese componente."));

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public void loadErrorTest() {
}

@Test
public void componentDetailWithoutReviewsRenderTest() {
public void componentDetailRenderTest() {

driver.get("http://localhost:5173/components/1");

Expand All @@ -191,66 +191,6 @@ public void componentDetailWithoutReviewsRenderTest() {
String loadedComponentPrice = driver.findElement(By.id("component-price")).getText();
assertThat(loadedComponentPrice).isEqualTo("350.00 €");

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-reviews-title")));
String loadedComponentReviewsTitle = driver.findElement(By.id("component-reviews-title")).getText();
assertThat(loadedComponentReviewsTitle).isEqualTo("Reseñas del producto:");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-average-rating")));
String loadedComponentAverageRating = driver.findElement(By.id("component-average-rating")).getText();
assertThat(loadedComponentAverageRating).isEqualTo("Puntuación media: ☆☆☆☆☆ 0/5 (0 reseña(s))");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-no-reviews")));
String loadedComponentNoReviews = driver.findElement(By.id("component-no-reviews")).getText();
assertThat(loadedComponentNoReviews).isEqualTo("No hay reseñas de este producto todavía.");

}

@Test
public void componentDetailWithReviewsRenderTest() {

driver.get("http://localhost:5173/components/2");

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-stock")));
String componentStockMessage = driver.findElement(By.id("component-stock")).getText();
assertThat(componentStockMessage).isEqualTo("¡Últimas unidades!");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-name")));
String loadedComponentName = driver.findElement(By.id("component-name")).getText();
assertThat(loadedComponentName).isEqualTo("NVIDIA GeForce RTX 5060 WINDFORCE MAX OC");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-description")));
String loadedComponentDescription = driver.findElement(By.id("component-description")).getText();
assertThat(loadedComponentDescription).contains("Ray Tracing y DLSS 4 para gaming fluido");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-brand-type")));
String loadedComponentBrandType = driver.findElement(By.id("component-brand-type")).getText();
assertThat(loadedComponentBrandType).isEqualTo("Gigabyte | GPU");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-price")));
String loadedComponentPrice = driver.findElement(By.id("component-price")).getText();
assertThat(loadedComponentPrice).isEqualTo("359.85 €");

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-reviews-title")));
String loadedComponentReviewsTitle = driver.findElement(By.id("component-reviews-title")).getText();
assertThat(loadedComponentReviewsTitle).isEqualTo("Reseñas del producto:");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-average-rating")));
String loadedComponentAverageRating = driver.findElement(By.id("component-average-rating")).getText();
assertThat(loadedComponentAverageRating).isEqualTo("Puntuación media: ★★★★☆ 3.5/5 (2 reseña(s))");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("usernameReview-1")));
String loadedUserExample = driver.findElement(By.id("usernameReview-1")).getText();
assertThat(loadedUserExample).isEqualTo("user_example");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-1")));
String loadedUserReview = driver.findElement(By.id("review-title-1")).getText();
assertThat(loadedUserReview).isEqualTo("Buena gráfica, aunque con cosas a mejorar.");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-valoration-1")));
String loadedUserRating = driver.findElement(By.id("review-valoration-1")).getText();
assertThat(loadedUserRating).isEqualTo("Valoración del producto: ★★★★☆ 4/5");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("usernameReview-2")));
String loadedAdminExample = driver.findElement(By.id("usernameReview-2")).getText();
assertThat(loadedAdminExample).isEqualTo("admin_example");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-2")));
String loadedAdminReview = driver.findElement(By.id("review-title-2")).getText();
assertThat(loadedAdminReview).isEqualTo("Tarjeta gráfica bastante mejorable.");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-valoration-2")));
String loadedAdminRating = driver.findElement(By.id("review-valoration-2")).getText();
assertThat(loadedAdminRating).isEqualTo("Valoración del producto: ★★★☆☆ 3/5");

assertThat(driver.findElements(By.id("loadMore"))).isEmpty();

}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public void loginButtonNavigatesToLoginTest() {
scrollToAndClick(By.linkText("Iniciar Sesión"));

wait.until(ExpectedConditions.urlToBe("http://localhost:5173/login"));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login-title"))).isDisplayed();
assertThat(driver.findElement(By.id("login-title")).getText()).isEqualTo("Iniciar sesión:");

}
Expand All @@ -89,6 +90,7 @@ public void registerButtonNavigatesToRegisterTest() {
scrollToAndClick(By.linkText("Registrarse"));

wait.until(ExpectedConditions.urlToBe("http://localhost:5173/register"));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("register-title"))).isDisplayed();
assertThat(driver.findElement(By.id("register-title")).getText()).isEqualTo("Registro:");

}
Expand Down
Loading
Loading