MIFOSX-97: some tidy up around users,roles and permissions in prep for command work.

This commit is contained in:
Keith Woodlock
2012-11-22 12:22:41 +00:00
parent baba0b809e
commit 85de5e92c2
28 changed files with 1467 additions and 1673 deletions
@@ -25,28 +25,29 @@ import org.springframework.stereotype.Component;
@Scope("singleton") @Scope("singleton")
public class PermissionsApiResource { public class PermissionsApiResource {
@Autowired @Autowired
private PermissionReadPlatformService permissionReadPlatformService; private PermissionReadPlatformService permissionReadPlatformService;
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "PERMISSION";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveAllPermissions(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); private final String resourceNameForPermissions = "PERMISSION";
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); @GET
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); @Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
final Collection<PermissionData> permissions = this.permissionReadPlatformService.retrieveAllPermissions(); public String retrieveAllPermissions(@Context final UriInfo uriInfo) {
return this.apiJsonSerializerService.serializePermissionDataToJson(prettyPrint, responseParameters, permissions); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
}
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
final Collection<PermissionData> permissions = this.permissionReadPlatformService.retrieveAllPermissions();
return this.apiJsonSerializerService.serializePermissionDataToJson(prettyPrint, responseParameters, permissions);
}
} }
@@ -53,16 +53,17 @@ public class RolesApiResource {
@Autowired @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService; private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "ROLE";
@Autowired @Autowired
private PlatformSecurityContext context; private PlatformSecurityContext context;
private final String resourceNameForPermissions = "ROLE";
@GET @GET
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveAllRoles(@Context final UriInfo uriInfo) { public String retrieveAllRoles(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -74,11 +75,11 @@ public class RolesApiResource {
@GET @GET
@Path("template") @Path("template")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveNewRoleDetails(@Context final UriInfo uriInfo) { public String retrieveNewRoleDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -91,8 +92,8 @@ public class RolesApiResource {
} }
@POST @POST
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String createRole(final String jsonRequestBody) { public String createRole(final String jsonRequestBody) {
final RoleCommand command = this.apiDataConversionService.convertJsonToRoleCommand(null, jsonRequestBody); final RoleCommand command = this.apiDataConversionService.convertJsonToRoleCommand(null, jsonRequestBody);
@@ -112,11 +113,11 @@ public class RolesApiResource {
// into account the Object its looking at. // into account the Object its looking at.
@GET @GET
@Path("{roleId}") @Path("{roleId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveRole(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) { public String retrieveRole(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
@@ -135,8 +136,8 @@ public class RolesApiResource {
@PUT @PUT
@Path("{roleId}") @Path("{roleId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String updateRole(@PathParam("roleId") final Long roleId, final String jsonRequestBody) { public String updateRole(@PathParam("roleId") final Long roleId, final String jsonRequestBody) {
final RoleCommand command = this.apiDataConversionService.convertJsonToRoleCommand(roleId, jsonRequestBody); final RoleCommand command = this.apiDataConversionService.convertJsonToRoleCommand(roleId, jsonRequestBody);
@@ -148,28 +149,27 @@ public class RolesApiResource {
@GET @GET
@Path("{roleId}/permissions") @Path("{roleId}/permissions")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String retrieveRolePermissions(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) { public String retrieveRolePermissions(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters()); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
RoleData role = this.roleReadPlatformService.retrieveRole(roleId); final RoleData role = this.roleReadPlatformService.retrieveRole(roleId);
Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId); final Collection<PermissionUsageData> permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId);
RolePermissionsData permissionsData = new RolePermissionsData(role.getId(), role.getName(), role.getDescription(),
permissionUsageData); final RolePermissionsData permissionsData = role.toRolePermissionData(permissionUsageData);
return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData); return this.apiJsonSerializerService.serializeRolePermissionDataToJson(prettyPrint, responseParameters, permissionsData);
} }
@PUT @PUT
@Path("{roleId}/permissions") @Path("{roleId}/permissions")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON }) @Produces({MediaType.APPLICATION_JSON})
public String updateRolePermissions(@PathParam("roleId") final Long roleId, final String jsonRequestBody) { public String updateRolePermissions(@PathParam("roleId") final Long roleId, final String jsonRequestBody) {
final RolePermissionCommand command = this.apiDataConversionService.convertJsonToRolePermissionCommand(roleId, jsonRequestBody); final RolePermissionCommand command = this.apiDataConversionService.convertJsonToRolePermissionCommand(roleId, jsonRequestBody);
@@ -1,9 +1,7 @@
package org.mifosng.platform.api; package org.mifosng.platform.api;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -41,134 +39,116 @@ import org.springframework.stereotype.Component;
@Scope("singleton") @Scope("singleton")
public class UsersApiResource { public class UsersApiResource {
@Autowired @Autowired
private AppUserReadPlatformService appUserReadPlatformService; private AppUserReadPlatformService appUserReadPlatformService;
@Autowired
private OfficeReadPlatformService officeReadPlatformService;
@Autowired
private AppUserWritePlatformService appUserWritePlatformService;
@Autowired @Autowired
private PortfolioApiDataConversionService apiDataConversionService; private OfficeReadPlatformService officeReadPlatformService;
@Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
private final String entityType = "USER"; @Autowired
@Autowired private AppUserWritePlatformService appUserWritePlatformService;
private PlatformSecurityContext context;
private static final Set<String> typicalResponseParameters = new HashSet<String>(Arrays.asList("id", "officeId", "officeName", "username", "firstname", "lastname", "email", "selectedRoles")); @Autowired
private PortfolioApiDataConversionService apiDataConversionService;
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveUsers(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); @Autowired
private PortfolioApiJsonSerializerService apiJsonSerializerService;
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Collection<AppUserData> users = this.appUserReadPlatformService.retrieveAllUsers(); @Autowired
private PlatformSecurityContext context;
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, users);
} private final String resourceNameForPermissions = "USER";
@GET @GET
@Path("{userId}") @Consumes({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON}) public String retrieveUsers(@Context final UriInfo uriInfo) {
public String retrieveUser(@PathParam("userId") final Long userId, @Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
AppUserData user = this.appUserReadPlatformService.retrieveUser(userId);
if (template) {
List<OfficeLookup> offices = new ArrayList<OfficeLookup>(this.officeReadPlatformService.retrieveAllOfficesForLookup());
user = new AppUserData(user, offices);
addTemplateRelatedParameters(responseParameters);
}
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
}
private void addTemplateRelatedParameters(final Set<String> responseParameters) { final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
responseParameters.add("allowedOffices"); final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
responseParameters.add("availableRoles");
}
@GET final Collection<AppUserData> users = this.appUserReadPlatformService.retrieveAllUsers();
@Path("template")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String newUserDetails(@Context final UriInfo uriInfo) {
context.authenticatedUser().validateHasReadPermission(entityType); return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, users);
}
Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
if (responseParameters.isEmpty()) {
responseParameters.addAll(typicalResponseParameters);
}
addTemplateRelatedParameters(responseParameters);
boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
AppUserData user = this.appUserReadPlatformService.retrieveNewUserDetails();
return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user); @GET
} @Path("{userId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String retrieveUser(@PathParam("userId") final Long userId, @Context final UriInfo uriInfo) {
@POST context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createUser(final String jsonRequestBody) {
UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(null, jsonRequestBody); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
Long userId = this.appUserWritePlatformService.createUser(command); final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
return Response.ok().entity(new EntityIdentifier(userId)).build();
}
@DELETE AppUserData user = this.appUserReadPlatformService.retrieveUser(userId);
@Path("{userId}") if (template) {
@Consumes({MediaType.APPLICATION_JSON}) List<OfficeLookup> offices = new ArrayList<OfficeLookup>(this.officeReadPlatformService.retrieveAllOfficesForLookup());
@Produces({MediaType.APPLICATION_JSON}) user = new AppUserData(user, offices);
public Response deleteUser(@PathParam("userId") final Long userId) { }
this.appUserWritePlatformService.deleteUser(userId); return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
}
return Response.ok(new EntityIdentifier(userId)).build(); @GET
} @Path("template")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public String newUserDetails(@Context final UriInfo uriInfo) {
@PUT context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
@Path("{userId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateUser(@PathParam("userId") final Long userId, final String jsonRequestBody) {
UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(userId, jsonRequestBody); final Set<String> responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
AppUser loggedInUser = context.authenticatedUser(); final AppUserData user = this.appUserReadPlatformService.retrieveNewUserDetails();
if (loggedInUser.hasIdOf(userId)) {
this.appUserWritePlatformService.updateUsersOwnAccountDetails(command);
} else {
this.appUserWritePlatformService.updateUser(command);
}
return Response.ok().entity(new EntityIdentifier(userId)).build(); return this.apiJsonSerializerService.serializeAppUserDataToJson(prettyPrint, responseParameters, user);
} }
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createUser(final String jsonRequestBody) {
final UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(null, jsonRequestBody);
final Long userId = this.appUserWritePlatformService.createUser(command);
return Response.ok().entity(new EntityIdentifier(userId)).build();
}
@DELETE
@Path("{userId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response deleteUser(@PathParam("userId") final Long userId) {
this.appUserWritePlatformService.deleteUser(userId);
return Response.ok(new EntityIdentifier(userId)).build();
}
@PUT
@Path("{userId}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateUser(@PathParam("userId") final Long userId, final String jsonRequestBody) {
final UserCommand command = this.apiDataConversionService.convertJsonToUserCommand(userId, jsonRequestBody);
final AppUser loggedInUser = context.authenticatedUser();
if (loggedInUser.hasIdOf(userId)) {
this.appUserWritePlatformService.updateUsersOwnAccountDetails(command);
} else {
this.appUserWritePlatformService.updateUser(command);
}
return Response.ok().entity(new EntityIdentifier(userId)).build();
}
} }
@@ -7,40 +7,36 @@ import java.util.Set;
*/ */
public class RoleCommand { public class RoleCommand {
private final Long id; private final Long id;
private final String name; private final String name;
private final String description; private final String description;
private final Set<String> modifiedParameters;
public RoleCommand(Set<String> modifiedParameters, final Long id, final String name, final String description, final String[] permissionIds) { private final Set<String> modifiedParameters;
this.modifiedParameters = modifiedParameters;
this.id = id;
this.name = name;
this.description = description;
}
public Long getId() { public RoleCommand(Set<String> modifiedParameters, final Long id, final String name, final String description) {
return id; this.modifiedParameters = modifiedParameters;
} this.id = id;
this.name = name;
this.description = description;
}
public String getName() { public Long getId() {
return name; return id;
} }
public String getDescription() { public String getName() {
return description; return name;
} }
public boolean isNameChanged() { public String getDescription() {
return this.modifiedParameters.contains("name"); return description;
} }
public boolean isDescriptionChanged() { public boolean isNameChanged() {
return this.modifiedParameters.contains("description"); return this.modifiedParameters.contains("name");
} }
public boolean isPermissionsChanged() { public boolean isDescriptionChanged() {
return this.modifiedParameters.contains("permissions"); return this.modifiedParameters.contains("description");
} }
} }
@@ -8,99 +8,67 @@ import java.util.List;
*/ */
public class AppUserData { public class AppUserData {
private final Long id; private final Long id;
private final String username; private final String username;
private final Long officeId; private final Long officeId;
private final String officeName; private final String officeName;
private final String firstname; private final String firstname;
private final String lastname; private final String lastname;
private final String email; private final String email;
private final List<OfficeLookup> allowedOffices; @SuppressWarnings("unused")
private final List<RoleData> availableRoles; private final List<OfficeLookup> allowedOffices;
private final List<RoleData> selectedRoles; private final List<RoleData> availableRoles;
private final List<RoleData> selectedRoles;
public AppUserData(final Long id, final String username, public AppUserData(final Long id, final String username, final String email, final Long officeId, final String officeName,
final String email, final Long officeId, final String firstname, final String lastname, final List<RoleData> availableRoles, final List<RoleData> selectedRoles) {
final String officeName, final String firstname, final String lastname, final List<RoleData> availableRoles, final List<RoleData> selectedRoles) { this.id = id;
this.id = id; this.username = username;
this.username = username; this.officeId = officeId;
this.officeId = officeId; this.officeName = officeName;
this.officeName = officeName; this.firstname = firstname;
this.firstname = firstname; this.lastname = lastname;
this.lastname = lastname; this.email = email;
this.email = email;
this.allowedOffices = new ArrayList<OfficeLookup>();
this.availableRoles = availableRoles;
this.selectedRoles = selectedRoles;
}
public AppUserData(AppUserData user, List<OfficeLookup> allowedOffices) {
this.id = user.getId();
this.username = user.getUsername();
this.officeId = user.getOfficeId();
this.officeName = user.getOfficeName();
this.firstname = user.getFirstname();
this.lastname = user.getLastname();
this.email = user.getEmail();
this.allowedOffices = allowedOffices;
this.availableRoles = user.getAvailableRoles();
this.selectedRoles = user.getSelectedRoles();
}
public AppUserData(final List<OfficeLookup> allowedOffices, final List<RoleData> availableRoles) { this.allowedOffices = new ArrayList<OfficeLookup>();
this.id = null; this.availableRoles = availableRoles;
this.username = null; this.selectedRoles = selectedRoles;
this.officeId = null; }
this.officeName = null;
this.firstname = null;
this.lastname = null;
this.email = null;
this.allowedOffices = allowedOffices;
this.availableRoles = availableRoles;
this.selectedRoles = new ArrayList<RoleData>();
}
public Long getId() { public AppUserData(final AppUserData user, final List<OfficeLookup> allowedOffices) {
return id; this.id = user.id;
} this.username = user.username;
this.officeId = user.officeId;
this.officeName = user.officeName;
this.firstname = user.firstname;
this.lastname = user.lastname;
this.email = user.email;
public String getUsername() { this.allowedOffices = allowedOffices;
return username; this.availableRoles = user.availableRoles;
} this.selectedRoles = user.selectedRoles;
}
public Long getOfficeId() { public AppUserData(final List<OfficeLookup> allowedOffices, final List<RoleData> availableRoles) {
return officeId; this.id = null;
} this.username = null;
this.officeId = null;
this.officeName = null;
this.firstname = null;
this.lastname = null;
this.email = null;
public String getOfficeName() { this.allowedOffices = allowedOffices;
return officeName; this.availableRoles = availableRoles;
} this.selectedRoles = new ArrayList<RoleData>();
}
public String getFirstname() { public boolean hasIdentifyOf(final Long createdById) {
return firstname; return this.id.equals(createdById);
} }
public String getLastname() { public String username() {
return lastname; return this.username;
} }
public String getEmail() {
return email;
}
public List<OfficeLookup> getAllowedOffices() {
return allowedOffices;
}
public List<RoleData> getAvailableRoles() {
return availableRoles;
}
public List<RoleData> getSelectedRoles() {
return selectedRoles;
}
} }
@@ -1,27 +1,23 @@
package org.mifosng.platform.api.data; package org.mifosng.platform.api.data;
/**
* Immutable data object used for office lookups (will remove eventually and just use {@link OfficeData}.
*/
public class OfficeLookup { public class OfficeLookup {
private Long id; private Long id;
private String name; @SuppressWarnings("unused")
private String nameDecorated; private String name;
@SuppressWarnings("unused")
private String nameDecorated;
public OfficeLookup(final Long id, final String name, final String nameDecorated) { public OfficeLookup(final Long id, final String name, final String nameDecorated) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.nameDecorated = nameDecorated; this.nameDecorated = nameDecorated;
} }
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getNameDecorated() {
return nameDecorated;
}
public boolean hasIdentifyOf(final Long officeId) {
return this.id.equals(officeId);
}
} }
@@ -5,29 +5,29 @@ package org.mifosng.platform.api.data;
*/ */
public class PermissionData { public class PermissionData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long id; private final Long id;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String name; private final String name;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String description; private final String description;
private final String code; private final String code;
public PermissionData(final Long id, final String name, final String description, final String code) { public PermissionData(final Long id, final String name, final String description, final String code) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.description = description; this.description = description;
this.code = code; this.code = code;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
PermissionData data = (PermissionData) obj; PermissionData data = (PermissionData) obj;
return this.code.equalsIgnoreCase(data.code); return this.code.equalsIgnoreCase(data.code);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return this.code.hashCode(); return this.code.hashCode();
} }
} }
@@ -1,11 +1,19 @@
package org.mifosng.platform.api.data; package org.mifosng.platform.api.data;
/**
* Immutable representation of permissions
*/
public class PermissionUsageData { public class PermissionUsageData {
@SuppressWarnings("unused")
private final String grouping; private final String grouping;
@SuppressWarnings("unused")
private final String code; private final String code;
@SuppressWarnings("unused")
private final String entityName; private final String entityName;
@SuppressWarnings("unused")
private final String actionName; private final String actionName;
@SuppressWarnings("unused")
private final Boolean selected; private final Boolean selected;
public PermissionUsageData(final String grouping, final String code, final String entityName, final String actionName, public PermissionUsageData(final String grouping, final String code, final String entityName, final String actionName,
@@ -16,25 +24,4 @@ public class PermissionUsageData {
this.actionName = actionName; this.actionName = actionName;
this.selected = selected; this.selected = selected;
} }
public String getGrouping() {
return grouping;
}
public String getCode() {
return code;
}
public String getEntityName() {
return entityName;
}
public String getActionName() {
return actionName;
}
public Boolean getSelected() {
return selected;
}
} }
@@ -8,70 +8,62 @@ import java.util.Collection;
*/ */
public class RoleData { public class RoleData {
private final Long id; private final Long id;
private final String name; private final String name;
private final String description; private final String description;
@SuppressWarnings("unused")
private final Collection<PermissionData> availablePermissions;
private final Collection<PermissionData> selectedPermissions;
public RoleData(final Long id, final String name, final String description) { @SuppressWarnings("unused")
this.id = id; private final Collection<PermissionData> availablePermissions;
this.name = name; private final Collection<PermissionData> selectedPermissions;
this.description = description;
this.availablePermissions = null;
this.selectedPermissions = null;
}
public RoleData(final Long id, final String name, final String description, final Collection<PermissionData> selectedPermissions) {
this.id = id;
this.name = name;
this.description = description;
this.availablePermissions = null;
this.selectedPermissions = selectedPermissions;
}
public RoleData(final Collection<PermissionData> availablePermissions, final Collection<PermissionData> selectedPermissions) {
this.id = null;
this.name = null;
this.description = null;
this.availablePermissions = new ArrayList<PermissionData>(availablePermissions);
this.selectedPermissions = new ArrayList<PermissionData>(selectedPermissions);
}
public RoleData(final RoleData role, final Collection<PermissionData> availablePermissions) { public RoleData(final Long id, final String name, final String description) {
this.id = role.id; this.id = id;
this.name = role.name; this.name = name;
this.description = role.description; this.description = description;
this.availablePermissions = availablePermissions; this.availablePermissions = null;
this.selectedPermissions = role.selectedPermissions; this.selectedPermissions = null;
} }
@Override public RoleData(final Long id, final String name, final String description, final Collection<PermissionData> selectedPermissions) {
public boolean equals(final Object obj) { this.id = id;
final RoleData role = (RoleData) obj; this.name = name;
return this.id.equals(role.id); this.description = description;
} this.availablePermissions = null;
this.selectedPermissions = selectedPermissions;
@Override }
public int hashCode() {
return this.id.hashCode();
}
public Collection<PermissionData> selectedPermissions() { public RoleData(final Collection<PermissionData> availablePermissions, final Collection<PermissionData> selectedPermissions) {
return this.selectedPermissions; this.id = null;
} this.name = null;
this.description = null;
this.availablePermissions = new ArrayList<PermissionData>(availablePermissions);
this.selectedPermissions = new ArrayList<PermissionData>(selectedPermissions);
}
public Long getId() { public RoleData(final RoleData role, final Collection<PermissionData> availablePermissions) {
return id; this.id = role.id;
} this.name = role.name;
this.description = role.description;
this.availablePermissions = availablePermissions;
this.selectedPermissions = role.selectedPermissions;
}
public String getName() { @Override
return name; public boolean equals(final Object obj) {
} final RoleData role = (RoleData) obj;
return this.id.equals(role.id);
}
public String getDescription() { @Override
return description; public int hashCode() {
} return this.id.hashCode();
}
public Collection<PermissionData> selectedPermissions() {
return this.selectedPermissions;
}
public RolePermissionsData toRolePermissionData(final Collection<PermissionUsageData> permissionUsageData) {
return new RolePermissionsData(id, name, description, permissionUsageData);
}
} }
@@ -2,12 +2,19 @@ package org.mifosng.platform.api.data;
import java.util.Collection; import java.util.Collection;
/**
* Immutable data object reprsenting a role with associated permissions.
*/
public class RolePermissionsData { public class RolePermissionsData {
@SuppressWarnings("unused")
private final Long id; private final Long id;
@SuppressWarnings("unused")
private final String name; private final String name;
@SuppressWarnings("unused")
private final String description; private final String description;
@SuppressWarnings("unused")
private final Collection<PermissionUsageData> permissionUsageData; private final Collection<PermissionUsageData> permissionUsageData;
public RolePermissionsData(final Long id, final String name, final String description, public RolePermissionsData(final Long id, final String name, final String description,
@@ -17,21 +24,4 @@ public class RolePermissionsData {
this.description = description; this.description = description;
this.permissionUsageData = permissionUsageData; this.permissionUsageData = permissionUsageData;
} }
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Collection<PermissionUsageData> getPermissionUsageData() {
return permissionUsageData;
}
} }
@@ -241,28 +241,10 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo
Set<String> modifiedParameters = new HashSet<String>(); Set<String> modifiedParameters = new HashSet<String>();
// check array
JsonParser parser = new JsonParser();
String[] permissionIds = null;
JsonElement element = parser.parse(json);
if (element.isJsonObject()) {
JsonObject object = element.getAsJsonObject();
if (object.has("permissions")) {
modifiedParameters.add("permissions");
JsonArray array = object.get("permissions").getAsJsonArray();
permissionIds = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
permissionIds[i] = array.get(i).getAsString();
}
}
}
//
String name = extractStringParameter("name", requestMap, modifiedParameters); String name = extractStringParameter("name", requestMap, modifiedParameters);
String description = extractStringParameter("description", requestMap, modifiedParameters); String description = extractStringParameter("description", requestMap, modifiedParameters);
return new RoleCommand(modifiedParameters, resourceIdentifier, name, description, permissionIds); return new RoleCommand(modifiedParameters, resourceIdentifier, name, description);
} }
@Override @Override
@@ -37,59 +37,56 @@ import org.springframework.stereotype.Service;
@Service @Service
public class ClientReadPlatformServiceImpl implements ClientReadPlatformService { public class ClientReadPlatformServiceImpl implements ClientReadPlatformService {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final OfficeReadPlatformService officeReadPlatformService; private final OfficeReadPlatformService officeReadPlatformService;
private final AppUserReadPlatformService appUserReadPlatformService; private final AppUserReadPlatformService appUserReadPlatformService;
@Autowired @Autowired
public ClientReadPlatformServiceImpl(final PlatformSecurityContext context, public ClientReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
final TenantAwareRoutingDataSource dataSource, final OfficeReadPlatformService officeReadPlatformService, final AppUserReadPlatformService appUserReadPlatformService) {
final OfficeReadPlatformService officeReadPlatformService, this.context = context;
final AppUserReadPlatformService appUserReadPlatformService) { this.officeReadPlatformService = officeReadPlatformService;
this.context = context; this.appUserReadPlatformService = appUserReadPlatformService;
this.officeReadPlatformService = officeReadPlatformService; this.jdbcTemplate = new JdbcTemplate(dataSource);
this.appUserReadPlatformService = appUserReadPlatformService; }
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override @Override
public Collection<ClientData> retrieveAllIndividualClients(final String extraCriteria) { public Collection<ClientData> retrieveAllIndividualClients(final String extraCriteria) {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy(); String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
ClientMapper rm = new ClientMapper();
String sql = "select " + rm.clientSchema(); ClientMapper rm = new ClientMapper();
if (StringUtils.isNotBlank(extraCriteria)) String sql = "select " + rm.clientSchema();
sql += " and (" + extraCriteria + ")";
sql += " order by c.lastname ASC, c.firstname ASC"; if (StringUtils.isNotBlank(extraCriteria)) sql += " and (" + extraCriteria + ")";
return this.jdbcTemplate.query(sql, rm, new Object[] {hierarchySearchString}); sql += " order by c.lastname ASC, c.firstname ASC";
}
@Override return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
public ClientData retrieveIndividualClient(final Long clientId) { }
try { @Override
public ClientData retrieveIndividualClient(final Long clientId) {
AppUser currentUser = context.authenticatedUser(); try {
String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%";
ClientMapper rm = new ClientMapper();
String sql = "select " + rm.clientSchema() + " and c.id = " + clientId; AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] {hierarchySearchString}); ClientMapper rm = new ClientMapper();
} catch (EmptyResultDataAccessException e) {
throw new ClientNotFoundException(clientId); String sql = "select " + rm.clientSchema() + " and c.id = " + clientId;
}
} return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { hierarchySearchString });
} catch (EmptyResultDataAccessException e) {
throw new ClientNotFoundException(clientId);
}
}
@Override @Override
public Collection<ClientLookup> retrieveAllIndividualClientsForLookup(String extraCriteria) { public Collection<ClientLookup> retrieveAllIndividualClientsForLookup(String extraCriteria) {
@@ -100,7 +97,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.clientLookupSchema(); String sql = "select " + rm.clientLookupSchema();
if (StringUtils.isNotBlank(extraCriteria)){ if (StringUtils.isNotBlank(extraCriteria)) {
sql += " and (" + extraCriteria + ")"; sql += " and (" + extraCriteria + ")";
} }
@@ -119,57 +116,53 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
@Override @Override
public ClientData retrieveNewClientDetails() { public ClientData retrieveNewClientDetails() {
final AppUser currentUser = context.authenticatedUser(); final AppUser currentUser = context.authenticatedUser();
final List<OfficeLookup> offices = new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup()); final List<OfficeLookup> offices = new ArrayList<OfficeLookup>(officeReadPlatformService.retrieveAllOfficesForLookup());
final Long officeId = currentUser.getOffice().getId(); final Long officeId = currentUser.getOffice().getId();
return ClientData.template(officeId, new LocalDate(), offices);
}
return ClientData.template(officeId, new LocalDate(), offices);
}
private static final class ClientMapper implements RowMapper<ClientData> {
private static final class ClientMapper implements RowMapper<ClientData> { public String clientSchema() {
return "c.office_id as officeId, o.name as officeName, c.id as id, c.firstname as firstname, c.lastname as lastname, c.display_name as displayName, "
+ "c.external_id as externalId, c.joining_date as joinedDate, c.image_key as imagekey from m_client c join m_office o on o.id = c.office_id "
+ " where o.hierarchy like ? and c.is_deleted=0 ";
}
public String clientSchema() { @Override
return "c.office_id as officeId, o.name as officeName, c.id as id, c.firstname as firstname, c.lastname as lastname, c.display_name as displayName, " + public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
"c.external_id as externalId, c.joining_date as joinedDate, c.image_key as imagekey from m_client c join m_office o on o.id = c.office_id " +
" where o.hierarchy like ? and c.is_deleted=0 ";
}
@Override final Long officeId = JdbcSupport.getLong(rs, "officeId");
public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) final Long id = JdbcSupport.getLong(rs, "id");
throws SQLException { String firstname = rs.getString("firstname");
if (StringUtils.isBlank(firstname)) {
firstname = "";
}
final String lastname = rs.getString("lastname");
final String displayName = rs.getString("displayName");
final String externalId = rs.getString("externalId");
final LocalDate joinedDate = JdbcSupport.getLocalDate(rs, "joinedDate");
final String imageKey = rs.getString("imageKey");
final String officeName = rs.getString("officeName");
final Long officeId = JdbcSupport.getLong(rs, "officeId"); return new ClientData(officeId, officeName, id, firstname, lastname, displayName, externalId, joinedDate, imageKey, null, null,
final Long id = JdbcSupport.getLong(rs, "id"); null);
String firstname = rs.getString("firstname"); }
if (StringUtils.isBlank(firstname)) {
firstname = "";
}
final String lastname = rs.getString("lastname");
final String displayName = rs.getString("displayName");
final String externalId = rs.getString("externalId");
final LocalDate joinedDate = JdbcSupport.getLocalDate(rs, "joinedDate");
final String imageKey = rs.getString("imageKey");
final String officeName = rs.getString("officeName");
return new ClientData(officeId, officeName, id, firstname, }
lastname, displayName, externalId, joinedDate,imageKey, null, null, null);
}
} private static final class ClientLookupMapper implements RowMapper<ClientLookup> {
private static final class ClientLookupMapper implements RowMapper<ClientLookup>{
public String clientLookupSchema() { public String clientLookupSchema() {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + "c.office_id as officeId, o.name as officeName "
"c.office_id as officeId, o.name as officeName " + + "from m_client c join m_office o on o.id = c.office_id where c.is_deleted=0 ";
"from m_client c join m_office o on o.id = c.office_id where c.is_deleted=0 ";
} }
@Override @Override
public ClientLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { public ClientLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
@@ -186,82 +179,83 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
} }
} }
@Override @Override
public ClientAccountSummaryCollectionData retrieveClientAccountDetails(final Long clientId) { public ClientAccountSummaryCollectionData retrieveClientAccountDetails(final Long clientId) {
try { try {
this.context.authenticatedUser(); this.context.authenticatedUser();
// Check if client exists
retrieveIndividualClient(clientId);
List<ClientAccountSummaryData> pendingApprovalLoans = new ArrayList<ClientAccountSummaryData>(); // Check if client exists
List<ClientAccountSummaryData> awaitingDisbursalLoans = new ArrayList<ClientAccountSummaryData>(); retrieveIndividualClient(clientId);
List<ClientAccountSummaryData> openLoans = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> closedLoans = new ArrayList<ClientAccountSummaryData>();
ClientLoanAccountSummaryDataMapper rm = new ClientLoanAccountSummaryDataMapper(); List<ClientAccountSummaryData> pendingApprovalLoans = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> awaitingDisbursalLoans = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> openLoans = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> closedLoans = new ArrayList<ClientAccountSummaryData>();
String sql = "select " + rm.loanAccountSummarySchema() + " where l.client_id = ?"; ClientLoanAccountSummaryDataMapper rm = new ClientLoanAccountSummaryDataMapper();
List<ClientAccountSummaryData> results = this.jdbcTemplate.query(sql, rm, new Object[] {clientId}); String sql = "select " + rm.loanAccountSummarySchema() + " where l.client_id = ?";
if (results != null) {
for (ClientAccountSummaryData row : results) {
LoanStatusMapper statusMapper = new LoanStatusMapper(row.getAccountStatusId()); List<ClientAccountSummaryData> results = this.jdbcTemplate.query(sql, rm, new Object[] { clientId });
if (results != null) {
for (ClientAccountSummaryData row : results) {
if (statusMapper.isOpen()) { LoanStatusMapper statusMapper = new LoanStatusMapper(row.getAccountStatusId());
openLoans.add(row);
} else if (statusMapper.isAwaitingDisbursal()) {
awaitingDisbursalLoans.add(row);
} else if (statusMapper.isPendingApproval()) {
pendingApprovalLoans.add(row);
} else {
closedLoans.add(row);
}
}
}
List<ClientAccountSummaryData> pendingApprovalDepositAccounts = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> approvedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> withdrawnByClientDespositAccounts = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> closedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> rejectedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> preclosedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
List<ClientAccountSummaryData> maturedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
ClientDespoitAccountSummaryDataMapper depositAccountMapper = new ClientDespoitAccountSummaryDataMapper();
String depositAccountsSql = "select " + depositAccountMapper.schema() + " where da.client_id = ? and da.is_deleted=0"; if (statusMapper.isOpen()) {
List<ClientAccountSummaryData> depositAccountResults = this.jdbcTemplate.query(depositAccountsSql, depositAccountMapper, new Object[] {clientId}); openLoans.add(row);
if (depositAccountResults != null) { } else if (statusMapper.isAwaitingDisbursal()) {
for (ClientAccountSummaryData row : depositAccountResults) { awaitingDisbursalLoans.add(row);
} else if (statusMapper.isPendingApproval()) {
pendingApprovalLoans.add(row);
} else {
closedLoans.add(row);
}
}
}
if (row.getAccountStatusId() == 100) { List<ClientAccountSummaryData> pendingApprovalDepositAccounts = new ArrayList<ClientAccountSummaryData>();
pendingApprovalDepositAccounts.add(row); List<ClientAccountSummaryData> approvedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
} else if (row.getAccountStatusId() == 300) { List<ClientAccountSummaryData> withdrawnByClientDespositAccounts = new ArrayList<ClientAccountSummaryData>();
approvedDepositAccounts.add(row); List<ClientAccountSummaryData> closedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
} else if (row.getAccountStatusId() == 400) { List<ClientAccountSummaryData> rejectedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
withdrawnByClientDespositAccounts.add(row); List<ClientAccountSummaryData> preclosedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
} else if (row.getAccountStatusId() == 500) { List<ClientAccountSummaryData> maturedDepositAccounts = new ArrayList<ClientAccountSummaryData>();
rejectedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 600) {
closedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 700) {
maturedDepositAccounts.add(row);
}else if (row.getAccountStatusId() == 800) {
preclosedDepositAccounts.add(row);
}
}
}
return new ClientAccountSummaryCollectionData(pendingApprovalLoans, awaitingDisbursalLoans, openLoans, closedLoans, ClientDespoitAccountSummaryDataMapper depositAccountMapper = new ClientDespoitAccountSummaryDataMapper();
pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts,
rejectedDepositAccounts,closedDepositAccounts,preclosedDepositAccounts,maturedDepositAccounts); String depositAccountsSql = "select " + depositAccountMapper.schema() + " where da.client_id = ? and da.is_deleted=0";
} catch (EmptyResultDataAccessException e) { List<ClientAccountSummaryData> depositAccountResults = this.jdbcTemplate.query(depositAccountsSql, depositAccountMapper,
throw new ClientNotFoundException(clientId); new Object[] { clientId });
} if (depositAccountResults != null) {
} for (ClientAccountSummaryData row : depositAccountResults) {
if (row.getAccountStatusId() == 100) {
pendingApprovalDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 300) {
approvedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 400) {
withdrawnByClientDespositAccounts.add(row);
} else if (row.getAccountStatusId() == 500) {
rejectedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 600) {
closedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 700) {
maturedDepositAccounts.add(row);
} else if (row.getAccountStatusId() == 800) {
preclosedDepositAccounts.add(row);
}
}
}
return new ClientAccountSummaryCollectionData(pendingApprovalLoans, awaitingDisbursalLoans, openLoans, closedLoans,
pendingApprovalDepositAccounts, approvedDepositAccounts, withdrawnByClientDespositAccounts, rejectedDepositAccounts,
closedDepositAccounts, preclosedDepositAccounts, maturedDepositAccounts);
} catch (EmptyResultDataAccessException e) {
throw new ClientNotFoundException(clientId);
}
}
@Override @Override
public Collection<ClientAccountSummaryData> retrieveClientLoanAccountsByLoanOfficerId(Long clientId, Long loanOfficerId) { public Collection<ClientAccountSummaryData> retrieveClientLoanAccountsByLoanOfficerId(Long clientId, Long loanOfficerId) {
@@ -275,282 +269,251 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService
String sql = "select " + rm.loanAccountSummarySchema() + " where l.client_id = ? and l.loan_officer_id = ?"; String sql = "select " + rm.loanAccountSummarySchema() + " where l.client_id = ? and l.loan_officer_id = ?";
List<ClientAccountSummaryData> loanAccounts = this.jdbcTemplate.query(sql, rm, new Object[] {clientId, loanOfficerId}); List<ClientAccountSummaryData> loanAccounts = this.jdbcTemplate.query(sql, rm, new Object[] { clientId, loanOfficerId });
return loanAccounts; return loanAccounts;
} }
private static final class ClientLoanAccountSummaryDataMapper implements private static final class ClientLoanAccountSummaryDataMapper implements RowMapper<ClientAccountSummaryData> {
RowMapper<ClientAccountSummaryData> {
public String loanAccountSummarySchema() { public String loanAccountSummarySchema() {
StringBuilder accountsSummary = new StringBuilder("l.id as id, l.external_id as externalId,"); StringBuilder accountsSummary = new StringBuilder("l.id as id, l.external_id as externalId,");
accountsSummary accountsSummary.append("l.product_id as productId, lp.name as productName,").append("l.loan_status_id as statusId ")
.append("l.product_id as productId, lp.name as productName,") .append("from m_loan l ").append("LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id ");
.append("l.loan_status_id as statusId ")
.append("from m_loan l ")
.append("LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id ");
return accountsSummary.toString(); return accountsSummary.toString();
} }
@Override @Override
public ClientAccountSummaryData mapRow(final ResultSet rs, public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
@SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id"); Long id = JdbcSupport.getLong(rs, "id");
String externalId = rs.getString("externalId"); String externalId = rs.getString("externalId");
Long productId = JdbcSupport.getLong(rs, "productId"); Long productId = JdbcSupport.getLong(rs, "productId");
String loanProductName = rs.getString("productName"); String loanProductName = rs.getString("productName");
Integer loanStatusId = JdbcSupport.getInteger(rs, "statusId"); Integer loanStatusId = JdbcSupport.getInteger(rs, "statusId");
return new ClientAccountSummaryData(id, externalId, productId, loanProductName, loanStatusId); return new ClientAccountSummaryData(id, externalId, productId, loanProductName, loanStatusId);
} }
} }
private static final class ClientDespoitAccountSummaryDataMapper implements RowMapper<ClientAccountSummaryData> {
public String schema() { private static final class ClientDespoitAccountSummaryDataMapper implements RowMapper<ClientAccountSummaryData> {
StringBuilder accountsSummary = new StringBuilder("da.id as id, da.external_id as externalId,");
accountsSummary.append("da.product_id as productId, dp.name as productName,")
.append("da.status_enum as statusId ")
.append("from m_deposit_account da ")
.append("LEFT JOIN m_product_deposit AS dp ON dp.id = da.product_id ");
return accountsSummary.toString();
}
@Override
public ClientAccountSummaryData mapRow(final ResultSet rs,
@SuppressWarnings("unused") final int rowNum) throws SQLException {
Long id = JdbcSupport.getLong(rs, "id");
String externalId = rs.getString("externalId");
Long productId = JdbcSupport.getLong(rs, "productId");
String productName = rs.getString("productName");
Integer accountStatusId = JdbcSupport.getInteger(rs, "statusId");
return new ClientAccountSummaryData(id, externalId, productId, productName, accountStatusId);
}
}
@Override public String schema() {
public NoteData retrieveClientNote(Long clientId, Long noteId) {
try { StringBuilder accountsSummary = new StringBuilder("da.id as id, da.external_id as externalId,");
context.authenticatedUser(); accountsSummary.append("da.product_id as productId, dp.name as productName,").append("da.status_enum as statusId ")
.append("from m_deposit_account da ").append("LEFT JOIN m_product_deposit AS dp ON dp.id = da.product_id ");
// Check if client exists
retrieveIndividualClient(clientId);
// FIXME - use join on sql query to fetch user information for note return accountsSummary.toString();
// rather than fetching users? }
Collection<AppUserData> allUsers = this.appUserReadPlatformService
.retrieveAllUsers();
NoteMapper noteMapper = new NoteMapper(allUsers); @Override
public ClientAccountSummaryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
String sql = "select " + noteMapper.schema() Long id = JdbcSupport.getLong(rs, "id");
+ " where n.client_id = ? and n.id = ?"; String externalId = rs.getString("externalId");
Long productId = JdbcSupport.getLong(rs, "productId");
String productName = rs.getString("productName");
Integer accountStatusId = JdbcSupport.getInteger(rs, "statusId");
return this.jdbcTemplate.queryForObject(sql, noteMapper, new Object[] {clientId, noteId}); return new ClientAccountSummaryData(id, externalId, productId, productName, accountStatusId);
} catch (EmptyResultDataAccessException e) { }
throw new NoteNotFoundException(clientId); }
}
}
@Override @Override
public Collection<NoteData> retrieveAllClientNotes(Long clientId) { public NoteData retrieveClientNote(Long clientId, Long noteId) {
context.authenticatedUser(); try {
context.authenticatedUser();
// Check if client exists
retrieveIndividualClient(clientId);
// FIXME - use join on sql query to fetch user information for note // Check if client exists
// rather than fetching users? retrieveIndividualClient(clientId);
Collection<AppUserData> allUsers = this.appUserReadPlatformService
.retrieveAllUsers();
NoteMapper noteMapper = new NoteMapper(allUsers); // FIXME - use join on sql query to fetch user information for note
// rather than fetching users?
Collection<AppUserData> allUsers = this.appUserReadPlatformService.retrieveAllUsers();
String sql = "select " NoteMapper noteMapper = new NoteMapper(allUsers);
+ noteMapper.schema()
+ " where n.client_id = ? order by n.created_date DESC";
return this.jdbcTemplate.query(sql, noteMapper, new Object[] {clientId}); String sql = "select " + noteMapper.schema() + " where n.client_id = ? and n.id = ?";
}
private static final class NoteMapper implements RowMapper<NoteData> { return this.jdbcTemplate.queryForObject(sql, noteMapper, new Object[] { clientId, noteId });
} catch (EmptyResultDataAccessException e) {
throw new NoteNotFoundException(clientId);
}
}
private final Collection<AppUserData> allUsers; @Override
public Collection<NoteData> retrieveAllClientNotes(Long clientId) {
public NoteMapper(Collection<AppUserData> allUsers) { context.authenticatedUser();
this.allUsers = allUsers;
}
public String schema() { // Check if client exists
return "n.id as id, n.client_id as clientId, n.loan_id as loanId, n.loan_transaction_id as transactionId, n.note_type_enum as noteTypeEnum, n.note as note, " retrieveIndividualClient(clientId);
+ "n.created_date as createdDate, n.createdby_id as createdById, n.lastmodified_date as lastModifiedDate, n.lastmodifiedby_id as lastModifiedById"
+ " from m_note n";
}
@Override // FIXME - use join on sql query to fetch user information for note
public NoteData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) // rather than fetching users?
throws SQLException { Collection<AppUserData> allUsers = this.appUserReadPlatformService.retrieveAllUsers();
Long id = JdbcSupport.getLong(rs, "id"); NoteMapper noteMapper = new NoteMapper(allUsers);
Long clientId = JdbcSupport.getLong(rs, "clientId");
Long loanId = JdbcSupport.getLong(rs, "loanId");
Long transactionId = JdbcSupport.getLong(rs, "transactionId");
Integer noteTypeId = JdbcSupport.getInteger(rs, "noteTypeEnum");
EnumOptionData noteType = NoteEnumerations.noteType(noteTypeId);
String note = rs.getString("note");
DateTime createdDate = JdbcSupport.getDateTime(rs, "createdDate"); String sql = "select " + noteMapper.schema() + " where n.client_id = ? order by n.created_date DESC";
Long createdById = JdbcSupport.getLong(rs, "createdById");
String createdByUsername = findUserById(createdById, allUsers);
DateTime lastModifiedDate = JdbcSupport.getDateTime(rs, return this.jdbcTemplate.query(sql, noteMapper, new Object[] { clientId });
"lastModifiedDate"); }
Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById");
String updatedByUsername = findUserById(createdById, allUsers);
return new NoteData(id, clientId, loanId, transactionId, noteType, private static final class NoteMapper implements RowMapper<NoteData> {
note, createdDate, createdById, createdByUsername,
lastModifiedDate, lastModifiedById, updatedByUsername);
}
private String findUserById(Long createdById, Collection<AppUserData> allUsers) { private final Collection<AppUserData> allUsers;
String username = "";
for (AppUserData appUserData : allUsers) {
if (appUserData.getId().equals(createdById)) {
username = appUserData.getUsername();
break;
}
}
return username;
}
}
@Override public NoteMapper(Collection<AppUserData> allUsers) {
public Collection<ClientIdentifierData> retrieveClientIdentifiers(final Long clientId) { this.allUsers = allUsers;
}
AppUser currentUser = context.authenticatedUser(); public String schema() {
String hierarchy = currentUser.getOffice().getHierarchy(); return "n.id as id, n.client_id as clientId, n.loan_id as loanId, n.loan_transaction_id as transactionId, n.note_type_enum as noteTypeEnum, n.note as note, "
String hierarchySearchString = hierarchy + "%"; + "n.created_date as createdDate, n.createdby_id as createdById, n.lastmodified_date as lastModifiedDate, n.lastmodifiedby_id as lastModifiedById"
+ " from m_note n";
}
ClientIdentityMapper rm = new ClientIdentityMapper(); @Override
public NoteData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
String sql = "select " + rm.schema(); Long id = JdbcSupport.getLong(rs, "id");
Long clientId = JdbcSupport.getLong(rs, "clientId");
Long loanId = JdbcSupport.getLong(rs, "loanId");
Long transactionId = JdbcSupport.getLong(rs, "transactionId");
Integer noteTypeId = JdbcSupport.getInteger(rs, "noteTypeEnum");
EnumOptionData noteType = NoteEnumerations.noteType(noteTypeId);
String note = rs.getString("note");
sql += " order by ci.id"; DateTime createdDate = JdbcSupport.getDateTime(rs, "createdDate");
Long createdById = JdbcSupport.getLong(rs, "createdById");
String createdByUsername = findUserById(createdById, allUsers);
return this.jdbcTemplate.query(sql, rm, new Object[] { clientId, hierarchySearchString }); DateTime lastModifiedDate = JdbcSupport.getDateTime(rs, "lastModifiedDate");
} Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById");
String updatedByUsername = findUserById(createdById, allUsers);
@Override
public ClientIdentifierData retrieveClientIdentifier(
final Long clientId,
final Long clientIdentifierId) {
try {
AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%";
ClientIdentityMapper rm = new ClientIdentityMapper(); return new NoteData(id, clientId, loanId, transactionId, noteType, note, createdDate, createdById, createdByUsername,
lastModifiedDate, lastModifiedById, updatedByUsername);
}
String sql = "select " + rm.schema(); private String findUserById(final Long createdById, final Collection<AppUserData> allUsers) {
String username = "";
for (AppUserData appUserData : allUsers) {
if (appUserData.hasIdentifyOf(createdById)) {
username = appUserData.username();
break;
}
}
return username;
}
}
sql += " and ci.id = ?"; @Override
public Collection<ClientIdentifierData> retrieveClientIdentifiers(final Long clientId) {
final ClientIdentifierData clientIdentifierData = this.jdbcTemplate AppUser currentUser = context.authenticatedUser();
.queryForObject(sql, rm, new Object[] { clientId, String hierarchy = currentUser.getOffice().getHierarchy();
hierarchySearchString, clientIdentifierId }); String hierarchySearchString = hierarchy + "%";
return clientIdentifierData; ClientIdentityMapper rm = new ClientIdentityMapper();
} catch (EmptyResultDataAccessException e) {
throw new ClientIdentifierNotFoundException(clientIdentifierId);
}
} String sql = "select " + rm.schema();
private static final class ClientIdentityMapper implements RowMapper<ClientIdentifierData> {
public ClientIdentityMapper() { sql += " order by ci.id";
}
public String schema() { return this.jdbcTemplate.query(sql, rm, new Object[] { clientId, hierarchySearchString });
return "ci.id as id, ci.client_id as clientId, ci.document_type_id as documentTypeId, ci.document_key as documentKey," }
+ " ci.description as description, cv.code_value as documentType "
+ " from m_client_identifier ci, m_client c, m_office o, m_code_value cv"
+ " where ci.client_id=c.id and c.office_id=o.id"
+ " and ci.document_type_id=cv.id"
+ " and ci.client_id = ? and o.hierarchy like ? ";
}
@Override @Override
public ClientIdentifierData mapRow(final ResultSet rs, public ClientIdentifierData retrieveClientIdentifier(final Long clientId, final Long clientIdentifierId) {
@SuppressWarnings("unused") final int rowNum) try {
throws SQLException { AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%";
final Long id = JdbcSupport.getLong(rs, "id"); ClientIdentityMapper rm = new ClientIdentityMapper();
final Long clientId = JdbcSupport.getLong(rs, "clientId");
final Long documentTypeId = JdbcSupport.getLong(rs, "documentTypeId");
final String documentKey = rs.getString("documentKey");
final String description = rs.getString("description");
final String documentTypeName = rs.getString("documentType");
return ClientIdentifierData.singleItem(id, clientId, documentTypeId,documentKey, description,documentTypeName); String sql = "select " + rm.schema();
}
} sql += " and ci.id = ?";
@Override final ClientIdentifierData clientIdentifierData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { clientId,
public ClientData retrieveClientByIdentifier( hierarchySearchString, clientIdentifierId });
final Long identifierTypeId,
final String identifierKey) {
try {
final ClientIdentifierMapper mapper = new ClientIdentifierMapper();
final String sql = "select " + mapper.clientLookupByIdentifierSchema(); return clientIdentifierData;
} catch (EmptyResultDataAccessException e) {
throw new ClientIdentifierNotFoundException(clientIdentifierId);
}
return jdbcTemplate.queryForObject(sql, mapper, new Object[] { identifierTypeId, identifierKey }); }
} catch (EmptyResultDataAccessException e) {
return null;
}
}
private static final class ClientIdentifierMapper implements RowMapper<ClientData> {
public String clientLookupByIdentifierSchema() { private static final class ClientIdentityMapper implements RowMapper<ClientIdentifierData> {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, "
+ "c.office_id as officeId, o.name as officeName "
+ "from m_client c, m_office o, m_client_identifier ci "
+ "where o.id = c.office_id and c.id=ci.client_id "
+ "and ci.document_type_id= ? and ci.document_key like ?";
}
@Override public ClientIdentityMapper() {}
public ClientData mapRow(final ResultSet rs,
@SuppressWarnings("unused") final int rowNum) public String schema() {
throws SQLException { return "ci.id as id, ci.client_id as clientId, ci.document_type_id as documentTypeId, ci.document_key as documentKey,"
+ " ci.description as description, cv.code_value as documentType "
final Long id = rs.getLong("id"); + " from m_client_identifier ci, m_client c, m_office o, m_code_value cv"
String firstname = rs.getString("firstname"); + " where ci.client_id=c.id and c.office_id=o.id" + " and ci.document_type_id=cv.id"
if (StringUtils.isBlank(firstname)) { + " and ci.client_id = ? and o.hierarchy like ? ";
firstname = ""; }
}
final String lastname = rs.getString("lastname"); @Override
public ClientIdentifierData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long officeId = rs.getLong("officeId");
final String officeName = rs.getString("officeName"); final Long id = JdbcSupport.getLong(rs, "id");
final Long clientId = JdbcSupport.getLong(rs, "clientId");
return ClientData.clientIdentifier(id, firstname, lastname, officeId, officeName); final Long documentTypeId = JdbcSupport.getLong(rs, "documentTypeId");
} final String documentKey = rs.getString("documentKey");
} final String description = rs.getString("description");
final String documentTypeName = rs.getString("documentType");
return ClientIdentifierData.singleItem(id, clientId, documentTypeId, documentKey, description, documentTypeName);
}
}
@Override
public ClientData retrieveClientByIdentifier(final Long identifierTypeId, final String identifierKey) {
try {
final ClientIdentifierMapper mapper = new ClientIdentifierMapper();
final String sql = "select " + mapper.clientLookupByIdentifierSchema();
return jdbcTemplate.queryForObject(sql, mapper, new Object[] { identifierTypeId, identifierKey });
} catch (EmptyResultDataAccessException e) {
return null;
}
}
private static final class ClientIdentifierMapper implements RowMapper<ClientData> {
public String clientLookupByIdentifierSchema() {
return "c.id as id, c.firstname as firstname, c.lastname as lastname, " + "c.office_id as officeId, o.name as officeName "
+ "from m_client c, m_office o, m_client_identifier ci " + "where o.id = c.office_id and c.id=ci.client_id "
+ "and ci.document_type_id= ? and ci.document_key like ?";
}
@Override
public ClientData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = rs.getLong("id");
String firstname = rs.getString("firstname");
if (StringUtils.isBlank(firstname)) {
firstname = "";
}
final String lastname = rs.getString("lastname");
final Long officeId = rs.getLong("officeId");
final String officeName = rs.getString("officeName");
return ClientData.clientIdentifier(id, firstname, lastname, officeId, officeName);
}
}
} }
@@ -2,6 +2,6 @@ package org.mifosng.platform.makerchecker.service;
public interface ChangeDetectionService { public interface ChangeDetectionService {
String detectChanges(String operation, String resourceName, Long resourceId, String commandSerializedAsJson); String detectChangesOnUpdate(String resourceName, Long resourceId, String commandSerializedAsJson);
} }
@@ -24,23 +24,26 @@ public class ChangeDetectionServiceJdbc implements ChangeDetectionService {
} }
@Override @Override
public String detectChanges(final String operation, final String resourceName, final Long resourceId, public String detectChangesOnUpdate(final String resourceName, final Long resourceId, final String commandSerializedAsJson) {
final String commandSerializedAsJson) {
String changesOnlyJson = ""; String changesOnlyJson = "";
// FIXME - KW/JW - this change detection code for update of clients if ("clients".equalsIgnoreCase(resourceName)) {
// using ClientCommand can re placed when more suitable sql version is // FIXME - KW/JW - this change detection code for update of clients
// implemented. // using ClientCommand can re placed when more suitable sql version is
final ClientData originalClient = this.clientReadPlatformService.retrieveIndividualClient(resourceId); // implemented.
final ClientData changedClient = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(resourceId, final ClientData originalClient = this.clientReadPlatformService.retrieveIndividualClient(resourceId);
commandSerializedAsJson); final ClientData changedClient = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(resourceId,
commandSerializedAsJson);
final String baseJson = this.apiJsonSerializerService.serializeClientDataToJson(originalClient);
final String workingJson = this.apiJsonSerializerService.serializeClientDataToJson(changedClient); final String baseJson = this.apiJsonSerializerService.serializeClientDataToJson(originalClient);
final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson); final String workingJson = this.apiJsonSerializerService.serializeClientDataToJson(changedClient);
final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson);
changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly);
changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly);
} else {
changesOnlyJson = commandSerializedAsJson;
}
return changesOnlyJson; return changesOnlyJson;
} }
@@ -57,8 +57,7 @@ public class ClientCommandHandler implements CommandSourceHandler {
} }
} else if (commandSource.isUpdate()) { } else if (commandSource.isUpdate()) {
try { try {
final String jsonOfChangesOnly = this.changeDetectionService.detectChanges(commandSource.operation(), final String jsonOfChangesOnly = this.changeDetectionService.detectChangesOnUpdate(commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson);
commandSourceResult.updateJsonTo(jsonOfChangesOnly); commandSourceResult.updateJsonTo(jsonOfChangesOnly);
final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand( final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand(
@@ -9,17 +9,17 @@ import org.mifosng.platform.api.data.OfficeTransactionData;
public interface OfficeReadPlatformService { public interface OfficeReadPlatformService {
Collection<OfficeData> retrieveAllOffices(); Collection<OfficeData> retrieveAllOffices();
Collection<OfficeLookup> retrieveAllOfficesForLookup(); Collection<OfficeLookup> retrieveAllOfficesForLookup();
OfficeData retrieveOffice(Long officeId); OfficeData retrieveOffice(Long officeId);
OfficeData retrieveNewOfficeTemplate(); OfficeData retrieveNewOfficeTemplate();
List<OfficeLookup> retrieveAllowedParents(Long officeId); List<OfficeLookup> retrieveAllowedParents(Long officeId);
Collection<OfficeTransactionData> retrieveAllOfficeTransactions(); Collection<OfficeTransactionData> retrieveAllOfficeTransactions();
OfficeTransactionData retrieveNewOfficeTransactionDetails(); OfficeTransactionData retrieveNewOfficeTransactionDetails();
} }
@@ -27,231 +27,204 @@ import org.springframework.stereotype.Service;
@Service @Service
public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService { public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final CurrencyReadPlatformService currencyReadPlatformService; private final CurrencyReadPlatformService currencyReadPlatformService;
private final static String nameDecoratedBaseOnHierarchy = "concat(substring('........................................', 1, ((LENGTH(o.hierarchy) - LENGTH(REPLACE(o.hierarchy, '.', '')) - 1) * 4)), o.name)"; private final static String nameDecoratedBaseOnHierarchy = "concat(substring('........................................', 1, ((LENGTH(o.hierarchy) - LENGTH(REPLACE(o.hierarchy, '.', '')) - 1) * 4)), o.name)";
@Autowired @Autowired
public OfficeReadPlatformServiceImpl(final PlatformSecurityContext context, public OfficeReadPlatformServiceImpl(final PlatformSecurityContext context,
final CurrencyReadPlatformService currencyReadPlatformService, final CurrencyReadPlatformService currencyReadPlatformService, final TenantAwareRoutingDataSource dataSource) {
final TenantAwareRoutingDataSource dataSource) { this.context = context;
this.context = context; this.currencyReadPlatformService = currencyReadPlatformService;
this.currencyReadPlatformService = currencyReadPlatformService; this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate = new JdbcTemplate(dataSource); }
}
private static final class OfficeMapper implements RowMapper<OfficeData> { private static final class OfficeMapper implements RowMapper<OfficeData> {
public String officeSchema() { public String officeSchema() {
return " o.id as id, o.name as name, " return " o.id as id, o.name as name, "
+ nameDecoratedBaseOnHierarchy + nameDecoratedBaseOnHierarchy
+ " as nameDecorated, o.external_id as externalId, o.opening_date as openingDate, o.hierarchy as hierarchy, parent.id as parentId, parent.name as parentName " + " as nameDecorated, o.external_id as externalId, o.opening_date as openingDate, o.hierarchy as hierarchy, parent.id as parentId, parent.name as parentName "
+ "from m_office o LEFT JOIN m_office AS parent ON parent.id = o.parent_id "; + "from m_office o LEFT JOIN m_office AS parent ON parent.id = o.parent_id ";
} }
@Override @Override
public OfficeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public OfficeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
String name = rs.getString("name"); String name = rs.getString("name");
String nameDecorated = rs.getString("nameDecorated"); String nameDecorated = rs.getString("nameDecorated");
String externalId = rs.getString("externalId"); String externalId = rs.getString("externalId");
LocalDate openingDate = JdbcSupport.getLocalDate(rs, "openingDate"); LocalDate openingDate = JdbcSupport.getLocalDate(rs, "openingDate");
String hierarchy = rs.getString("hierarchy"); String hierarchy = rs.getString("hierarchy");
Long parentId = JdbcSupport.getLong(rs, "parentId"); Long parentId = JdbcSupport.getLong(rs, "parentId");
String parentName = rs.getString("parentName"); String parentName = rs.getString("parentName");
List<OfficeLookup> allowedParents = new ArrayList<OfficeLookup>(); List<OfficeLookup> allowedParents = new ArrayList<OfficeLookup>();
return new OfficeData(id, name, nameDecorated, externalId, return new OfficeData(id, name, nameDecorated, externalId, openingDate, hierarchy, parentId, parentName, allowedParents);
openingDate, hierarchy, parentId, parentName, }
allowedParents); }
}
}
private static final class OfficeLookupMapper implements private static final class OfficeLookupMapper implements RowMapper<OfficeLookup> {
RowMapper<OfficeLookup> {
public String officeLookupSchema() { public String officeLookupSchema() {
return " o.id as id, " + nameDecoratedBaseOnHierarchy return " o.id as id, " + nameDecoratedBaseOnHierarchy + " as nameDecorated, o.name as name from m_office o ";
+ " as nameDecorated, o.name as name from m_office o "; }
}
@Override @Override
public OfficeLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public OfficeLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
String name = rs.getString("name"); String name = rs.getString("name");
String nameDecorated = rs.getString("nameDecorated"); String nameDecorated = rs.getString("nameDecorated");
return new OfficeLookup(id, name, nameDecorated); return new OfficeLookup(id, name, nameDecorated);
} }
} }
private static final class OfficeTransactionMapper implements private static final class OfficeTransactionMapper implements RowMapper<OfficeTransactionData> {
RowMapper<OfficeTransactionData> {
public String officeTransactionSchema() { public String officeTransactionSchema() {
return " ot.id as id, ot.transaction_date as transactionDate, ot.from_office_id as fromOfficeId, fromoff.name as fromOfficeName, " return " ot.id as id, ot.transaction_date as transactionDate, ot.from_office_id as fromOfficeId, fromoff.name as fromOfficeName, "
+ " ot.to_office_id as toOfficeId, tooff.name as toOfficeName, ot.transaction_amount as transactionAmount, ot.description as description, " + " ot.to_office_id as toOfficeId, tooff.name as toOfficeName, ot.transaction_amount as transactionAmount, ot.description as description, "
+ " ot.currency_code as currencyCode, rc.decimal_places as currencyDigits, " + " ot.currency_code as currencyCode, rc.decimal_places as currencyDigits, "
+ "rc.name as currencyName, rc.internationalized_name_code as currencyNameCode, rc.display_symbol as currencyDisplaySymbol " + "rc.name as currencyName, rc.internationalized_name_code as currencyNameCode, rc.display_symbol as currencyDisplaySymbol "
+ " from m_office_transaction ot " + " from m_office_transaction ot "
+ " left join m_office fromoff on fromoff.id = ot.from_office_id " + " left join m_office fromoff on fromoff.id = ot.from_office_id "
+ " left join m_office tooff on tooff.id = ot.to_office_id " + " left join m_office tooff on tooff.id = ot.to_office_id " + " join m_currency rc on rc.`code` = ot.currency_code";
+ " join m_currency rc on rc.`code` = ot.currency_code"; }
}
@Override @Override
public OfficeTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) public OfficeTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
throws SQLException {
Long id = rs.getLong("id"); Long id = rs.getLong("id");
LocalDate transactionDate = JdbcSupport.getLocalDate(rs, LocalDate transactionDate = JdbcSupport.getLocalDate(rs, "transactionDate");
"transactionDate"); Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId");
Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId"); String fromOfficeName = rs.getString("fromOfficeName");
String fromOfficeName = rs.getString("fromOfficeName"); Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId");
Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId"); String toOfficeName = rs.getString("toOfficeName");
String toOfficeName = rs.getString("toOfficeName");
String currencyCode = rs.getString("currencyCode"); String currencyCode = rs.getString("currencyCode");
String currencyName = rs.getString("currencyName"); String currencyName = rs.getString("currencyName");
String currencyNameCode = rs.getString("currencyNameCode"); String currencyNameCode = rs.getString("currencyNameCode");
String currencyDisplaySymbol = rs String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
.getString("currencyDisplaySymbol"); Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
Integer currencyDigits = JdbcSupport.getInteger(rs,
"currencyDigits");
CurrencyData currencyData = new CurrencyData(currencyCode, CurrencyData currencyData = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyName, currencyDigits, currencyDisplaySymbol, currencyNameCode);
currencyNameCode);
BigDecimal transactionAmount = rs BigDecimal transactionAmount = rs.getBigDecimal("transactionAmount");
.getBigDecimal("transactionAmount"); String description = rs.getString("description");
String description = rs.getString("description");
return new OfficeTransactionData(id, transactionDate, fromOfficeId, return new OfficeTransactionData(id, transactionDate, fromOfficeId, fromOfficeName, toOfficeId, toOfficeName, currencyData,
fromOfficeName, toOfficeId, toOfficeName, currencyData, transactionAmount, description);
transactionAmount, description); }
} }
}
@Override @Override
public Collection<OfficeData> retrieveAllOffices() { public Collection<OfficeData> retrieveAllOffices() {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy(); String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
OfficeMapper rm = new OfficeMapper(); OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema() String sql = "select " + rm.officeSchema() + "where o.hierarchy like ? order by o.hierarchy";
+ "where o.hierarchy like ? order by o.hierarchy";
return this.jdbcTemplate.query(sql, rm, return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
new Object[] { hierarchySearchString }); }
}
@Override @Override
public Collection<OfficeLookup> retrieveAllOfficesForLookup() { public Collection<OfficeLookup> retrieveAllOfficesForLookup() {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy(); String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
OfficeLookupMapper rm = new OfficeLookupMapper(); OfficeLookupMapper rm = new OfficeLookupMapper();
String sql = "select " + rm.officeLookupSchema() String sql = "select " + rm.officeLookupSchema() + "where o.hierarchy like ? order by o.hierarchy";
+ "where o.hierarchy like ? order by o.hierarchy";
return this.jdbcTemplate.query(sql, rm, return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString });
new Object[] { hierarchySearchString }); }
}
@Override @Override
public OfficeData retrieveOffice(final Long officeId) { public OfficeData retrieveOffice(final Long officeId) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
OfficeMapper rm = new OfficeMapper(); OfficeMapper rm = new OfficeMapper();
String sql = "select " + rm.officeSchema() + " where o.id = ?"; String sql = "select " + rm.officeSchema() + " where o.id = ?";
OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql, OfficeData selectedOffice = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { officeId });
rm, new Object[] { officeId });
return selectedOffice; return selectedOffice;
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
throw new OfficeNotFoundException(officeId); throw new OfficeNotFoundException(officeId);
} }
} }
@Override @Override
public OfficeData retrieveNewOfficeTemplate() { public OfficeData retrieveNewOfficeTemplate() {
context.authenticatedUser(); context.authenticatedUser();
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(); List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>();
return OfficeData.template(parentLookups, new LocalDate()); return OfficeData.template(parentLookups, new LocalDate());
} }
@Override @Override
public List<OfficeLookup> retrieveAllowedParents(final Long officeId) { public List<OfficeLookup> retrieveAllowedParents(final Long officeId) {
context.authenticatedUser(); context.authenticatedUser();
List<OfficeLookup> filterParentLookups = new ArrayList<OfficeLookup>(); List<OfficeLookup> filterParentLookups = new ArrayList<OfficeLookup>();
if (isNotHeadOffice(officeId)) { if (isNotHeadOffice(officeId)) {
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>( List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(retrieveAllOfficesForLookup());
retrieveAllOfficesForLookup());
for (OfficeLookup office : parentLookups) { for (OfficeLookup office : parentLookups) {
if (!office.getId().equals(officeId)) { if (!office.hasIdentifyOf(officeId)) {
filterParentLookups.add(office); filterParentLookups.add(office);
} }
} }
} }
return filterParentLookups; return filterParentLookups;
} }
private boolean isNotHeadOffice(final Long officeId) { private boolean isNotHeadOffice(final Long officeId) {
return !Long.valueOf(1).equals(officeId); return !Long.valueOf(1).equals(officeId);
} }
@Override @Override
public Collection<OfficeTransactionData> retrieveAllOfficeTransactions() { public Collection<OfficeTransactionData> retrieveAllOfficeTransactions() {
AppUser currentUser = context.authenticatedUser(); AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy(); String hierarchy = currentUser.getOffice().getHierarchy();
String hierarchySearchString = hierarchy + "%"; String hierarchySearchString = hierarchy + "%";
OfficeTransactionMapper rm = new OfficeTransactionMapper(); OfficeTransactionMapper rm = new OfficeTransactionMapper();
String sql = "select " String sql = "select " + rm.officeTransactionSchema()
+ rm.officeTransactionSchema() + " where (fromoff.hierarchy like ? or tooff.hierarchy like ?) order by ot.transaction_date, ot.id";
+ " where (fromoff.hierarchy like ? or tooff.hierarchy like ?) order by ot.transaction_date, ot.id";
return this.jdbcTemplate.query(sql, rm, new Object[] { return this.jdbcTemplate.query(sql, rm, new Object[] { hierarchySearchString, hierarchySearchString });
hierarchySearchString, hierarchySearchString }); }
}
@Override @Override
public OfficeTransactionData retrieveNewOfficeTransactionDetails() { public OfficeTransactionData retrieveNewOfficeTransactionDetails() {
context.authenticatedUser(); context.authenticatedUser();
List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>( List<OfficeLookup> parentLookups = new ArrayList<OfficeLookup>(retrieveAllOfficesForLookup());
retrieveAllOfficesForLookup()); List<CurrencyData> currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies();
List<CurrencyData> currencyOptions = currencyReadPlatformService
.retrieveAllowedCurrencies();
return new OfficeTransactionData(new LocalDate(), parentLookups, return new OfficeTransactionData(new LocalDate(), parentLookups, currencyOptions);
currencyOptions); }
}
} }
@@ -4,6 +4,5 @@ import org.mifosng.platform.user.domain.AppUser;
public interface PlatformSecurityContext { public interface PlatformSecurityContext {
AppUser authenticatedUser(); AppUser authenticatedUser();
}
}
@@ -8,26 +8,25 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* Wrapper around spring security's {@link SecurityContext} for extracted the current authenticated {@link AppUser}. * Wrapper around spring security's {@link SecurityContext} for extracted the
* current authenticated {@link AppUser}.
*/ */
@Service @Service
public class SpringSecurityPlatformSecurityContext implements PlatformSecurityContext { public class SpringSecurityPlatformSecurityContext implements PlatformSecurityContext {
@Override @Override
public AppUser authenticatedUser() { public AppUser authenticatedUser() {
AppUser currentUser = null; AppUser currentUser = null;
SecurityContext context = SecurityContextHolder.getContext(); SecurityContext context = SecurityContextHolder.getContext();
if (context != null) { if (context != null) {
Authentication auth = context.getAuthentication(); Authentication auth = context.getAuthentication();
if (auth != null) { if (auth != null) {
currentUser = (AppUser) auth.getPrincipal(); currentUser = (AppUser) auth.getPrincipal();
} }
} }
if (currentUser == null) { if (currentUser == null) { throw new UnAuthenticatedUserException(); }
throw new UnAuthenticatedUserException();
}
return currentUser; return currentUser;
} }
} }
@@ -27,377 +27,351 @@ import org.springframework.security.core.userdetails.User;
@Entity @Entity
@Table(name = "m_appuser", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }, name = "username_org")) @Table(name = "m_appuser", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }, name = "username_org"))
public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements public class AppUser extends AbstractAuditableCustom<AppUser, Long> implements PlatformUser {
PlatformUser {
@Column(name = "email", nullable = false, length = 100)
@Column(name = "email", nullable = false, length = 100) private String email;
private String email;
@Column(name = "username", nullable = false, length = 100)
@Column(name = "username", nullable = false, length = 100) private String username;
private String username;
@Column(name = "firstname", nullable = false, length = 100)
@Column(name = "firstname", nullable = false, length = 100) private String firstname;
private String firstname;
@Column(name = "lastname", nullable = false, length = 100)
@Column(name = "lastname", nullable = false, length = 100) private String lastname;
private String lastname;
@Column(name = "password", nullable = false)
@Column(name = "password", nullable = false) private String password;
private String password;
@Column(name = "nonexpired", nullable = false)
@Column(name = "nonexpired", nullable = false) private boolean accountNonExpired;
private boolean accountNonExpired;
@Column(name = "nonlocked", nullable = false)
@Column(name = "nonlocked", nullable = false) private final boolean accountNonLocked;
private final boolean accountNonLocked;
@Column(name = "nonexpired_credentials", nullable = false)
@Column(name = "nonexpired_credentials", nullable = false) private final boolean credentialsNonExpired;
private final boolean credentialsNonExpired;
@Column(name = "enabled", nullable = false)
@Column(name = "enabled", nullable = false) private boolean enabled;
private boolean enabled;
@SuppressWarnings("unused")
@SuppressWarnings("unused") @Column(name = "firsttime_login_remaining", nullable = false)
@Column(name = "firsttime_login_remaining", nullable = false) private boolean firstTimeLoginRemaining;
private boolean firstTimeLoginRemaining;
@Column(name = "is_deleted", nullable = false)
@Column(name = "is_deleted", nullable = false) private boolean deleted;
private boolean deleted;
@ManyToOne
@ManyToOne @JoinColumn(name = "office_id")
@JoinColumn(name = "office_id") private Office office;
private Office office;
@ManyToMany(fetch = FetchType.EAGER)
@ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "m_appuser_role", joinColumns = @JoinColumn(name = "appuser_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
@JoinTable(name = "m_appuser_role", joinColumns = @JoinColumn(name = "appuser_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles;
private Set<Role> roles;
public static AppUser createNew(final Office office, final Set<Role> allRoles, final String username, final String email,
public static AppUser createNew(final Office office, final String firstname, final String lastname, final String password) {
final Set<Role> allRoles, final String username,
final String email, final String firstname, final String lastname, boolean userEnabled = true;
final String password) { boolean userAccountNonExpired = true;
boolean userCredentialsNonExpired = true;
boolean userEnabled = true; boolean userAccountNonLocked = true;
boolean userAccountNonExpired = true;
boolean userCredentialsNonExpired = true; Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
boolean userAccountNonLocked = true; authorities.add(new SimpleGrantedAuthority("DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION"));
Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); User user = new User(username, password, userEnabled, userAccountNonExpired, userCredentialsNonExpired, userAccountNonLocked,
authorities.add(new SimpleGrantedAuthority( authorities);
"DUMMY_ROLE_NOT_USED_OR_PERSISTED_TO_AVOID_EXCEPTION")); return new AppUser(office, user, allRoles, email, firstname, lastname);
}
User user = new User(username, password, userEnabled,
userAccountNonExpired, userCredentialsNonExpired, protected AppUser() {
userAccountNonLocked, authorities); this.office = null;
return new AppUser(office, user, allRoles, email, firstname, lastname); this.email = null;
} this.username = null;
this.password = null;
protected AppUser() { this.accountNonExpired = false;
this.office = null; this.accountNonLocked = false;
this.email = null; this.credentialsNonExpired = false;
this.username = null; this.enabled = false;
this.password = null; this.roles = new HashSet<Role>();
this.accountNonExpired = false; this.firstTimeLoginRemaining = true;
this.accountNonLocked = false; }
this.credentialsNonExpired = false;
this.enabled = false; public AppUser(final Office office, final User user, final Set<Role> roles, final String email, final String firstname,
this.roles = new HashSet<Role>(); final String lastname) {
this.firstTimeLoginRemaining = true; this.office = office;
} this.email = email.trim();
this.username = user.getUsername().trim();
public AppUser(final Office office, final User user, final Set<Role> roles, this.firstname = firstname.trim();
final String email, final String firstname, final String lastname) { this.lastname = lastname.trim();
this.office = office; this.password = user.getPassword().trim();
this.email = email.trim(); this.accountNonExpired = user.isAccountNonExpired();
this.username = user.getUsername().trim(); this.accountNonLocked = user.isAccountNonLocked();
this.firstname = firstname.trim(); this.credentialsNonExpired = user.isCredentialsNonExpired();
this.lastname = lastname.trim(); this.enabled = user.isEnabled();
this.password = user.getPassword().trim(); this.roles = roles;
this.accountNonExpired = user.isAccountNonExpired(); this.firstTimeLoginRemaining = true;
this.accountNonLocked = user.isAccountNonLocked(); }
this.credentialsNonExpired = user.isCredentialsNonExpired();
this.enabled = user.isEnabled(); public void updatePassword(final String encodePassword) {
this.roles = roles; this.password = encodePassword;
this.firstTimeLoginRemaining = true; this.firstTimeLoginRemaining = false;
} }
public void updatePassword(final String encodePassword) { public void update(final Set<Role> allRoles, final Office office, final UserCommand userCommand) {
this.password = encodePassword;
this.firstTimeLoginRemaining = false; if (userCommand.isRolesChanged() && !allRoles.isEmpty()) {
} this.roles.clear();
this.roles = allRoles;
public void update(final Set<Role> allRoles, final Office office, }
final UserCommand userCommand) { if (userCommand.isOfficeChanged()) {
this.office = office;
if (userCommand.isRolesChanged() && !allRoles.isEmpty()) { }
this.roles.clear(); if (userCommand.isUsernameChanged()) {
this.roles = allRoles; this.username = userCommand.getUsername();
} }
if (userCommand.isOfficeChanged()) { if (userCommand.isFirstnameChanged()) {
this.office = office; this.firstname = userCommand.getFirstname();
} }
if (userCommand.isUsernameChanged()) { if (userCommand.isLastnameChanged()) {
this.username = userCommand.getUsername(); this.lastname = userCommand.getLastname();
} }
if (userCommand.isFirstnameChanged()) { if (userCommand.isEmailChanged()) {
this.firstname = userCommand.getFirstname(); this.email = userCommand.getEmail();
} }
if (userCommand.isLastnameChanged()) { }
this.lastname = userCommand.getLastname();
} /**
if (userCommand.isEmailChanged()) { * Delete is a <i>soft delete</i>. Updates flag so it wont appear in
this.email = userCommand.getEmail(); * query/report results.
} *
} * Any fields with unique constraints and prepended with id of record.
*/
/** public void delete() {
* Delete is a <i>soft delete</i>. Updates flag so it wont appear in this.deleted = true;
* query/report results. this.enabled = false;
* this.accountNonExpired = false;
* Any fields with unique constraints and prepended with id of record. this.firstTimeLoginRemaining = true;
*/ this.username = this.getId() + "_DELETED_" + this.username;
public void delete() { }
this.deleted = true;
this.enabled = false; public boolean isDeleted() {
this.accountNonExpired = false; return deleted;
this.firstTimeLoginRemaining = true; }
this.username = this.getId() + "_DELETED_" + this.username;
} @Override
public Collection<GrantedAuthority> getAuthorities() {
public boolean isDeleted() { return this.populateGrantedAuthorities();
return deleted; }
}
private List<GrantedAuthority> populateGrantedAuthorities() {
@Override List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
public Collection<GrantedAuthority> getAuthorities() { for (Role role : this.roles) {
return this.populateGrantedAuthorities(); Collection<Permission> permissions = role.getPermissions();
} for (Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission.code()));
private List<GrantedAuthority> populateGrantedAuthorities() { }
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); }
for (Role role : this.roles) { return grantedAuthorities;
Collection<Permission> permissions = role.getPermissions(); }
for (Permission permission : permissions) {
grantedAuthorities.add(new SimpleGrantedAuthority(permission @Override
.code())); public String getPassword() {
} return this.password;
} }
return grantedAuthorities;
} @Override
public String getUsername() {
@Override return this.username;
public String getPassword() { }
return this.password;
} @Override
public boolean isAccountNonExpired() {
@Override return this.accountNonExpired;
public String getUsername() { }
return this.username;
} @Override
public boolean isAccountNonLocked() {
@Override return this.accountNonLocked;
public boolean isAccountNonExpired() { }
return this.accountNonExpired;
} @Override
public boolean isCredentialsNonExpired() {
@Override return this.credentialsNonExpired;
public boolean isAccountNonLocked() { }
return this.accountNonLocked;
} @Override
public boolean isEnabled() {
@Override return this.enabled;
public boolean isCredentialsNonExpired() { }
return this.credentialsNonExpired;
} public String getFirstname() {
return firstname;
@Override }
public boolean isEnabled() {
return this.enabled; public String getLastname() {
} return lastname;
}
public String getFirstname() {
return firstname; public String getEmail() {
} return this.email;
}
public String getLastname() {
return lastname; public Set<Role> getRoles() {
} return this.roles;
}
public String getEmail() {
return this.email; public Office getOffice() {
} return this.office;
}
public Set<Role> getRoles() {
return this.roles; public boolean canNotApproveLoanInPast() {
} return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public Office getOffice() {
return this.office; public boolean canNotRejectLoanInPast() {
} return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
}
public boolean canNotApproveLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "APPROVEINPAST_LOAN", public boolean canNotWithdrawByClientLoanInPast() {
"PORTFOLIO_MANAGEMENT_SUPER_USER"); return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
} }
public boolean canNotRejectLoanInPast() { public boolean canNotDisburseLoanInPast() {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REJECTINPAST_LOAN", return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
"PORTFOLIO_MANAGEMENT_SUPER_USER"); }
}
public boolean canNotMakeRepaymentOnLoanInPast() {
public boolean canNotWithdrawByClientLoanInPast() { return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "REPAYMENTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER");
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "WITHDRAWINPAST_LOAN", }
"PORTFOLIO_MANAGEMENT_SUPER_USER");
} public boolean hasNotPermissionForReport(String reportName) {
public boolean canNotDisburseLoanInPast() { if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER", "READ_" + reportName)) return true;
return hasNotPermissionForAnyOf("ALL_FUNCTIONS", "DISBURSEINPAST_LOAN",
"PORTFOLIO_MANAGEMENT_SUPER_USER"); return false;
} }
public boolean canNotMakeRepaymentOnLoanInPast() { public boolean hasNotPermissionForDatatable(String datatable, String accessType) {
return hasNotPermissionForAnyOf("ALL_FUNCTIONS",
"REPAYMENTINPAST_LOAN", "PORTFOLIO_MANAGEMENT_SUPER_USER"); String matchPermission = accessType + "_" + datatable;
}
if (accessType.equalsIgnoreCase("READ")) {
public boolean hasNotPermissionForReport(String reportName) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", "REPORTING_SUPER_USER",
"READ_" + reportName)) return false;
return true; }
return false; if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
}
return false;
public boolean hasNotPermissionForDatatable(String datatable, }
String accessType) {
public boolean hasNotPermissionForSet(String type, String set, String accessType) {
String matchPermission = accessType + "_" + datatable;
String matchPermission = "CAN_" + accessType + "_" + type + "_x" + set;
if (accessType.equalsIgnoreCase("READ")) {
if (accessType.equalsIgnoreCase("READ")) {
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ",
matchPermission)) if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission)) return true;
return true;
return false;
return false; }
}
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission)) return true;
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission))
return true; return false;
}
return false;
} public boolean hasNotPermissionForAnyOf(final String... permissionCodes) {
boolean hasNotPermission = true;
public boolean hasNotPermissionForSet(String type, String set, for (String permissionCode : permissionCodes) {
String accessType) { boolean checkPermission = this.hasPermissionTo(permissionCode);
if (checkPermission) {
String matchPermission = "CAN_" + accessType + "_" + type + "_x" + set; hasNotPermission = false;
break;
if (accessType.equalsIgnoreCase("READ")) { }
}
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", return hasNotPermission;
matchPermission)) }
return true;
public void validateHasReadPermission(final String entityType) {
return false;
} String authorizationMessage = "User has no authority to view " + entityType.toLowerCase() + "s";
String matchPermission = "READ_" + entityType.toUpperCase();
if (hasNotPermissionForAnyOf("ALL_FUNCTIONS", matchPermission))
return true; if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", matchPermission))) return;
return false; String higherPermission = "";
} if (entityType.equalsIgnoreCase("CHARGE")) {
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
public boolean hasNotPermissionForAnyOf(final String... permissionCodes) { } else if (entityType.equalsIgnoreCase("CLIENT")) {
boolean hasNotPermission = true; higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
for (String permissionCode : permissionCodes) { } else if (entityType.equalsIgnoreCase("CLIENTNOTE")) {
boolean checkPermission = this.hasPermissionTo(permissionCode); higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
if (checkPermission) { } else if (entityType.equalsIgnoreCase("CLIENTIDENTIFIER")) {
hasNotPermission = false; higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
break; } else if (entityType.equalsIgnoreCase("CLIENTIMAGE")) {
} higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
} } else if (entityType.equalsIgnoreCase("CODE")) {
return hasNotPermission; higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
} } else if (entityType.equalsIgnoreCase("CURRENCY")) {
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
public void validateHasReadPermission(final String entityType) { } else if (entityType.equalsIgnoreCase("DOCUMENTMAN")) {
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
String authorizationMessage = "User has no authority to view " } else if (entityType.equalsIgnoreCase("FUND")) {
+ entityType.toLowerCase() + "s"; higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
String matchPermission = "READ_" + entityType.toUpperCase(); } else if (entityType.equalsIgnoreCase("GROUP")) {
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
if (!(hasNotPermissionForAnyOf("ALL_FUNCTIONS", "ALL_FUNCTIONS_READ", } else if (entityType.equalsIgnoreCase("LOANPRODUCT")) {
matchPermission))) higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
return; } else if (entityType.equalsIgnoreCase("LOAN")) {
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
String higherPermission = ""; } else if (entityType.equalsIgnoreCase("OFFICE")) {
if (entityType.equalsIgnoreCase("CHARGE")) { higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; } else if (entityType.equalsIgnoreCase("OFFICETRANSACTION")) {
} else if (entityType.equalsIgnoreCase("CLIENT")) { higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; } else if (entityType.equalsIgnoreCase("PERMISSION")) {
} else if (entityType.equalsIgnoreCase("CLIENTNOTE")) { higherPermission = "USER_ADMINISTRATION_SUPER_USER";
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; } else if (entityType.equalsIgnoreCase("ROLE")) {
} else if (entityType.equalsIgnoreCase("CLIENTIDENTIFIER")) { higherPermission = "USER_ADMINISTRATION_SUPER_USER";
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; } else if (entityType.equalsIgnoreCase("USER")) {
} else if (entityType.equalsIgnoreCase("CLIENTIMAGE")) { higherPermission = "USER_ADMINISTRATION_SUPER_USER";
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; } else if (entityType.equalsIgnoreCase("STAFF")) {
} else if (entityType.equalsIgnoreCase("CODE")) { higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; } else if (entityType.equalsIgnoreCase("SAVINGSPRODUCT")) {
} else if (entityType.equalsIgnoreCase("CURRENCY")) { higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; } else if (entityType.equalsIgnoreCase("DEPOSITPRODUCT")) {
} else if (entityType.equalsIgnoreCase("DOCUMENTMAN")) { higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; } else if (entityType.equalsIgnoreCase("DEPOSITACCOUNT")) {
} else if (entityType.equalsIgnoreCase("FUND")) { higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; } else if (entityType.equalsIgnoreCase("SAVINGSACCOUNT")) {
} else if (entityType.equalsIgnoreCase("GROUP")) { higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; }
} else if (entityType.equalsIgnoreCase("LOANPRODUCT")) {
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; if (!(higherPermission.equals(""))) {
} else if (entityType.equalsIgnoreCase("LOAN")) { if (hasNotPermissionForAnyOf(higherPermission)) throw new NoAuthorizationException(authorizationMessage);
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; }
} else if (entityType.equalsIgnoreCase("OFFICE")) {
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; }
} else if (entityType.equalsIgnoreCase("OFFICETRANSACTION")) {
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; private boolean hasPermissionTo(final String permissionCode) {
} else if (entityType.equalsIgnoreCase("PERMISSION")) { boolean match = false;
higherPermission = "USER_ADMINISTRATION_SUPER_USER"; for (Role role : this.roles) {
} else if (entityType.equalsIgnoreCase("ROLE")) { if (role.hasPermissionTo(permissionCode)) {
higherPermission = "USER_ADMINISTRATION_SUPER_USER"; match = true;
} else if (entityType.equalsIgnoreCase("USER")) { break;
higherPermission = "USER_ADMINISTRATION_SUPER_USER"; }
} else if (entityType.equalsIgnoreCase("STAFF")) { }
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER";
} else if (entityType.equalsIgnoreCase("SAVINGSPRODUCT")) { return match;
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; }
} else if (entityType.equalsIgnoreCase("DEPOSITPRODUCT")) {
higherPermission = "ORGANISATION_ADMINISTRATION_SUPER_USER"; public boolean hasIdOf(final Long userId) {
} else if (entityType.equalsIgnoreCase("DEPOSITACCOUNT")) { return getId().equals(userId);
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER"; }
} else if (entityType.equalsIgnoreCase("SAVINGSACCOUNT")) {
higherPermission = "PORTFOLIO_MANAGEMENT_SUPER_USER";
}
if (!(higherPermission.equals(""))) {
if (hasNotPermissionForAnyOf(higherPermission))
throw new NoAuthorizationException(authorizationMessage);
}
}
private boolean hasPermissionTo(final String permissionCode) {
boolean match = false;
for (Role role : this.roles) {
if (role.hasPermissionTo(permissionCode)) {
match = true;
break;
}
}
return match;
}
public boolean hasIdOf(final Long userId) {
return getId().equals(userId);
}
} }
@@ -22,11 +22,11 @@ import org.mifosng.platform.infrastructure.AbstractAuditableCustom;
@Table(name = "m_role") @Table(name = "m_role")
public class Role extends AbstractAuditableCustom<AppUser, Long> { public class Role extends AbstractAuditableCustom<AppUser, Long> {
@Column(name="name", nullable=false, length=100) @Column(name = "name", nullable = false, length = 100)
private String name; private String name;
@Column(name="description", nullable=false, length=500) @Column(name = "description", nullable = false, length = 500)
private String description; private String description;
@ManyToMany(fetch = FetchType.EAGER) @ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "m_role_permission", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "permission_id")) @JoinTable(name = "m_role_permission", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "permission_id"))
@@ -58,30 +58,30 @@ public class Role extends AbstractAuditableCustom<AppUser, Long> {
return match; return match;
} }
public RoleData toData() { public RoleData toData() {
Collection<PermissionData> rolePermissions = new ArrayList<PermissionData>();
for (Permission permission : this.permissions) {
PermissionData permissionData = permission.toData();
rolePermissions.add(permissionData);
}
return new RoleData(this.getId(), this.name, this.description, rolePermissions);
}
public void update(final RoleCommand command) { Collection<PermissionData> rolePermissions = new ArrayList<PermissionData>();
if (command.isNameChanged()) { for (Permission permission : this.permissions) {
this.name = command.getName(); PermissionData permissionData = permission.toData();
} rolePermissions.add(permissionData);
}
if (command.isDescriptionChanged()) {
this.description = command.getDescription(); return new RoleData(this.getId(), this.name, this.description, rolePermissions);
} }
} public void update(final RoleCommand command) {
if (command.isNameChanged()) {
this.name = command.getName();
}
if (command.isDescriptionChanged()) {
this.description = command.getDescription();
}
}
public String getName() {
return name;
}
public String getName() {
return name;
}
} }
@@ -6,9 +6,9 @@ import org.mifosng.platform.api.data.AppUserData;
public interface AppUserReadPlatformService { public interface AppUserReadPlatformService {
Collection<AppUserData> retrieveAllUsers(); Collection<AppUserData> retrieveAllUsers();
AppUserData retrieveNewUserDetails(); AppUserData retrieveNewUserDetails();
AppUserData retrieveUser(Long userId); AppUserData retrieveUser(Long userId);
} }
@@ -6,14 +6,15 @@ import org.springframework.security.access.prepost.PreAuthorize;
public interface AppUserWritePlatformService { public interface AppUserWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'CREATE_USER')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'CREATE_USER')")
Long createUser(final UserCommand command); Long createUser(final UserCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'UPDATE_USER')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'UPDATE_USER')")
Long updateUser(final UserCommand command); Long updateUser(final UserCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'DELETE_USER')") @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'USER_ADMINISTRATION_SUPER_USER', 'DELETE_USER')")
void deleteUser(final Long userId); void deleteUser(final Long userId);
// we dont put any permissions on this e.g. a user with no admin rights can change their own details (email, username, password etc). // we dont put any permissions on this e.g. a user with no admin rights can
void updateUsersOwnAccountDetails(UserCommand command); // change their own details (email, username, password etc).
void updateUsersOwnAccountDetails(UserCommand command);
} }
@@ -36,164 +36,157 @@ import org.springframework.util.ObjectUtils;
@Service @Service
public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWritePlatformService { public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(AppUserWritePlatformServiceJpaRepositoryImpl.class); private final static Logger logger = LoggerFactory.getLogger(AppUserWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final UserDomainService userDomainService;
private final PlatformPasswordEncoder platformPasswordEncoder;
private final AppUserRepository appUserRepository;
private final OfficeRepository officeRepository;
private final RoleRepository roleRepository;
@Autowired
public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository, final UserDomainService userDomainService,
final OfficeRepository officeRepository, final RoleRepository roleRepository, final PlatformPasswordEncoder platformPasswordEncoder) {
this.context = context;
this.appUserRepository = appUserRepository;
this.userDomainService = userDomainService;
this.officeRepository = officeRepository;
this.roleRepository = roleRepository;
this.platformPasswordEncoder = platformPasswordEncoder;
}
@Transactional
@Override
public Long createUser(final UserCommand command) {
try {
context.authenticatedUser();
UserCommandValidator validator = new UserCommandValidator(command);
validator.validateForCreate();
final Set<Role> allRoles = assembleSetOfRoles(command);
Office office = this.officeRepository.findOne(command.getOfficeId()); private final PlatformSecurityContext context;
if (office == null) { private final UserDomainService userDomainService;
throw new OfficeNotFoundException(command.getOfficeId()); private final PlatformPasswordEncoder platformPasswordEncoder;
} private final AppUserRepository appUserRepository;
private final OfficeRepository officeRepository;
private final RoleRepository roleRepository;
String password = command.getPassword(); @Autowired
if (StringUtils.isBlank(password)) { public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository,
password = "autogenerate"; final UserDomainService userDomainService, final OfficeRepository officeRepository, final RoleRepository roleRepository,
} final PlatformPasswordEncoder platformPasswordEncoder) {
this.context = context;
AppUser appUser = AppUser.createNew(office, this.appUserRepository = appUserRepository;
allRoles, command.getUsername(), command.getEmail(), this.userDomainService = userDomainService;
command.getFirstname(), command.getLastname(), this.officeRepository = officeRepository;
password); this.roleRepository = roleRepository;
this.platformPasswordEncoder = platformPasswordEncoder;
this.userDomainService.create(appUser); }
return appUser.getId();
} catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
} catch (PlatformEmailSendException e) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", "The parameter email is invalid.", "email", command.getEmail());
dataValidationErrors.add(error);
throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors);
}
}
@Transactional @Transactional
@Override @Override
public Long updateUser(final UserCommand command) { public Long createUser(final UserCommand command) {
try {
context.authenticatedUser();
UserCommandValidator validator = new UserCommandValidator(command);
validator.validateForUpdate();
final Set<Role> allRoles = assembleSetOfRoles(command);
Office office = null; try {
if (command.isOfficeChanged()) { context.authenticatedUser();
office = this.officeRepository.findOne(command.getOfficeId());
if (office == null) {
throw new OfficeNotFoundException(command.getOfficeId());
}
}
AppUser userToUpdate = this.appUserRepository.findOne(command.getId()); UserCommandValidator validator = new UserCommandValidator(command);
if (userToUpdate == null) { validator.validateForCreate();
throw new UserNotFoundException(command.getId());
}
userToUpdate.update(allRoles, office, command);
this.appUserRepository.saveAndFlush(userToUpdate);
if (command.isPasswordChanged()) {
PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(
userToUpdate.getId(),
userToUpdate.getUsername(), command.getPassword());
String newPasswordEncoded = this.platformPasswordEncoder.encode(dummyPlatformUser); final Set<Role> allRoles = assembleSetOfRoles(command);
userToUpdate.updatePassword(newPasswordEncoded); Office office = this.officeRepository.findOne(command.getOfficeId());
this.appUserRepository.saveAndFlush(userToUpdate); if (office == null) { throw new OfficeNotFoundException(command.getOfficeId()); }
}
String password = command.getPassword();
return userToUpdate.getId(); if (StringUtils.isBlank(password)) {
} catch (DataIntegrityViolationException dve) { password = "autogenerate";
handleDataIntegrityIssues(command, dve); }
return Long.valueOf(-1);
} AppUser appUser = AppUser.createNew(office, allRoles, command.getUsername(), command.getEmail(), command.getFirstname(),
} command.getLastname(), password);
@Transactional this.userDomainService.create(appUser);
@Override
public void updateUsersOwnAccountDetails(final UserCommand command) { return appUser.getId();
updateUser(command); } catch (DataIntegrityViolationException dve) {
} handleDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
private Set<Role> assembleSetOfRoles(final UserCommand command) { } catch (PlatformEmailSendException e) {
List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final Set<Role> allRoles = new HashSet<Role>(); ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", "The parameter email is invalid.",
"email", command.getEmail());
String[] rolesArray = command.getRoles(); dataValidationErrors.add(error);
if (command.isRolesChanged() && !ObjectUtils.isEmpty(rolesArray)) {
for (String roleId : rolesArray) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
Long id = Long.valueOf(roleId); dataValidationErrors);
Role role = this.roleRepository.findOne(id); }
if (role == null) { }
throw new RoleNotFoundException(id);
} @Transactional
allRoles.add(role); @Override
} public Long updateUser(final UserCommand command) {
}
try {
return allRoles; context.authenticatedUser();
}
UserCommandValidator validator = new UserCommandValidator(command);
@Transactional validator.validateForUpdate();
@Override
public void deleteUser(final Long userId) { final Set<Role> allRoles = assembleSetOfRoles(command);
AppUser user = this.appUserRepository.findOne(userId); Office office = null;
if (user == null || user.isDeleted()) { if (command.isOfficeChanged()) {
throw new UserNotFoundException(userId); office = this.officeRepository.findOne(command.getOfficeId());
} if (office == null) { throw new OfficeNotFoundException(command.getOfficeId()); }
}
user.delete();
this.appUserRepository.save(user); AppUser userToUpdate = this.appUserRepository.findOne(command.getId());
} if (userToUpdate == null) { throw new UserNotFoundException(command.getId()); }
/* userToUpdate.update(allRoles, office, command);
* Guaranteed to throw an exception no matter what the data integrity issue is. this.appUserRepository.saveAndFlush(userToUpdate);
*/
private void handleDataIntegrityIssues(final UserCommand command, final DataIntegrityViolationException dve) { if (command.isPasswordChanged()) {
PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(userToUpdate.getId(), userToUpdate.getUsername(),
Throwable realCause = dve.getMostSpecificCause(); command.getPassword());
if (realCause.getMessage().contains("username_org")) {
StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(command.getUsername()).append(" already exists."); String newPasswordEncoded = this.platformPasswordEncoder.encode(dummyPlatformUser);
throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username", command.getUsername());
} userToUpdate.updatePassword(newPasswordEncoded);
this.appUserRepository.saveAndFlush(userToUpdate);
logger.error(dve.getMessage(), dve); }
throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource.");
} return userToUpdate.getId();
} catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve);
return Long.valueOf(-1);
}
}
@Transactional
@Override
public void updateUsersOwnAccountDetails(final UserCommand command) {
updateUser(command);
}
private Set<Role> assembleSetOfRoles(final UserCommand command) {
final Set<Role> allRoles = new HashSet<Role>();
String[] rolesArray = command.getRoles();
if (command.isRolesChanged() && !ObjectUtils.isEmpty(rolesArray)) {
for (String roleId : rolesArray) {
Long id = Long.valueOf(roleId);
Role role = this.roleRepository.findOne(id);
if (role == null) { throw new RoleNotFoundException(id); }
allRoles.add(role);
}
}
return allRoles;
}
@Transactional
@Override
public void deleteUser(final Long userId) {
AppUser user = this.appUserRepository.findOne(userId);
if (user == null || user.isDeleted()) { throw new UserNotFoundException(userId); }
user.delete();
this.appUserRepository.save(user);
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue
* is.
*/
private void handleDataIntegrityIssues(final UserCommand command, final DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("username_org")) {
StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(command.getUsername()).append(
" already exists.");
throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username",
command.getUsername());
}
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource.");
}
} }
@@ -7,7 +7,7 @@ import org.mifosng.platform.api.data.PermissionUsageData;
public interface PermissionReadPlatformService { public interface PermissionReadPlatformService {
Collection<PermissionData> retrieveAllPermissions(); Collection<PermissionData> retrieveAllPermissions();
Collection<PermissionUsageData> retrieveAllRolePermissions(Long roleId); Collection<PermissionUsageData> retrieveAllRolePermissions(Long roleId);
} }
@@ -17,74 +17,73 @@ import org.springframework.stereotype.Service;
@Service @Service
public class PermissionReadPlatformServiceImpl implements PermissionReadPlatformService { public class PermissionReadPlatformServiceImpl implements PermissionReadPlatformService {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
@Autowired @Autowired
public PermissionReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) { public PermissionReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) {
this.context = context; this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource); this.jdbcTemplate = new JdbcTemplate(dataSource);
} }
@Override @Override
public Collection<PermissionData> retrieveAllPermissions() { public Collection<PermissionData> retrieveAllPermissions() {
context.authenticatedUser(); context.authenticatedUser();
final PermissionMapper mapper = new PermissionMapper(); final PermissionMapper mapper = new PermissionMapper();
final String sql = "select " + mapper.schema() + " order by p.id"; final String sql = "select " + mapper.schema() + " order by p.id";
return this.jdbcTemplate.query(sql, mapper, new Object[] {}); return this.jdbcTemplate.query(sql, mapper, new Object[] {});
} }
private static final class PermissionMapper implements RowMapper<PermissionData> { private static final class PermissionMapper implements RowMapper<PermissionData> {
@Override @Override
public PermissionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { public PermissionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id"); final Long id = JdbcSupport.getLong(rs, "id");
final String name = rs.getString("name"); final String name = rs.getString("name");
final String description = rs.getString("description"); final String description = rs.getString("description");
final String code = rs.getString("code"); final String code = rs.getString("code");
return new PermissionData(id, name, description, code); return new PermissionData(id, name, description, code);
} }
public String schema() { public String schema() {
return " p.id as id, p.default_name as name, p.default_description as description, p.code as code from m_permission p "; return " p.id as id, p.default_name as name, p.default_description as description, p.code as code from m_permission p ";
} }
} }
@Override @Override
public Collection<PermissionUsageData> retrieveAllRolePermissions(Long roleId) { public Collection<PermissionUsageData> retrieveAllRolePermissions(final Long roleId) {
final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper();
final String sql = mapper.schema();
return this.jdbcTemplate.query(sql, mapper, new Object[] {roleId}); final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper();
} final String sql = mapper.schema();
private static final class PermissionUsageDataMapper implements RowMapper<PermissionUsageData> { return this.jdbcTemplate.query(sql, mapper, new Object[] { roleId });
}
@Override private static final class PermissionUsageDataMapper implements RowMapper<PermissionUsageData> {
public PermissionUsageData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final String grouping = rs.getString("grouping"); @Override
final String code = rs.getString("code"); public PermissionUsageData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final String entityName = rs.getString("entityName");
final String actionName = rs.getString("actionName");
final Boolean selected = rs.getBoolean("selected");
return new PermissionUsageData(grouping, code, entityName, actionName, selected); final String grouping = rs.getString("grouping");
} final String code = rs.getString("code");
final String entityName = rs.getString("entityName");
final String actionName = rs.getString("actionName");
final Boolean selected = rs.getBoolean("selected");
return new PermissionUsageData(grouping, code, entityName, actionName, selected);
}
public String schema() {
return "select p.grouping, p.code, p.entity_name as entityName, p.action_name as actionName, if(isnull(rp.role_id), false, true) as selected "
+ "from m_permission p "
+ "left join m_role_permission rp on rp.permission_id = p.id and rp.role_id = ? "
+ "order by p.grouping, ifnull(entity_name, ''), p.code";
}
}
public String schema() {
return "select p.grouping, p.code, p.entity_name as entityName, p.action_name as actionName, if(isnull(rp.role_id), false, true) as selected " +
"from m_permission p " +
"left join m_role_permission rp on rp.permission_id = p.id and rp.role_id = ? " +
"order by p.grouping, ifnull(entity_name, ''), p.code";
}
}
} }
@@ -6,7 +6,7 @@ import org.mifosng.platform.api.data.RoleData;
public interface RoleReadPlatformService { public interface RoleReadPlatformService {
Collection<RoleData> retrieveAllRoles(); Collection<RoleData> retrieveAllRoles();
RoleData retrieveRole(Long roleId); RoleData retrieveRole(Long roleId);
} }
@@ -19,53 +19,52 @@ import org.springframework.stereotype.Service;
@Service @Service
public class RoleReadPlatformServiceImpl implements RoleReadPlatformService { public class RoleReadPlatformServiceImpl implements RoleReadPlatformService {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final RoleRepository roleRepository; private final RoleRepository roleRepository;
@Autowired @Autowired
public RoleReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource, final RoleRepository roleRepository) { public RoleReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource,
this.context = context; final RoleRepository roleRepository) {
this.roleRepository = roleRepository; this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource); this.roleRepository = roleRepository;
} this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override @Override
public Collection<RoleData> retrieveAllRoles() { public Collection<RoleData> retrieveAllRoles() {
context.authenticatedUser(); context.authenticatedUser();
final RoleMapper mapper = new RoleMapper(); final RoleMapper mapper = new RoleMapper();
final String sql = "select " + mapper.schema() + " order by r.id"; final String sql = "select " + mapper.schema() + " order by r.id";
return this.jdbcTemplate.query(sql, mapper, new Object[] {}); return this.jdbcTemplate.query(sql, mapper, new Object[] {});
} }
@Override @Override
public RoleData retrieveRole(final Long id) { public RoleData retrieveRole(final Long id) {
context.authenticatedUser(); context.authenticatedUser();
final Role role = this.roleRepository.findOne(id);
if (role == null) {
throw new RoleNotFoundException(id);
}
return role.toData();
}
protected static final class RoleMapper implements RowMapper<RoleData> { final Role role = this.roleRepository.findOne(id);
if (role == null) { throw new RoleNotFoundException(id); }
return role.toData();
}
@Override protected static final class RoleMapper implements RowMapper<RoleData> {
public RoleData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum)
throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id"); @Override
final String name = rs.getString("name"); public RoleData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final String description = rs.getString("description");
return new RoleData(id, name, description); final Long id = JdbcSupport.getLong(rs, "id");
} final String name = rs.getString("name");
final String description = rs.getString("description");
public String schema() { return new RoleData(id, name, description);
return " r.id as id, r.name as name, r.description as description from m_role r"; }
}
} public String schema() {
return " r.id as id, r.name as name, r.description as description from m_role r";
}
}
} }