Solve creation visit bug

This commit is contained in:
PEDSF 2020-12-19 16:46:44 +01:00
parent 8301534007
commit 8792783b10
16 changed files with 76 additions and 120 deletions

View file

@ -27,6 +27,14 @@ public final class CommonError {
public static final String PHONE_FORMAT = "Not a valid phone number !";
public static final String PASSWORD_WRONG_MESSAGE = "Wrong password !";
public static final String PASSWORD_NOT_MATCHING_MESSAGE = "New passwords are not matching !";
public static final String PASSWORD_EMPTY_MESSAGE = "Password can't be empty !";
public static final String PASSWORD_LENGTH_MESSAGE = "Wrong password lenght !";
private CommonError() {
throw new IllegalStateException("Utility class");
}

View file

@ -75,7 +75,7 @@ public class MailConfig {
private ITemplateResolver textTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(Integer.valueOf(1));
templateResolver.setOrder(1);
templateResolver.setResolvablePatterns(Collections.singleton("text/*"));
templateResolver.setPrefix("/mail/");
templateResolver.setSuffix(".txt");
@ -87,7 +87,7 @@ public class MailConfig {
private ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(Integer.valueOf(2));
templateResolver.setOrder(2);
templateResolver.setResolvablePatterns(Collections.singleton("html/*"));
templateResolver.setPrefix("/mail/");
templateResolver.setSuffix(".html");
@ -99,7 +99,7 @@ public class MailConfig {
private ITemplateResolver stringTemplateResolver() {
final StringTemplateResolver templateResolver = new StringTemplateResolver();
templateResolver.setOrder(Integer.valueOf(3));
templateResolver.setOrder(3);
// No resolvable pattern, will simply process as a String template everything not
// previously matched
templateResolver.setTemplateMode("HTML5");

View file

@ -109,11 +109,11 @@ public class UserController extends WebSocketSender {
"Your attempt to create new account. To confirm your account, please click here : ",
CommonEndPoint.PETCLINIC_CONFIRM_ACCOUNT + credential.getToken());
emailService.sendMailAsynch(message, Locale.getDefault());
// emailService.sendMailAsynch(message, Locale.getDefault());
log.info(message.toString());
return CommonView.HOME + user.getId();
return CommonView.HOME;
}
@GetMapping(CommonEndPoint.LOGIN)
@ -156,11 +156,15 @@ public class UserController extends WebSocketSender {
@GetMapping(CommonEndPoint.OAUTH2_SUCCESS)
public String postLoginOAUTH2(Model model, OAuth2AuthenticationToken authentication) {
String firstName;
String lastName;
String email;
String providerId;
String provider = authentication.getAuthorizedClientRegistrationId();
CredentialDTO credential = credentialService.findByAuthentication(authentication);
Map<String, Object> attributes = authentication.getPrincipal().getAttributes();
if (provider.equals(CommonAttribute.GOOGLE)) {
@ -181,8 +185,6 @@ public class UserController extends WebSocketSender {
email = attributes.get(CommonAttribute.EMAIL).toString();
CredentialDTO credential = credentialService.findByAuthentication(authentication);
UserDTO user = userService.findByEmail(email);
if (credential.isNew()) {
@ -246,28 +248,16 @@ public class UserController extends WebSocketSender {
credential.setExpiration(null);
credential = credentialService.save(credential);
// find corresponding user
UserDTO user = userService.findByEmail(credential.getEmail());
// Enabled corresponding user
UserDTO user = userService.setEnabled(credential.getEmail());
securityService.autoLogin(credential.getEmail(), credential.getPassword());
model.addAttribute(CommonAttribute.USER, user);
return CommonView.USER_UPDATE;
}
return CommonView.HOME;
}
@GetMapping(CommonEndPoint.LOGOUT)
public String logout(HttpServletRequest request, HttpServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
new SecurityContextLogoutHandler().logout(request, response, authentication);
}
sendSuccessMessage(CommonWebSocket.USER_LOGGED_OUT);
return CommonView.USER_LOGIN_R;
}
@GetMapping(CommonEndPoint.LOGOUT_SUCCESS)
public String postLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@ -336,7 +326,7 @@ public class UserController extends WebSocketSender {
UserDTO operator = (UserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDTO user = userService.findById(userId);
if (user.equals(operator) || operator.hasRole("ROLE_ADMIN")) {
if (user.getEmail().equals(operator.getEmail()) || operator.hasRole("ROLE_ADMIN")) {
model.addAttribute(CommonAttribute.USER, user);
model.addAttribute(CommonAttribute.USER_ID, user.getId());
return CommonView.USER_CHANGE_PASSWORD;
@ -357,14 +347,33 @@ public class UserController extends WebSocketSender {
// verify the matching with old password
if (!user.matches(oldPassword)) {
bindingResult.rejectValue("password", "6", "Bad password !");
bindingResult.rejectValue(CommonAttribute.PASSWORD, "6", CommonError.PASSWORD_WRONG_MESSAGE);
sendErrorMessage(CommonError.PASSWORD_WRONG_MESSAGE);
model.addAttribute(CommonAttribute.USER, user);
return CommonView.USER_CHANGE_PASSWORD;
}
// verify matching between two password
if (!newPassword.equals(newMatchingPassword)) {
bindingResult.rejectValue("password", "7", "Bad matching password !");
bindingResult.rejectValue(CommonAttribute.PASSWORD, "7", CommonError.PASSWORD_NOT_MATCHING_MESSAGE);
sendErrorMessage(CommonError.PASSWORD_NOT_MATCHING_MESSAGE);
model.addAttribute(CommonAttribute.USER, user);
return CommonView.USER_CHANGE_PASSWORD;
}
// verify password not empty
if (newPassword.isEmpty()) {
bindingResult.rejectValue(CommonAttribute.PASSWORD, "8", CommonError.PASSWORD_EMPTY_MESSAGE);
sendErrorMessage(CommonError.PASSWORD_EMPTY_MESSAGE);
model.addAttribute(CommonAttribute.USER, user);
return CommonView.USER_CHANGE_PASSWORD;
}
// verify password lenght
if (newPassword.length() < CommonParameter.PASSWORD_MIN
|| newPassword.length() > CommonParameter.PASSWORD_MAX) {
bindingResult.rejectValue(CommonAttribute.PASSWORD, "9", CommonError.PASSWORD_LENGTH_MESSAGE);
sendErrorMessage(CommonError.PASSWORD_LENGTH_MESSAGE);
model.addAttribute(CommonAttribute.USER, user);
return CommonView.USER_CHANGE_PASSWORD;
}
@ -376,7 +385,7 @@ public class UserController extends WebSocketSender {
// encode password
user.encode(newPassword);
user = userService.save(user);
sendInfoMessage("Password changed !");
model.addAttribute(CommonAttribute.USER, user);
return CommonView.USER_UPDATE_R;
}

View file

@ -51,7 +51,7 @@ public class CredentialDTO extends BaseDTO {
public CredentialDTO(UserDTO user) {
this.setProvider(CommonParameter.DEFAULT_PROVIDER);
this.email = user.getEmail();
this.password = user.getId().toString();
this.password = user.getPassword();
this.verified = false;
this.setToken();
this.setExpiration();

View file

@ -19,6 +19,7 @@ import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.samples.petclinic.model.business.Pet;
import org.springframework.samples.petclinic.model.business.PetType;
import org.springframework.transaction.annotation.Transactional;
@ -50,7 +51,9 @@ public interface PetRepository extends Repository<Pet, Integer> {
* @param id the id to search for
* @return the {@link Pet} if found
*/
Pet findById(Integer id);
@Query("SELECT DISTINCT pet FROM Pet pet left join fetch pet.owner WHERE pet.id =:id")
@Transactional(readOnly = true)
Pet findById(@Param("id") Integer id);
/**
* Retrieve all {@link Pet}d from the data store by owner id.

View file

@ -3,11 +3,8 @@ package org.springframework.samples.petclinic.service.business;
import org.modelmapper.ModelMapper;
import org.modelmapper.internal.util.Lists;
import org.springframework.samples.petclinic.dto.business.OwnerDTO;
import org.springframework.samples.petclinic.dto.business.PetDTO;
import org.springframework.samples.petclinic.model.business.Owner;
import org.springframework.samples.petclinic.model.business.Pet;
import org.springframework.samples.petclinic.repository.OwnerRepository;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@ -24,25 +21,16 @@ public class OwnerService implements BaseService<Owner, OwnerDTO> {
private final OwnerRepository ownerRepository;
private final PetRepository petRepository;
private final ModelMapper modelMapper = new ModelMapper();
public OwnerService(OwnerRepository ownerRepository, PetRepository petRepository) {
public OwnerService(OwnerRepository ownerRepository) {
this.ownerRepository = ownerRepository;
this.petRepository = petRepository;
}
@Override
public Owner dtoToEntity(OwnerDTO dto) {
if (dto != null) {
Owner owner = modelMapper.map(dto, Owner.class);
dto.getPets().forEach(petDTO -> {
Pet pet = modelMapper.map(petDTO, Pet.class);
pet.setOwner(owner);
owner.addPet(pet);
});
return owner;
return modelMapper.map(dto, Owner.class);
}
return new Owner();
@ -51,13 +39,7 @@ public class OwnerService implements BaseService<Owner, OwnerDTO> {
@Override
public OwnerDTO entityToDTO(Owner entity) {
if (entity != null) {
OwnerDTO ownerDTO = modelMapper.map(entity, OwnerDTO.class);
entity.getPets().forEach(pet -> {
PetDTO petDTO = modelMapper.map(pet, PetDTO.class);
petDTO.setOwner(ownerDTO);
ownerDTO.addPet(petDTO);
});
return ownerDTO;
return modelMapper.map(entity, OwnerDTO.class);
}
return new OwnerDTO();
@ -83,24 +65,12 @@ public class OwnerService implements BaseService<Owner, OwnerDTO> {
@Override
public OwnerDTO findById(int ownerId) {
Owner owner = ownerRepository.findById(ownerId);
List<Pet> pets = petRepository.findByOwnerId(owner.getId());
pets.forEach(pet -> {
// Add pet to the owner
owner.addPet(pet);
// Add owner to the pet
pet.setOwner(owner);
});
return entityToDTO(owner);
return entityToDTO(ownerRepository.findById(ownerId));
}
@Override
public List<OwnerDTO> findAll() {
List<Owner> owners = ownerRepository.findAll();
return entitiesToDTOS(owners);
return entitiesToDTOS(ownerRepository.findAll());
}
@Override

View file

@ -1,7 +1,6 @@
package org.springframework.samples.petclinic.service.business;
import org.modelmapper.ModelMapper;
import org.springframework.samples.petclinic.dto.business.OwnerDTO;
import org.springframework.samples.petclinic.dto.business.PetDTO;
import org.springframework.samples.petclinic.dto.business.PetTypeDTO;
import org.springframework.samples.petclinic.model.business.Owner;
@ -9,10 +8,10 @@ import org.springframework.samples.petclinic.model.business.Pet;
import org.springframework.samples.petclinic.model.business.PetType;
import org.springframework.samples.petclinic.repository.PetRepository;
import org.springframework.samples.petclinic.repository.PetTypeRepository;
import org.springframework.samples.petclinic.repository.VisitRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
@ -27,39 +26,17 @@ public class PetService implements BaseService<Pet, PetDTO> {
private final PetTypeService petTypeService;
private final VisitService visitService;
private final ModelMapper modelMapper = new ModelMapper();
public PetService(PetRepository petRepository, PetTypeRepository petTypeRepository,
VisitRepository visitRepository) {
public PetService(PetRepository petRepository, PetTypeRepository petTypeRepository) {
this.petRepository = petRepository;
this.visitService = new VisitService(visitRepository);
this.petTypeService = new PetTypeService(petTypeRepository);
}
@Override
public Pet dtoToEntity(PetDTO dto) {
if (dto != null) {
Pet pet = modelMapper.map(dto, Pet.class);
PetType petType = modelMapper.map(dto.getType(), PetType.class);
Owner owner = modelMapper.map(dto.getOwner(), Owner.class);
dto.getVisits().forEach(visitDTO -> pet.addVisit(visitService.dtoToEntity(visitDTO)));
dto.getOwner().getPets().forEach(petDTO -> {
if (dto.getId() == null || petDTO.getId().equals(dto.getId())) {
owner.addPet(pet);
}
else {
Pet otherPet = modelMapper.map(petDTO, Pet.class);
otherPet.setOwner(owner);
owner.addPet(otherPet);
}
});
pet.setOwner(owner);
pet.setType(petType);
return pet;
return modelMapper.map(dto, Pet.class);
}
return new Pet();
@ -68,21 +45,7 @@ public class PetService implements BaseService<Pet, PetDTO> {
@Override
public PetDTO entityToDTO(Pet entity) {
if (entity != null) {
PetDTO petDTO = modelMapper.map(entity, PetDTO.class);
PetTypeDTO petTypeDTO = modelMapper.map(entity.getType(), PetTypeDTO.class);
OwnerDTO ownerDTO = modelMapper.map(entity.getOwner(), OwnerDTO.class);
petRepository.findByOwnerId(ownerDTO.getId()).forEach(pet -> {
PetDTO otherPetDTO = modelMapper.map(pet, PetDTO.class);
otherPetDTO.setOwner(ownerDTO);
ownerDTO.addPet(otherPetDTO);
});
entity.getVisits().forEach(visit -> petDTO.addVisit(visitService.entityToDTO(visit)));
petDTO.setOwner(ownerDTO);
petDTO.setType(petTypeDTO);
return petDTO;
return modelMapper.map(entity, PetDTO.class);
}
return new PetDTO();
@ -109,6 +72,9 @@ public class PetService implements BaseService<Pet, PetDTO> {
@Override
public PetDTO findById(int petId) {
Pet pet = petRepository.findById(petId);
Owner owner = pet.getOwner();
owner.setPets(new HashSet<>());
petRepository.findByOwnerId(owner.getId()).forEach(owner::addPet);
return entityToDTO(pet);
}

View file

@ -70,9 +70,7 @@ public class RoleService implements BaseService<Role, RoleDTO> {
Collection<Role> roles = roleRepository.findAll();
List<RoleDTO> roleDTOS = new ArrayList<>();
roles.forEach(role -> {
roleDTOS.add(entityToDTO(role));
});
roles.forEach(role -> roleDTOS.add(entityToDTO(role)));
return roleDTOS;
}

View file

@ -2,9 +2,7 @@ package org.springframework.samples.petclinic.service.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
@ -18,13 +16,10 @@ import org.springframework.stereotype.Service;
@Service("SecurityService")
public class SecurityServiceImpl implements SecurityService {
private final AuthenticationManager authenticationManager;
private final UserDetailsServiceImpl userDetailsService;
@Autowired
public SecurityServiceImpl(AuthenticationManager authenticationManager, UserDetailsServiceImpl userDetailsService) {
this.authenticationManager = authenticationManager;
public SecurityServiceImpl(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}

View file

@ -119,4 +119,11 @@ public class UserService implements BaseService<User, UserDTO> {
return userRepository.existsByEmail(email);
}
public UserDTO setEnabled(String email) {
User user = userRepository.findByEmail(email);
user.setEnabled(true);
user = userRepository.save(user);
return entityToDTO(user);
}
}

View file

@ -24,7 +24,7 @@
<td th:text="${owner.address}"/>
<td th:text="${owner.city}"/>
<td th:text="${owner.telephone}"/>
<td><span th:each="pet : ${owner.pets}" th:text="${pet.name} "/></td>
<td><span th:each="pet : ${owner.pets}" th:text="${pet.name} + ' '"/></td>
</tr>
</tbody>
</table>

View file

@ -13,7 +13,7 @@
<input type="hidden" th:field="${user.enabled}" />
<input type="hidden" th:field="${user.accountNonExpired}" />
<input type="hidden" th:field="${user.accountNonLocked}" />
<input type="hidden" th:field="${user.credentialsNonExpired}" />;
<input type="hidden" th:field="${user.credentialsNonExpired}" />
<input type="hidden" th:field="${user.roles}" />
<input type="hidden" th:field="${user.telephone}" />
<input type="hidden" th:field="${user.street1}" />

View file

@ -41,7 +41,7 @@
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" type="submit">Update</button>
<a class="btn btn-default" th:href="@{'/user/' + ${user.id} + '/edit/password'}">Change password</a>
<a class="btn btn-default" th:href="@{'/users/' + ${user.id} + '/edit/password'}">Change password</a>
<a class="btn btn-default" th:href="@{/}">Cancel</a>
</div>
</div>

View file

@ -223,7 +223,7 @@ class UserControllerTest extends WebSocketSender {
given(credentialService.save(any(CredentialDTO.class))).willReturn(credentialDTO);
mockMvc.perform(post(CommonEndPoint.REGISTER).flashAttr(CommonAttribute.USER, userDTO))
.andExpect(status().is3xxRedirection()).andExpect(view().name(CommonView.HOME + user.getId()));
.andExpect(status().is3xxRedirection()).andExpect(view().name(CommonView.HOME));
}
@Test

View file

@ -78,8 +78,8 @@ class OwnerServiceTest {
@BeforeEach
void beforeEach() {
petService = new PetService(petRepository, petTypeRepository, visitRepository);
ownerService = new OwnerService(ownerRepository, petRepository);
petService = new PetService(petRepository, petTypeRepository);
ownerService = new OwnerService(ownerRepository);
PetTypeService petTypeService = new PetTypeService(petTypeRepository);
Collection<PetTypeDTO> petTypeDTOS = petService.findPetTypes();
PetTypeDTO petTypeDTO = petTypeDTOS.stream().findFirst().get();

View file

@ -67,8 +67,8 @@ class PetServiceTest {
@BeforeEach
void beforeEach() {
this.petService = new PetService(petRepository, petTypeRepository, visitRepository);
this.ownerService = new OwnerService(ownerRepository, petRepository);
this.petService = new PetService(petRepository, petTypeRepository);
this.ownerService = new OwnerService(ownerRepository);
PetTypeService petTypeService = new PetTypeService(petTypeRepository);
Collection<PetTypeDTO> petTypeDTOS = petService.findPetTypes();