Skip to content

Commit

Permalink
Unified Process/Validate HTTP Handler, +test, doc comments
Browse files Browse the repository at this point in the history
  • Loading branch information
marioferro2002 committed Apr 6, 2024
1 parent 5db601a commit 569329c
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 139 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package cat.udl.eps.softarch.demo.handler;

import cat.udl.eps.softarch.demo.domain.Adoption;
import cat.udl.eps.softarch.demo.exceptions.InvalidPostRequest;
import org.springframework.data.rest.core.annotation.HandleAfterSave;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import cat.udl.eps.softarch.demo.exceptions.UnauthorizedAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
* This class defines event handlers for Adoption entity.
*/
@Component
@RepositoryEventHandler() // Ensure this handler is for MedicalRecord entity
public class AdoptionEventHandler {

private static final Logger logger = LoggerFactory.getLogger(AdoptionEventHandler.class);

/**
* These are the roles that are allowed to create an adoption.
*/
private static final String ROLE_USER = "ROLE_USER";
private static final String ROLE_SHELTER_VOLUNTEER = "ROLE_SHELTER_VOLUNTEER";
private static final String ROLE_ADMIN = "ROLE_ADMIN";

/**
* Handles actions before creating an adoption.
* @param adoption The adoption object to be created.
* @throws UnauthorizedAccessException If the user is not authorized.
* @throws InvalidPostRequest If the request is invalid.
*/
@HandleBeforeCreate
public void handleAdoptionBeforeCreate(Adoption adoption) throws UnauthorizedAccessException, InvalidPostRequest {

checkAuthorization("POST");
// If the pet is already adopted or the pet is null, an exception is thrown
if (adoption.getPet() == null || adoption.getPet().isAdopted() || adoption.getConfirmed()) {
logger.error("Pet is already adopted or bad request");
throw new InvalidPostRequest();
}
// If the adoption is successful, the adoption is in process

logger.info("Adoption for pet {} created successfully ", adoption.getPet().getName());
}

/**
* Handles actions before saving an adoption.
* @param adoption The adoption object to be saved.
* @throws UnauthorizedAccessException If the user is not authorized.
*/
@HandleBeforeSave
public void handleAdoptionBeforeSave(Adoption adoption) throws UnauthorizedAccessException {
checkAuthorization("PUT");
logger.info("Authorized save of adoption for pet {} ", adoption.getPet().getName());
}
// This function is called after editing an adoption
@HandleAfterSave
public void handleAdoptionAfterSave(Adoption adoption) throws UnauthorizedAccessException {
adoption.getPet().setAdopted(true);
logger.info("Pet {} adopted successfully", adoption.getPet().getName());
}


/**
* Checks if the user is authorized to create or edit an adoption.
* @param httpMethod The HTTP method used for the request.
* @throws UnauthorizedAccessException If the user is not authorized.
*/
private void checkAuthorization(String httpMethod) throws UnauthorizedAccessException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!isAuthorized(authentication, httpMethod)) {
throw new UnauthorizedAccessException();
}
}

/**
* Checks if the user is authorized and checks the role of the user.
* @param authentication The authentication object of the user.
* @param HTTPMethod The HTTP method used for the request.
* @return True if the user is authorized, false otherwise.
*/
private boolean isAuthorized(Authentication authentication, String HTTPMethod) {
if (authentication == null || !authentication.isAuthenticated()) {
return false;
}
List<String> requiredAuthorities;

if (HTTPMethod.equals("PUT")) {
requiredAuthorities = Arrays.asList(ROLE_SHELTER_VOLUNTEER, ROLE_ADMIN);
}
else if (HTTPMethod.equals("POST")) {
requiredAuthorities = Arrays.asList(ROLE_SHELTER_VOLUNTEER, ROLE_ADMIN, ROLE_USER);
}
else {
requiredAuthorities = Arrays.asList(ROLE_ADMIN, ROLE_SHELTER_VOLUNTEER);
}
return authentication.getAuthorities().stream()
.anyMatch(grantedAuthority -> requiredAuthorities.contains(grantedAuthority.getAuthority()));
}



}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
import cat.udl.eps.softarch.demo.repository.AdoptionRepository;
import cat.udl.eps.softarch.demo.repository.PetRepository;
import cat.udl.eps.softarch.demo.repository.UserRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
Expand Down Expand Up @@ -39,8 +37,8 @@ public class ValidateAdoptionStepDefs {
protected ResultActions result;


@And("There is a dog with a pending adoption request from user {string}")
public void thereIsAPendingAdoptionRequestForPetFromUser(String arg0) {
@And("There is a dog with a pending adoption request from an user")
public void thereIsAPendingAdoptionRequestForPetFromUser() {
Pet pet = new Pet();
pet.setName("Pet");
pet.setAdopted(false);
Expand All @@ -57,7 +55,7 @@ public void thereIsAPendingAdoptionRequestForPetFromUser(String arg0) {
adoption.setConfirmed(false);
adoption.setStartDate(ZonedDateTime.now());
adoption.setUser(userRepository.findAll().iterator().next());
adoption.setPet(pet);
adoption.setPet(petRepository.findAll().iterator().next());
adoption.setType("Adoption");
adoption.setEndDate(null);
adoptionRepository.save(adoption);
Expand All @@ -66,11 +64,13 @@ public void thereIsAPendingAdoptionRequestForPetFromUser(String arg0) {

@When("I validate the adoption request")
public void iValidateTheAdoptionRequestForPetFromUser() throws Throwable {
Adoption existingAdoption = adoptionRepository.findAll().iterator().next();
existingAdoption.setConfirmed(true);

stepDefs.result = stepDefs.mockMvc.perform(
put("/adoptions")
put("/adoptions/" + existingAdoption.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(stepDefs.mapper.writeValueAsString(adoptionRepository.findAll().iterator().next()))
.content(stepDefs.mapper.writeValueAsString(existingAdoption))
.characterEncoding(StandardCharsets.UTF_8)
.with(AuthenticationStepDefs.authenticate()))
.andDo(print());
Expand Down
13 changes: 9 additions & 4 deletions src/test/resources/features/ValidateAdoption.feature
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,24 @@ Feature: Validate Adoption (Admin or Shelter Volunteer)
Given There is a registered user with username "username" and password "password" and email "[email protected]"
And There is a registered admin with name "admin" and password "password" and email "[email protected]"
And There is a registered volunteer with name "volunteer" and password "password" and email "[email protected]"
And There is a dog with a pending adoption request from user "username"
And There is a dog with a pending adoption request from an user

Scenario: Admin validates adoption request
Given I login as "admin" with password "password"
When I validate the adoption request
And The response code is 200
And The response code is 204

Scenario: Shelter volunteer validates adoption request
Given I login as "volunteer" with password "password"
When I validate the adoption request
And The response code is 200
And The response code is 204

Scenario: User validates adoption request
Given I login as "username" with password "password"
When I validate the adoption request
And The response code is 404
And The response code is 403

Scenario: User is not logged in
Given I'm not logged in
When I validate the adoption request
Then The response code is 401

0 comments on commit 569329c

Please sign in to comment.