Skip to content

Commit

Permalink
Merge branch 'main' into Feature-validate-shelter-certificate
Browse files Browse the repository at this point in the history
  • Loading branch information
peremunoz authored Apr 3, 2024
2 parents 0cf38ef + 151e200 commit 4049f5a
Show file tree
Hide file tree
Showing 13 changed files with 431 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,14 @@ protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exce
.requestMatchers(HttpMethod.GET, "/identity").authenticated()
.requestMatchers(HttpMethod.POST, "/users").anonymous()
.requestMatchers(HttpMethod.POST, "/users/*").denyAll()
.requestMatchers(HttpMethod.POST, "/**/*").authenticated()
.requestMatchers(HttpMethod.PUT, "/**/*").authenticated()
.requestMatchers(HttpMethod.PATCH, "/**/*").authenticated()
.requestMatchers(HttpMethod.DELETE, "/shelters/*").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/**/*").authenticated()
.anyRequest().permitAll())
.requestMatchers("/shelters/**").hasAuthority("ROLE_ADMIN")
.requestMatchers(HttpMethod.POST, "/**/*").authenticated()

.anyRequest().permitAll())
.csrf((csrf) -> csrf.disable())
.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.cors((cors) -> cors.configurationSource(corsConfigurationSource()))
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/cat/udl/eps/softarch/demo/domain/Admin.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ public class Admin extends User{
@Override
@JsonValue(value = false)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Collection<? extends GrantedAuthority> getAuthorities(){
@ElementCollection
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
}
}
3 changes: 0 additions & 3 deletions src/main/java/cat/udl/eps/softarch/demo/domain/Pet.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,4 @@ public class Pet extends UriEntity<Long> {

@ManyToOne
public Shelter isIn;

@ManyToMany
public User[] favouritedBy;
}
5 changes: 5 additions & 0 deletions src/main/java/cat/udl/eps/softarch/demo/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collection;
import java.util.List;

@Entity
@Table(name = "DemoUser") //Avoid collision with system table User
Expand Down Expand Up @@ -75,4 +76,8 @@ public boolean isCredentialsNonExpired() {
public boolean isEnabled() {
return true;
}

@ManyToMany
public List<Pet> favouritedPets;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package cat.udl.eps.softarch.demo.handler;

import cat.udl.eps.softarch.demo.domain.Shelter;
import cat.udl.eps.softarch.demo.repository.ShelterRepository;
import org.springframework.data.rest.core.annotation.HandleAfterSave;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;

import java.time.ZonedDateTime;

@Component
@RepositoryEventHandler
public class ShelterEventHandler {
final ShelterRepository shelterRepository;

public ShelterEventHandler(ShelterRepository shelterRepository) {
this.shelterRepository = shelterRepository;
}

@HandleBeforeCreate
public void handleShelterPreCreate(Shelter shelter) {
shelter.setCreatedAt(ZonedDateTime.now());
shelter.setUpdatedAt(ZonedDateTime.now());

}
@HandleAfterSave
public void handleShelterPostSave(Shelter shelter) {
shelter.setUpdatedAt(ZonedDateTime.now());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
public interface PetRepository extends CrudRepository<Pet, Long>, PagingAndSortingRepository<Pet, Long> {
List<Pet> findBySize(@Param("size") String size);
List<Pet> findByName(@Param("name") String name);
List<Pet> findByIsAdopted(@Param("isAdopted") Boolean isAdopted);
List<Pet> findByBreed(@Param("breed") String breed);
//Pet findByShelter(@Param("id") Long shelterId);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package cat.udl.eps.softarch.demo.steps;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import cat.udl.eps.softarch.demo.domain.*;
import cat.udl.eps.softarch.demo.repository.AdminRepository;
import cat.udl.eps.softarch.demo.repository.ShelterRepository;
import cat.udl.eps.softarch.demo.repository.ShelterVolunteerRepository;
import cat.udl.eps.softarch.demo.repository.UserRepository;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import jakarta.validation.constraints.AssertTrue;
import org.json.JSONObject;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;

public class CreateShelterStepDefs {
@Autowired

private StepDefs stepDefs;
@Autowired
private ShelterRepository shelterRepository;

@Autowired
private UserRepository userRepository;

@Autowired
private ShelterVolunteerRepository ShelterVolunteerRepository;

@Autowired
private AdminRepository adminRepository;

@Given("^There is a registered admin with name \"([^\"]*)\" and password \"([^\"]*)\" and email \"([^\"]*)\"$")
public void thereIsARegisteredAdminWithNameAndPasswordAndEmail(String username, String password, String email) throws Throwable {
if (!adminRepository.existsById(username)) {
Admin user = new Admin();
user.setEmail(email);
user.setId(username);
user.setPassword(password);
user.encodePassword();
adminRepository.save(user);

}
}

@When("^I create a shelter with a name \"([^\"]*)\", email \"([^\"]*)\" and phone \"([^\"]*)\" and location \"([^\"]*)\"$")
public void iCreateAShelterWithAName(String name, String email, String mobile, String location) throws Throwable {;
Shelter newshelter = new Shelter();
newshelter.setName(name);
newshelter.setEmail(email);
newshelter.setMobile(mobile);
newshelter.setCreatedAt(ZonedDateTime.now());
newshelter.setUpdatedAt(ZonedDateTime.now());
//Following code is doing a post request to /shelters storing the response in stepDefs.result to test REST functionalty
stepDefs.result = stepDefs.mockMvc.perform(
post("/shelters")
.contentType(MediaType.APPLICATION_JSON)
.content(stepDefs.mapper.writeValueAsString(newshelter))
.characterEncoding(StandardCharsets.UTF_8)
.with(AuthenticationStepDefs.authenticate()))
.andDo(print());

}

@And("^There is (\\d+) Shelter created$")
public void thereIsShelterCreated(int sheltersCreatedNum) {
Assert.assertEquals("Shelters created", sheltersCreatedNum, shelterRepository.count());
}

@Given("^There is no shelter registered with the name \"([^\"]*)\"$")
public void thereIsNoShelterRegisteredWithTheName(String name) {
Assert.assertTrue("Shelter with name \""
+ name + "\" shouldn't exist", shelterRepository.findByName(name).isEmpty());
}

@Given("^There is a registered volunteer with name \"([^\"]*)\" and password \"([^\"]*)\" and email \"([^\"]*)\"$")
public void thereIsARegisteredVolunteerWithNameAndPasswordAndEmail(String name, String password, String email) {
if(!ShelterVolunteerRepository.existsById(name)) {
ShelterVolunteer volunteer = new ShelterVolunteer();
volunteer.setEmail(email);
volunteer.setId(name);
volunteer.setPassword(password);
volunteer.encodePassword();
ShelterVolunteerRepository.save(volunteer);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package cat.udl.eps.softarch.demo.steps;

import cat.udl.eps.softarch.demo.domain.Shelter;
import cat.udl.eps.softarch.demo.repository.ShelterRepository;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import java.util.List;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

public class DeleteShelterStepDefs {

@Autowired
private StepDefs stepDefs;

@Autowired
private ShelterRepository shelterRepository;


@Given("There is a created shelter with name {string}, email {string} and phone {string}")
public void thereIsACreatedShelterWithNameEmailAndPhone(String name, String email, String phone) {
if (shelterRepository.findByName(name).isEmpty()) {
Shelter shelter = new Shelter();
shelter.setName(name);
shelter.setEmail(email);
shelter.setMobile(phone);
shelter.setLocatedAt(null);

shelterRepository.save(shelter);
}
}

@When("I try to delete Shelter with name {string}")
public void iTryToDeleteShelterWithName(String name) throws Exception {
List<Shelter> shelterList = shelterRepository.findByName(name);

stepDefs.result = stepDefs.mockMvc.perform(
delete("/shelters/{id}", shelterList.isEmpty() ? "0" : shelterList.get(0).getId())
.accept(MediaType.APPLICATION_JSON)
.with(AuthenticationStepDefs.authenticate()))
.andDo(print());
}


}
60 changes: 60 additions & 0 deletions src/test/java/cat/udl/eps/softarch/demo/steps/LoginStepDefs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cat.udl.eps.softarch.demo.steps;

import cat.udl.eps.softarch.demo.domain.User;
import cat.udl.eps.softarch.demo.repository.UserRepository;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class LoginStepDefs {
@Autowired
private StepDefs stepDefs;

@Autowired
private UserRepository userRepository;

@Given("^There isn't registered user with username \"([^\"]*)\"$")
public void thereIsNoRegisteredUserWithUsername(String user) {
Assert.assertFalse("User \""
+ user + "\"shouldn't exist",
userRepository.existsById(user));
}

@Given("^There is a registered user with username \"([^\"]*)\" and password \"([^\"]*)\"$")
public void thereIsARegisteredUserWithUsernameAndPassword(String username, String password) {
if(!userRepository.existsById(username)){
User user = new User();
user.setId(username);
user.setEmail("[email protected]");
user.setPassword(password);
user.encodePassword();
userRepository.save(user);
}
}



@When("^I login with username \"([^\"]*)\" and password \"([^\"]*)\"$")
public void iLoginWithUsernameAndPassword(String username, String password) throws Exception {
AuthenticationStepDefs.currentUsername = username;
AuthenticationStepDefs.currentPassword = password;

stepDefs.result = stepDefs.mockMvc.perform(
get("/identity")
.accept(MediaType.APPLICATION_JSON)
.with(AuthenticationStepDefs.authenticate()))
.andDo(print());
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import cat.udl.eps.softarch.demo.domain.Admin;
import cat.udl.eps.softarch.demo.domain.ShelterVolunteer;
import cat.udl.eps.softarch.demo.domain.User;
import cat.udl.eps.softarch.demo.repository.AdminRepository;
import cat.udl.eps.softarch.demo.repository.ShelterRepository;
import cat.udl.eps.softarch.demo.repository.ShelterVolunteerRepository;
import cat.udl.eps.softarch.demo.repository.UserRepository;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
Expand All @@ -27,6 +32,12 @@ public class RegisterStepDefs {
@Autowired
private UserRepository userRepository;

@Autowired
private AdminRepository adminRepository;

@Autowired
private ShelterVolunteerRepository shelterVolunteerRepository;

@Given("^There is no registered user with username \"([^\"]*)\"$")
public void thereIsNoRegisteredUserWithUsername(String user) {
Assert.assertFalse("User \""
Expand All @@ -46,6 +57,31 @@ public void thereIsARegisteredUserWithUsernameAndPasswordAndEmail(String usernam
}
}


@Given("^There is a registered admin with username \"([^\"]*)\" and password \"([^\"]*)\" and email \"([^\"]*)\"$")
public void thereIsARegisteredAdminWithUsernameAndPasswordAndEmail(String username, String password, String email) {
if (!adminRepository.existsById(username)) {
Admin user = new Admin();
user.setEmail(email);
user.setId(username);
user.setPassword(password);
user.encodePassword();
userRepository.save(user);
}
}

@Given("^There is a registered shelter volunteer with username \"([^\"]*)\" and password \"([^\"]*)\" and email \"([^\"]*)\"$")
public void thereIsARegisteredShelterVolunteerWithUsernameAndPasswordAndEmail(String username, String password, String email) {
if (!shelterVolunteerRepository.existsById(username)) {
ShelterVolunteer user = new ShelterVolunteer();
user.setEmail(email);
user.setId(username);
user.setPassword(password);
user.encodePassword();
userRepository.save(user);
}
}

@And("^I can login with username \"([^\"]*)\" and password \"([^\"]*)\"$")
public void iCanLoginWithUsernameAndPassword(String username, String password) throws Throwable {
AuthenticationStepDefs.currentUsername = username;
Expand Down
Loading

0 comments on commit 4049f5a

Please sign in to comment.