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
@@ -1,5 +1,7 @@
package es.codeurjcstudents.pcmod.controller;

import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest;

import java.net.URI;
import java.security.Principal;

Expand All @@ -11,12 +13,11 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest;

import es.codeurjcstudents.pcmod.dto.ReviewDTO;
import es.codeurjcstudents.pcmod.model.Review;
import es.codeurjcstudents.pcmod.service.ReviewsService;
Expand Down Expand Up @@ -60,4 +61,16 @@ public void deleteReview(@PathVariable long id, @PathVariable long reviewId) {
reviewsService.delete(id, reviewId);
}

@PutMapping("/{reviewId}")
public ResponseEntity<ReviewDTO> updateComponent(@RequestBody ReviewDTO updatedData, @PathVariable long id, @PathVariable long reviewId) {

Review newReviewData = reviewsService.toDomain(updatedData);
Review updatedReview = reviewsService.updateReview(newReviewData, id, reviewId);

URI location = fromCurrentRequest().buildAndExpand(updatedReview.getId()).toUri();

return ResponseEntity.created(location).body(reviewsService.toDTO(updatedReview));

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) {
http.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.POST, "/api/v1/components/*/reviews/").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.DELETE, "/api/v1/components/*/reviews/*").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.PUT, "/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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,48 @@ public Review save(Review review, long userId, long componentId) {
return reviewRepository.save(review);
}

@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);

}

}

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

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

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

List<String> errors = validateReview(newReviewData);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
}

Review review = reviewRepository.findById(reviewId).orElseThrow();
review.setTitle(newReviewData.getTitle());
review.setMessage(newReviewData.getMessage());
review.setRating(newReviewData.getRating());
review.setDate(LocalDate.now(ZoneId.of("Europe/Madrid")));

return reviewRepository.save(review);

}

public boolean hasUserReviewed(Long componentId, Long userId) {
return reviewRepository.existsByComponentIdAndUserId(componentId, userId);
}
Expand Down Expand Up @@ -123,23 +165,6 @@ public void validateRating(Review review, List<String> errors) {

}

@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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -436,4 +436,221 @@ public void deleteReviewWithWrongComponentId() {

}

@Test
public void putReviewAsNoLoggedIn() {
given()
.header("Content-Type", "application/json")
.body("""
{
"title": "sample_title",
"message": "sample_message",
"rating": 5
}
""")
.when().put("/components/2/reviews/1")
.then().statusCode(401).contentType(ContentType.JSON)
.body("error", equalTo("Unauthorized"));
}

@Test
public void putReviewAsRegisteredUserNoAdmin() {
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()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": "sample_title",
"message": "sample_message",
"rating": 5
}
""")
.when().put("/components/2/reviews/1")
.then().statusCode(201).contentType(ContentType.JSON)
.body("id", notNullValue())
.body("title", equalTo("sample_title"))
.body("message", equalTo("sample_message"))
.body("rating", equalTo(5));
}

@Test
public void putOtherUserReviewAsRegisteredUserNoAdmin() {
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()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": "sample_title",
"message": "sample_message",
"rating": 5
}
""")
.when().put("/components/2/reviews/2")
.then().statusCode(403).contentType(ContentType.JSON)
.body("error", equalTo("Forbidden"));
}

@Test
public void putReviewsAsAdmin() {
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()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": "sample_title",
"message": "sample_message",
"rating": 5
}
""")
.when().put("/components/2/reviews/1")
.then().statusCode(201).contentType(ContentType.JSON)
.body("id", notNullValue())
.body("title", equalTo("sample_title"))
.body("message", equalTo("sample_message"))
.body("rating", equalTo(5));

given()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": "sample_title",
"message": "sample_message",
"rating": 5
}
""")
.when().put("/components/2/reviews/2")
.then().statusCode(201).contentType(ContentType.JSON)
.body("id", notNullValue())
.body("title", equalTo("sample_title"))
.body("message", equalTo("sample_message"))
.body("rating", equalTo(5));
}

@Test
public void putVoidReviewData() {
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()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": "",
"message": "",
"rating": ""
}
""")
.when().put("/components/2/reviews/1")
.then().statusCode(500).contentType(ContentType.JSON)
.body("message", equalTo(
"Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria."));
}

@Test
public void putNullComponentData() {
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()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": null,
"message": null,
"rating": null
}
""")
.when().put("/components/2/reviews/1")
.then().statusCode(500).contentType(ContentType.JSON)
.body("message", equalTo(
"Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria."));
}

@Test
public void putBadNumReviewData() {
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()
.cookie("AuthToken", authToken)
.header("Content-Type", "application/json")
.body("""
{
"title": "sample_title",
"message": "sample_message",
"rating": -5
}
""")
.when().put("/components/2/reviews/1")
.then().statusCode(500).contentType(ContentType.JSON)
.body("status", equalTo(500))
.body("message", equalTo(
"Validación fallida:\n• La valoración del producto ha de estar entre 1 y 5."));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ public void loadHomePage() {
wait.until(ExpectedConditions.numberOfElementsToBe(recentComponentNames, 3));
assertThat(driver.findElements(recentComponentNames))
.extracting(WebElement::getText)
.containsExactly(
"testComponent",
.contains(
"Corsair iCUE LINK 3500X RGB",
"Kingston FURY Beast");

Expand Down
Loading
Loading