first steps around moving users to new approach.

This commit is contained in:
Keith Woodlock
2012-05-14 12:47:16 +01:00
parent 9ddaf4c003
commit 7947dda4fe
12 changed files with 449 additions and 279 deletions
@@ -760,11 +760,13 @@ public class ReadPlatformServiceImpl implements ReadPlatformService {
List<OfficeData> offices = retrieveOffices();
List<RoleData> availableRoles = new ArrayList<RoleData>(
retrieveAllRoles());
List<RoleData> availableRoles = new ArrayList<RoleData>(retrieveAllRoles());
AppUser user = this.appUserRepository.findOne(usersThatMatch(
currentUser.getOrganisation(), userId));
AppUser user = this.appUserRepository.findOne(usersThatMatch(currentUser.getOrganisation(), userId));
if (user == null) {
throw new PlatformResourceNotFoundException("error.msg.user.id.invalid", "User with identifier {0} does not exist.", userId);
}
List<RoleData> userRoleData = new ArrayList<RoleData>();
Set<Role> userRoles = user.getRoles();
@@ -8,11 +8,11 @@ import org.mifosng.data.ErrorResponse;
import org.mifosng.data.command.UserCommand;
import org.mifosng.platform.exceptions.NewDataValidationException;
public class UserValidator {
public class UserCommandValidator {
private final UserCommand command;
public UserValidator(UserCommand command) {
public UserCommandValidator(UserCommand command) {
this.command = command;
}
@@ -27,7 +27,7 @@ public class UserValidator {
dataValidationErrors.add(error);
}
if (command.getRoleIds() == null) {
if (command.getSelectedItems() == null) {
ErrorResponse error = new ErrorResponse("validation.msg.user.roles.cannot.be.blank", "selectedItems");
dataValidationErrors.add(error);
}
@@ -15,6 +15,7 @@ import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.mifosng.data.ApiParameterError;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.LoanSchedule;
@@ -42,8 +43,10 @@ import org.mifosng.platform.currency.domain.MonetaryCurrency;
import org.mifosng.platform.currency.domain.Money;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.InvalidSignupException;
import org.mifosng.platform.exceptions.NewDataValidationException;
import org.mifosng.platform.exceptions.NoAuthorizationException;
import org.mifosng.platform.exceptions.PlatformApiDataValidationException;
import org.mifosng.platform.exceptions.PlatformDataIntegrityException;
import org.mifosng.platform.exceptions.PlatformResourceNotFoundException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.infrastructure.BasicPasswordEncodablePlatformUser;
import org.mifosng.platform.infrastructure.PlatformPasswordEncoder;
@@ -147,11 +150,11 @@ public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformServi
try {
AppUser currentUser = extractAuthenticatedUser();
UserValidator validator = new UserValidator(command);
UserCommandValidator validator = new UserCommandValidator(command);
validator.validate();
Set<Role> allRoles = new HashSet<Role>();
for (String roleId : command.getRoleIds()) {
for (String roleId : command.getSelectedItems()) {
Role role = this.roleRepository.findOne(Long.valueOf(roleId));
allRoles.add(role);
}
@@ -173,36 +176,42 @@ public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformServi
@Transactional
@Override
public Long updateUser(UserCommand command) {
try {
AppUser currentUser = extractAuthenticatedUser();
UserValidator validator = new UserValidator(command);
UserCommandValidator validator = new UserCommandValidator(command);
validator.validate();
List<ErrorResponse> dataValidationErrors = new ArrayList<ErrorResponse>();
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
if (command.getId() == null) {
ErrorResponse error = new ErrorResponse("validation.msg.user.id.cannot.be.blank", "id");
ApiParameterError error = ApiParameterError.parameterError("validation.msg.user.id.cannot.be.blank", "The parameter id cannot be empty.", "id");
dataValidationErrors.add(error);
}
if (!dataValidationErrors.isEmpty()) {
throw new NewDataValidationException(dataValidationErrors, "Data validation error exist.");
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
Set<Role> allRoles = new HashSet<Role>();
for (String roleId : command.getRoleIds()) {
for (String roleId : command.getSelectedItems()) {
Role role = this.roleRepository.findOne(Long.valueOf(roleId));
allRoles.add(role);
}
Office office = this.officeRepository.findOne(command.getOfficeId());
if (office == null) {
throw new PlatformResourceNotFoundException("error.msg.office.id.invalid", "Office with identifier {0} does not exist.", command.getOfficeId());
}
AppUser userToUpdate = this.appUserRepository.findOne(usersThatMatch(currentUser.getOrganisation(), command.getId()));
if (userToUpdate == null) {
throw new PlatformResourceNotFoundException("error.msg.user.id.invalid", "User with identifier {0} does not exist.", command.getId());
}
userToUpdate.update(allRoles, office, command.getUsername(), command.getFirstname(), command.getLastname(), command.getEmail());
return userToUpdate.getId();
} catch (DataIntegrityViolationException e) {
throw new UsernameAlreadyExistsException(e);
throw new PlatformDataIntegrityException("validation.msg.username.already.exists.in.organisation", "Username already exists.", "username", command.getUsername());
}
}
@@ -211,7 +220,7 @@ public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformServi
public Long updateCurrentUser(UserCommand command) {
AppUser currentUser = extractAuthenticatedUser();
UserValidator validator = new UserValidator(command);
UserCommandValidator validator = new UserCommandValidator(command);
validator.validateAccountSettingDetails();
AppUser userToUpdate = this.appUserRepository.findOne(currentUser.getId());
@@ -0,0 +1,257 @@
package org.mifosng.platform.api.user;
import java.util.Arrays;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.mifosng.data.AppUserData;
import org.mifosng.data.EntityIdentifier;
import org.mifosng.data.ErrorResponse;
import org.mifosng.data.ErrorResponseList;
import org.mifosng.data.UserList;
import org.mifosng.data.command.ChangePasswordCommand;
import org.mifosng.data.command.UserCommand;
import org.mifosng.platform.ReadPlatformService;
import org.mifosng.platform.WritePlatformService;
import org.mifosng.platform.exceptions.ApplicationDomainRuleException;
import org.mifosng.platform.exceptions.NewDataValidationException;
import org.mifosng.platform.exceptions.UnAuthenticatedUserException;
import org.mifosng.platform.user.domain.AppUser;
import org.mifosng.platform.user.domain.AppUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Path("/v1/users")
@Component
@Scope("singleton")
public class UserApiResource {
private final static Logger logger = LoggerFactory.getLogger(UserApiResource.class);
@Autowired
private ReadPlatformService readPlatformService;
@Autowired
private WritePlatformService writePlatformService;
@Autowired
private AppUserRepository appUserRepository;
private void hardcodeUserIntoSecurityContext() {
AppUser currentUser = this.appUserRepository.findOne(Long.valueOf(1));
Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, currentUser, currentUser.getAuthorities());
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(auth);
}
@GET
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON})
public Response retrieveUsers() {
hardcodeUserIntoSecurityContext();
Collection<AppUserData> users = this.readPlatformService.retrieveAllUsers();
return Response.ok().entity(new UserList(users)).build();
}
@GET
@Path("{userId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response retrieveUser(@PathParam("userId") final Long userId) {
hardcodeUserIntoSecurityContext();
AppUserData user = this.readPlatformService.retrieveUser(userId);
return Response.ok().entity(user).build();
}
@GET
@Path("template")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response newUserDetails() {
hardcodeUserIntoSecurityContext();
AppUserData newUser = this.readPlatformService.retrieveNewUserDetails();
return Response.ok().entity(newUser).build();
}
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response createUser(@Context HttpServletRequest request) {
// try {
String selectedItems = request.getParameter("selectedItems");
final UserCommand command = new UserCommand();
// command.setSelectedItems(Arrays.asList(a));
hardcodeUserIntoSecurityContext();
Long userId = this.writePlatformService.createUser(command);
return Response.ok().entity(new EntityIdentifier(userId)).build();
// } catch (UsernameAlreadyExistsException e) {
// List<ErrorResponse> allErrors = new ArrayList<ErrorResponse>();
// ErrorResponse err = new ErrorResponse("validation.msg.username.already.exists.in.organisation", "username", command.getUsername());
// allErrors.add(err);
//
// throw new WebApplicationException(Response
// .status(Status.BAD_REQUEST)
// .entity(new ErrorResponseList(allErrors)).build());
// } catch (PlatformEmailSendException e) {
// List<ErrorResponse> allErrors = new ArrayList<ErrorResponse>();
// ErrorResponse err = new ErrorResponse("error.msg.user.email.invalid","email", "Email is invalid.");
// allErrors.add(err);
// throw new WebApplicationException(Response
// .status(Status.BAD_REQUEST)
// .entity(new ErrorResponseList(allErrors)).build());
// }
}
@DELETE
@Path("{userId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response deleteUser(@PathParam("userId") final Long userId) {
try {
this.writePlatformService.deleteUser(userId);
return Response.ok().build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@PUT
@Path("{userId}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response updateUser(@PathParam("userId") final Long userId, UserCommand command) {
hardcodeUserIntoSecurityContext();
// UserCommand command = new UserCommand();
// command.setSelectedItems(new ArrayList<String>(commandEile.getSelectedItems()));
command.setId(userId);
this.writePlatformService.updateUser(command);
return Response.ok().entity(new EntityIdentifier(userId)).build();
}
@GET
@Path("user/current")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON})
public Response retrieveCurrentUser() {
try {
hardcodeUserIntoSecurityContext();
AppUserData user = this.readPlatformService.retrieveCurrentUser();
return Response.ok().entity(user).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
@POST
@Path("user/current")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateCurrentUser(UserCommand command) {
try {
hardcodeUserIntoSecurityContext();
Long userId = this.writePlatformService.updateCurrentUser(command);
return Response.ok().entity(new EntityIdentifier(userId)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
} catch (DataIntegrityViolationException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.username.already.exists.in.organisation", "username", command.getUsername());
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
}
}
@POST
@Path("user/current/password")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateCurrentUserPassword(ChangePasswordCommand command) {
try {
hardcodeUserIntoSecurityContext();
Long userId = this.writePlatformService.updateCurrentUserPassword(command);
return Response.ok().entity(new EntityIdentifier(userId)).build();
} catch (UnAuthenticatedUserException e) {
throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
} catch (AccessDeniedException e) {
ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id");
ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse));
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build());
} catch (ApplicationDomainRuleException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build());
} catch (NewDataValidationException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build());
}
}
}