diff --git a/mifosng-data/src/main/java/org/mifosng/data/command/RoleCommand.java b/mifosng-data/src/main/java/org/mifosng/data/command/RoleCommand.java index 5a4e450f3..5a8243267 100644 --- a/mifosng-data/src/main/java/org/mifosng/data/command/RoleCommand.java +++ b/mifosng-data/src/main/java/org/mifosng/data/command/RoleCommand.java @@ -11,7 +11,9 @@ public class RoleCommand { private Long id; private String name; private String description; - private String[] permissionIds; + + private String[] notSelectedItems; + private String[] selectedItems; protected RoleCommand() { // @@ -20,7 +22,7 @@ public class RoleCommand { public RoleCommand(final String name, final String description, final String[] permissionIds) { this.name = name; this.description = description; - this.permissionIds = permissionIds; + this.selectedItems = permissionIds; } public String getName() { @@ -39,14 +41,6 @@ public class RoleCommand { this.description = description; } - public String[] getPermissionIds() { - return this.permissionIds; - } - - public void setPermissionIds(final String[] permissionIds) { - this.permissionIds = permissionIds; - } - public Long getId() { return id; } @@ -54,4 +48,20 @@ public class RoleCommand { public void setId(Long id) { this.id = id; } + + public String[] getNotSelectedItems() { + return notSelectedItems; + } + + public void setNotSelectedItems(String... notSelectedItems) { + this.notSelectedItems = notSelectedItems; + } + + public String[] getSelectedItems() { + return selectedItems; + } + + public void setSelectedItems(String... selectedItems) { + this.selectedItems = selectedItems; + } } \ No newline at end of file diff --git a/mifosng-data/src/main/java/org/mifosng/data/command/UserCommand.java b/mifosng-data/src/main/java/org/mifosng/data/command/UserCommand.java index a77704ca6..adea09ef3 100644 --- a/mifosng-data/src/main/java/org/mifosng/data/command/UserCommand.java +++ b/mifosng-data/src/main/java/org/mifosng/data/command/UserCommand.java @@ -1,8 +1,6 @@ package org.mifosng.data.command; import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @@ -20,7 +18,7 @@ public class UserCommand implements Serializable { private String email; private Long officeId; - private List notSelectedItems = new ArrayList(); + private String[] notSelectedItems; private String[] selectedItems; public UserCommand() { @@ -87,11 +85,11 @@ public class UserCommand implements Serializable { this.id = id; } - public List getNotSelectedItems() { + public String[] getNotSelectedItems() { return notSelectedItems; } - public void setNotSelectedItems(List notSelectedItems) { + public void setNotSelectedItems(String... notSelectedItems) { this.notSelectedItems = notSelectedItems; } diff --git a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java index 58308bb43..71f6f775b 100644 --- a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java +++ b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java @@ -13,14 +13,12 @@ import org.mifosng.data.LoanSchedule; import org.mifosng.data.NewLoanWorkflowStepOneData; import org.mifosng.data.NoteData; import org.mifosng.data.PermissionData; -import org.mifosng.data.RoleData; import org.mifosng.data.command.AdjustLoanTransactionCommand; import org.mifosng.data.command.CalculateLoanScheduleCommand; import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.NoteCommand; -import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand; @@ -33,20 +31,10 @@ public interface CommonRestOperations { void updateProtectedResource(ProtectedResourceDetails loadProtectedResourceDetailsById); - Collection retrieveAllRoles(); - - RoleData retrieveRole(Long roleId); - - RoleData retrieveNewRoleDetails(); - - EntityIdentifier updateRole(RoleCommand command); - Collection retrieveAllPermissions(); Collection retrieveAllPermissionGroups(); - EntityIdentifier createRole(RoleCommand command); - Collection retrieveAllIndividualClients(); Collection retrieveAllLoanProducts(); diff --git a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java index d9e8b0a17..c53946a40 100644 --- a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java +++ b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java @@ -24,15 +24,12 @@ import org.mifosng.data.NoteData; import org.mifosng.data.NoteDataList; import org.mifosng.data.PermissionData; import org.mifosng.data.PermissionList; -import org.mifosng.data.RoleData; -import org.mifosng.data.RoleList; import org.mifosng.data.command.AdjustLoanTransactionCommand; import org.mifosng.data.command.CalculateLoanScheduleCommand; import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.NoteCommand; -import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand; @@ -556,92 +553,6 @@ public class CommonRestOperationsImpl implements CommonRestOperations { return requestEntity; } - private HttpEntity roleRequest(final RoleCommand command) { - - HttpHeaders requestHeaders = new HttpHeaders(); - requestHeaders.set("Accept", "application/xml"); - requestHeaders.set("Content-Type", "application/xml"); - - HttpEntity requestEntity = new HttpEntity( - command, requestHeaders); - return requestEntity; - } - - @Override - public Collection retrieveAllRoles() { - try { - URI restUri = URI.create(getBaseServerUrl().concat( - "api/protected/admin/role/all")); - - ResponseEntity s = this.oauthRestServiceTemplate - .exchange(restUri, HttpMethod.GET, emptyRequest(), - RoleList.class); - - return s.getBody().getRoles(); - } catch (HttpStatusCodeException e) { - ErrorResponseList errorList = parseErrors(e); - throw new ClientValidationException(errorList.getErrors()); - } - } - - @Override - public RoleData retrieveRole(final Long roleId) { - - URI restUri = URI.create(getBaseServerUrl().concat( - "api/protected/admin/role/").concat(roleId.toString())); - - ResponseEntity s = this.oauthRestServiceTemplate.exchange( - restUri, HttpMethod.GET, emptyRequest(), RoleData.class); - - return s.getBody(); - } - - @Override - public RoleData retrieveNewRoleDetails() { - URI restUri = URI.create(getBaseServerUrl().concat( - "api/protected/admin/role/new")); - - ResponseEntity s = this.oauthRestServiceTemplate.exchange( - restUri, HttpMethod.GET, emptyRequest(), RoleData.class); - - return s.getBody(); - } - - @Override - public EntityIdentifier createRole(final RoleCommand command) { - try { - URI restUri = URI.create(getBaseServerUrl().concat( - "api/protected/admin/role/new")); - - ResponseEntity s = this.oauthRestServiceTemplate - .postForEntity(restUri, roleRequest(command), - EntityIdentifier.class); - - return s.getBody(); - } catch (HttpStatusCodeException e) { - ErrorResponseList errorList = parseErrors(e); - throw new ClientValidationException(errorList.getErrors()); - } - } - - @Override - public EntityIdentifier updateRole(RoleCommand command) { - try { - URI restUri = URI.create(getBaseServerUrl().concat( - "api/protected/admin/role/").concat( - command.getId().toString())); - - ResponseEntity s = this.oauthRestServiceTemplate - .postForEntity(restUri, roleRequest(command), - EntityIdentifier.class); - - return s.getBody(); - } catch (HttpStatusCodeException e) { - ErrorResponseList errorList = parseErrors(e); - throw new ClientValidationException(errorList.getErrors()); - } - } - @Override public Collection retrieveAllPermissions() { diff --git a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/AppUserController.java b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/AppUserController.java deleted file mode 100644 index 11d9415a2..000000000 --- a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/AppUserController.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.mifosng.ui.user; - -import java.util.Collection; - -import javax.servlet.http.HttpServletResponse; - -import org.mifosng.data.EntityIdentifier; -import org.mifosng.data.ErrorResponse; -import org.mifosng.data.PermissionData; -import org.mifosng.data.RoleData; -import org.mifosng.data.command.RoleCommand; -import org.mifosng.ui.CommonRestOperations; -import org.mifosng.ui.loanproduct.ClientValidationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class AppUserController { - - private final CommonRestOperations commonRestOperations; - - @Autowired - public AppUserController(final CommonRestOperations commonRestOperations) { - this.commonRestOperations = commonRestOperations; - } - - @RequestMapping(consumes="application/json", produces="application/json", value = "/admin/permission/all", method = RequestMethod.GET) - public @ResponseBody Collection viewAllPermission() { - - return this.commonRestOperations.retrieveAllPermissions(); - } - - @RequestMapping(consumes="application/json", produces="application/json", value = "/admin/role/all", method = RequestMethod.GET) - public @ResponseBody Collection viewAllRoles() { - - return this.commonRestOperations.retrieveAllRoles(); - } - - @RequestMapping(consumes="application/json", produces="application/json", value = "/admin/role/new", method = RequestMethod.GET) - public @ResponseBody RoleData newRoleDetails() { - - return this.commonRestOperations.retrieveNewRoleDetails(); - } - - @RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "/admin/role/new", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.OK) - public @ResponseBody EntityIdentifier createNewRole(@RequestParam(value="selectedItems", required=false) String[] selectedRoles, - @RequestParam(value="name") String name, - @RequestParam(value="description") String description) { - - RoleCommand command = new RoleCommand(name, description, selectedRoles); - - return this.commonRestOperations.createRole(command); - } - - @RequestMapping(consumes = "application/json", produces = "application/json", value = "/admin/role/{roleId}", method = RequestMethod.GET) - public @ResponseBody - RoleData retrieveRoleDetails(@PathVariable("roleId") Long roleId) { - - return this.commonRestOperations.retrieveRole(roleId); - } - - @RequestMapping(consumes="application/x-www-form-urlencoded", produces="application/json", value = "/admin/role/{roleId}", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.OK) - public @ResponseBody EntityIdentifier updateRole(@PathVariable("roleId") Long roleId, - @RequestParam(value="selectedItems", required=false) String[] selectedRoles, - @RequestParam(value="name") String name, - @RequestParam(value="description") String description) { - - RoleCommand command = new RoleCommand(name, description, selectedRoles); - command.setId(roleId); - - return this.commonRestOperations.updateRole(command); - } - - @ExceptionHandler(ClientValidationException.class) - public @ResponseBody Collection validationException(ClientValidationException ex, HttpServletResponse response) { - - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.setContentType("application/json"); - - return ex.getValidationErrors(); - } -} \ No newline at end of file diff --git a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/admin/userhome.jsp b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/admin/userhome.jsp index e50188e02..5854ccd8c 100644 --- a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/admin/userhome.jsp +++ b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/admin/userhome.jsp @@ -346,62 +346,30 @@ $(document).ready(function() { }); $('#listroles').click(function(e) { - var listUrl = "${allRolesUrl}"; - var templateSelector = "#roleListTemplate"; - var displayAreaDivSelector = "#contentplaceholder"; - var singleEntityPrefixUrl = '${rootContext}admin/role/'; - var singleEntityTemplateSelector = "#roleFormTemplate"; - - var saveSuccessFunction = function(data, textStatus, jqXHR) { - - $("#dialog-form").dialog("close"); - - var listUrl = "${allRolesUrl}"; - var templateSelector = "#roleListTemplate"; - var displayAreaDivSelector = "#contentplaceholder"; - var singleEntityPrefixUrl = '${rootContext}admin/role/'; - var singleEntityTemplateSelector = "#roleFormTemplate"; - - displayListView(listUrl, templateSelector, displayAreaDivSelector, singleEntityPrefixUrl, singleEntityTemplateSelector); - } - - displayListView(listUrl, templateSelector, displayAreaDivSelector, singleEntityPrefixUrl, singleEntityTemplateSelector, saveSuccessFunction); - + var listUrl = "http://localhost:8080/mifosng-provider/api/v1/roles"; + refreshRolesView(); e.preventDefault(); }); $('#addrole').click(function(e) { - var url = '${rootContext}admin/role/new'; + var url = 'http://localhost:8080/mifosng-provider/api/v1/roles/template'; + var postUrl = "http://localhost:8080/mifosng-provider/api/v1/roles"; var templateSelector = "#roleFormTemplate"; var width = 1000; var height = 550; var saveSuccessFunction = function(data, textStatus, jqXHR) { - - $("#dialog-form").dialog("close"); - - var listUrl = "${allRolesUrl}"; - var templateSelector = "#roleListTemplate"; - var displayAreaDivSelector = "#contentplaceholder"; - var singleEntityPrefixUrl = '${rootContext}admin/role/'; - var singleEntityTemplateSelector = "#roleFormTemplate"; - - displayListView(listUrl, templateSelector, displayAreaDivSelector, singleEntityPrefixUrl, singleEntityTemplateSelector); + $("#dialog-form").dialog("close"); + refreshRolesView(); } - - popupDialogWithFormView(url, 'dialog.title.add.role', templateSelector, width, height, saveSuccessFunction); + + popupDialogWithFormView(url, postUrl, 'POST', 'dialog.title.add.role', templateSelector, width, height, saveSuccessFunction); e.preventDefault(); }); $('#listpermissions').click(function(e) { - var listUrl = "${allPermissionsUrl}"; - var templateSelector = "#permissionListTemplate"; - var displayAreaDivSelector = "#contentplaceholder"; - var singleEntityPrefixUrl = '${rootContext}admin/permission/'; - var singleEntityTemplateSelector = "#roleFormTemplate"; - - displayListView(listUrl, templateSelector, displayAreaDivSelector, singleEntityPrefixUrl, singleEntityTemplateSelector); + refreshPermissionsView(); e.preventDefault(); }); @@ -410,8 +378,6 @@ $(document).ready(function() { var listUrl = 'http://localhost:8080/mifosng-provider/api/v1/users'; var templateSelector = "#usersListTemplate"; var displayAreaDivSelector = "#contentplaceholder"; - var singleEntityPrefixUrl = 'http://localhost:8080/mifosng-provider/api/v1/users/'; - var singleEntityTemplateSelector = "#userFormTemplate"; var jqxhr = $.ajax({ url: listUrl, @@ -430,8 +396,8 @@ $(document).ready(function() { var putUrl = 'http://localhost:8080/mifosng-provider/api/v1/users/' + entityId; var templateSelector = "#userFormTemplate"; - var width = 600; - var height = 400; + var width = 1000; + var height = 550; var saveSuccessFunction = function(data, textStatus, jqXHR) { $("#dialog-form").dialog("close"); @@ -469,6 +435,102 @@ $(document).ready(function() { handleXhrError(jqXHR, textStatus, errorThrown, "#formErrorsTemplate", "#formerrors"); }); } + + function refreshRolesView() { + var listUrl = 'http://localhost:8080/mifosng-provider/api/v1/roles'; + var templateSelector = "#roleListTemplate"; + var displayAreaDivSelector = "#contentplaceholder"; + + var jqxhr = $.ajax({ + url: listUrl, + type: 'GET', + contentType: 'application/json', + dataType: 'json', + success: function(data, textStatus, jqXHR) { + console.log(data); + var listHtml = $(templateSelector).render(data); + $(displayAreaDivSelector).html(listHtml); + + $("a.edit").click( function(e) { + var linkId = this.id; + var entityId = linkId.replace("edit", ""); + var getUrl = 'http://localhost:8080/mifosng-provider/api/v1/roles/' + entityId; + var putUrl = 'http://localhost:8080/mifosng-provider/api/v1/roles/' + entityId; + + var templateSelector = "#roleFormTemplate"; + var width = 1000; + var height = 550; + + var saveSuccessFunction = function(data, textStatus, jqXHR) { + $("#dialog-form").dialog("close"); + refreshUsersView(); + } + + popupDialogWithFormView(getUrl, putUrl, 'PUT', "dialog.title.edit.details", templateSelector, width, height, saveSuccessFunction); + e.preventDefault(); + }); + + $("a.delete").click( function(e) { + var linkId = this.id; + var entityId = linkId.replace("delete", ""); + var url = 'http://localhost:8080/mifosng-provider/api/v1/roles/' + entityId; + showNotAvailableDialog('dialog.title.functionality.not.available'); + + e.preventDefault(); + }); + + var oTable = $("#entitytable").dataTable( { + "bSort": true, + "bInfo": true, + "bJQueryUI": true, + "bRetrieve": false, + "bScrollCollapse": false, + "bPaginate": false, + "bLengthChange": false, + "bFilter": false, + "bAutoWidth": false, + } ); + } + }); + + jqxhr.error(function(jqXHR, textStatus, errorThrown) { + handleXhrError(jqXHR, textStatus, errorThrown, "#formErrorsTemplate", "#formerrors"); + }); + } + + function refreshPermissionsView() { + var listUrl = 'http://localhost:8080/mifosng-provider/api/v1/permissions'; + var templateSelector = "#permissionListTemplate"; + var displayAreaDivSelector = "#contentplaceholder"; + + var jqxhr = $.ajax({ + url: listUrl, + type: 'GET', + contentType: 'application/json', + dataType: 'json', + success: function(data, textStatus, jqXHR) { + console.log(data); + var listHtml = $(templateSelector).render(data); + $(displayAreaDivSelector).html(listHtml); + + var oTable = $("#entitytable").dataTable( { + "bSort": true, + "bInfo": true, + "bJQueryUI": true, + "bRetrieve": false, + "bScrollCollapse": false, + "bPaginate": false, + "bLengthChange": false, + "bFilter": false, + "bAutoWidth": false, + } ); + } + }); + + jqxhr.error(function(jqXHR, textStatus, errorThrown) { + handleXhrError(jqXHR, textStatus, errorThrown, "#formErrorsTemplate", "#formerrors"); + }); + } // end of document.ready }); diff --git a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/administration-view-templates.jsp b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/administration-view-templates.jsp index 7a2beadfa..c1642c36a 100644 --- a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/administration-view-templates.jsp +++ b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/administration-view-templates.jsp @@ -372,7 +372,7 @@ -{{#each items}} +{{#each permissions}} {{#if $ctx.number(groupType)===$ctx.number(0)}} @@ -412,7 +412,7 @@ -{{#each items}} +{{#each roles}} {{=name}} {{=description}} diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java index 7214c12ad..b5fe3d229 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java @@ -55,6 +55,8 @@ public class ReadExtraDataAndReportingServiceImpl implements final String type, final Map queryParams) { return new StreamingOutput() { + + @Override public void write(OutputStream out) throws IOException, WebApplicationException { try { diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformService.java index f6fdd92d6..bb9c4c648 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformService.java @@ -1,20 +1,14 @@ package org.mifosng.platform; import java.util.Collection; -import java.util.List; -import org.mifosng.data.AppUserData; import org.mifosng.data.ClientData; import org.mifosng.data.ClientDataWithAccountsData; -import org.mifosng.data.CurrencyData; -import org.mifosng.data.EnumOptionReadModel; import org.mifosng.data.LoanAccountData; import org.mifosng.data.LoanRepaymentData; import org.mifosng.data.NewLoanWorkflowStepOneData; import org.mifosng.data.NoteData; import org.mifosng.data.OrganisationReadModel; -import org.mifosng.data.PermissionData; -import org.mifosng.data.RoleData; public interface ReadPlatformService { @@ -36,26 +30,6 @@ public interface ReadPlatformService { LoanRepaymentData retrieveLoanRepaymentDetails(Long loanId, Long repaymentId); - List retrieveAllowedCurrencies(); - - List retrieveAllPlatformCurrencies(); - - Collection retrieveAllUsers(); - - AppUserData retrieveNewUserDetails(); - - AppUserData retrieveUser(Long userId); - - AppUserData retrieveCurrentUser(); - - Collection retrieveAllRoles(); - - RoleData retrieveRole(Long roleId); - - Collection retrieveAllPermissionGroups(); - - Collection retrieveAllPermissions(); - ClientData retrieveNewClientDetails(); Collection retrieveAllClientNotes(Long clientId); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformServiceImpl.java index 3cf6ade6a..77f9528af 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/ReadPlatformServiceImpl.java @@ -3,7 +3,6 @@ package org.mifosng.platform; import static org.mifosng.platform.Specifications.clientsThatMatch; import static org.mifosng.platform.Specifications.loanTransactionsThatMatch; import static org.mifosng.platform.Specifications.loansThatMatch; -import static org.mifosng.platform.Specifications.usersThatMatch; import java.sql.ResultSet; import java.sql.SQLException; @@ -11,7 +10,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Set; import javax.sql.DataSource; @@ -23,7 +21,6 @@ import org.mifosng.data.ClientData; import org.mifosng.data.ClientDataWithAccountsData; import org.mifosng.data.CurrencyData; import org.mifosng.data.DerivedLoanData; -import org.mifosng.data.EnumOptionReadModel; import org.mifosng.data.LoanAccountData; import org.mifosng.data.LoanProductData; import org.mifosng.data.LoanRepaymentData; @@ -32,8 +29,6 @@ import org.mifosng.data.NewLoanWorkflowStepOneData; import org.mifosng.data.NoteData; import org.mifosng.data.OfficeData; import org.mifosng.data.OrganisationReadModel; -import org.mifosng.data.PermissionData; -import org.mifosng.data.RoleData; import org.mifosng.platform.client.domain.Client; import org.mifosng.platform.client.domain.ClientRepository; import org.mifosng.platform.currency.domain.ApplicationCurrency; @@ -48,10 +43,7 @@ import org.mifosng.platform.loan.domain.LoanTransactionRepository; import org.mifosng.platform.loanproduct.service.LoanProductReadPlatformService; import org.mifosng.platform.organisation.domain.Organisation; import org.mifosng.platform.user.domain.AppUser; -import org.mifosng.platform.user.domain.AppUserRepository; -import org.mifosng.platform.user.domain.PermissionGroup; -import org.mifosng.platform.user.domain.Role; -import org.mifosng.platform.user.domain.RoleRepository; +import org.mifosng.platform.user.service.AppUserReadPlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; @@ -69,26 +61,22 @@ public class ReadPlatformServiceImpl implements ReadPlatformService { private final LoanRepository loanRepository; private final LoanTransactionRepository loanTransactionRepository; private final ApplicationCurrencyRepository applicationCurrencyRepository; - private final AppUserRepository appUserRepository; - private final RoleRepository roleRepository; - private final LoanProductReadPlatformService loanProductReadPlatformService; + private final AppUserReadPlatformService appUserReadPlatformService; @Autowired public ReadPlatformServiceImpl( final LoanProductReadPlatformService loanProductReadPlatformService, + final AppUserReadPlatformService appUserReadPlatformService, final DataSource dataSource, final ClientRepository clientRepository, final LoanRepository loanRepository, final LoanTransactionRepository loanTransactionRepository, - final ApplicationCurrencyRepository applicationCurrencyRepository, - final AppUserRepository appUserRepository, - final RoleRepository roleRepository) { + final ApplicationCurrencyRepository applicationCurrencyRepository) { this.loanProductReadPlatformService = loanProductReadPlatformService; + this.appUserReadPlatformService = appUserReadPlatformService; this.loanTransactionRepository = loanTransactionRepository; this.applicationCurrencyRepository = applicationCurrencyRepository; - this.appUserRepository = appUserRepository; - this.roleRepository = roleRepository; this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); this.clientRepository = clientRepository; this.loanRepository = loanRepository; @@ -174,7 +162,7 @@ public class ReadPlatformServiceImpl implements ReadPlatformService { try { AppUser currentUser = extractAuthenticatedUser(); - Collection allUsers = retrieveAllUsers(); + Collection allUsers = this.appUserReadPlatformService.retrieveAllUsers(); NoteMapper noteMapper = new NoteMapper(allUsers); @@ -196,7 +184,7 @@ public class ReadPlatformServiceImpl implements ReadPlatformService { AppUser currentUser = extractAuthenticatedUser(); - Collection allUsers = retrieveAllUsers(); + Collection allUsers = this.appUserReadPlatformService.retrieveAllUsers(); NoteMapper noteMapper = new NoteMapper(allUsers); @@ -680,260 +668,6 @@ public class ReadPlatformServiceImpl implements ReadPlatformService { tolerance, loanData, waiveAllowed, interestRebateOwed); } - @Override - public List retrieveAllowedCurrencies() { - - AppUser currentUser = extractAuthenticatedUser(); - - String sql = "select c.code as code, c.name as name, c.decimal_places as decimalPlaces, c.display_symbol as displaySymbol, c.internationalized_name_code as nameCode from org_organisation_currency c where c.org_id = ?"; - - RowMapper rm = new CurrencyMapper(); - - return this.jdbcTemplate.query(sql, rm, new Object[] { currentUser - .getOrganisation().getId() }); - } - - @Override - public List retrieveAllPlatformCurrencies() { - - String sql = "select c.code as code, c.name as name, c.decimal_places as decimalPlaces, c.display_symbol as displaySymbol, c.internationalized_name_code as nameCode from ref_currency c"; - - RowMapper rm = new CurrencyMapper(); - - return this.jdbcTemplate.query(sql, rm, new Object[] {}); - } - - protected static final class CurrencyMapper implements - RowMapper { - - @Override - public CurrencyData mapRow(final ResultSet rs, final int rowNum) - throws SQLException { - - String code = rs.getString("code"); - String name = rs.getString("name"); - int decimalPlaces = rs.getInt("decimalPlaces"); - String displaySymbol = rs.getString("displaySymbol"); - String nameCode = rs.getString("nameCode"); - - return new CurrencyData(code, name, decimalPlaces, displaySymbol, - nameCode); - } - } - - @Override - public Collection retrieveAllUsers() { - - AppUser currentUser = extractAuthenticatedUser(); - - List offices = retrieveOffices(); - String officeIdsList = generateOfficeIdInClause(offices); - - AppUserMapper mapper = new AppUserMapper(offices); - String sql = "select " + mapper.schema() - + " where u.org_id = ? and u.office_id in (" + officeIdsList - + ")"; - - return this.jdbcTemplate.query(sql, mapper, new Object[] { currentUser - .getOrganisation().getId() }); - } - - @Override - public AppUserData retrieveNewUserDetails() { - - List offices = retrieveOffices(); - - List availableRoles = new ArrayList( - retrieveAllRoles()); - - AppUserData userData = new AppUserData(); - userData.setAllowedOffices(offices); - userData.setAvailableRoles(availableRoles); - - return userData; - } - - @Override - public AppUserData retrieveUser(Long userId) { - - AppUser currentUser = extractAuthenticatedUser(); - - List offices = retrieveOffices(); - - List availableRoles = new ArrayList(retrieveAllRoles()); - - AppUser user = this.appUserRepository.findOne(usersThatMatch(currentUser.getOrganisation(), userId)); - - if (user == null) { - throw new PlatformResourceNotFoundException("error.msg.user.id.invalid", "User with identifier {0} does not exist.", userId); - } - - List userRoleData = new ArrayList(); - Set userRoles = user.getRoles(); - for (Role role : userRoles) { - userRoleData.add(role.toData()); - } - - AppUserData userData = new AppUserData(user.getId(), - user.getUsername(), user.getEmail(), user.getOrganisation() - .getId(), user.getOffice().getId(), user.getOffice() - .getName()); - userData.setFirstname(user.getFirstname()); - userData.setLastname(user.getLastname()); - - userData.setAllowedOffices(offices); - - availableRoles.removeAll(userRoleData); - userData.setAvailableRoles(availableRoles); - userData.setSelectedRoles(userRoleData); - - return userData; - } - - @Override - public AppUserData retrieveCurrentUser() { - AppUser currentUser = extractAuthenticatedUser(); - - List offices = retrieveOffices(); - - List availableRoles = new ArrayList( - retrieveAllRoles()); - - AppUser user = this.appUserRepository.findOne(usersThatMatch( - currentUser.getOrganisation(), currentUser.getId())); - - List userRoleData = new ArrayList(); - Set userRoles = user.getRoles(); - for (Role role : userRoles) { - userRoleData.add(role.toData()); - } - - AppUserData userData = new AppUserData(user.getId(), - user.getUsername(), user.getEmail(), user.getOrganisation() - .getId(), user.getOffice().getId(), user.getOffice() - .getName()); - userData.setFirstname(user.getFirstname()); - userData.setLastname(user.getLastname()); - - userData.setAllowedOffices(offices); - - availableRoles.removeAll(userRoleData); - userData.setAvailableRoles(availableRoles); - userData.setSelectedRoles(userRoleData); - - return userData; - } - - protected static final class AppUserMapper implements - RowMapper { - - private final List offices; - - public AppUserMapper(final List offices) { - this.offices = offices; - } - - @Override - public AppUserData mapRow(final ResultSet rs, final int rowNum) - throws SQLException { - - Long id = rs.getLong("id"); - String username = rs.getString("username"); - String firstname = rs.getString("firstname"); - String lastname = rs.getString("lastname"); - String email = rs.getString("email"); - Long orgId = rs.getLong("orgId"); - Long officeId = rs.getLong("officeId"); - - String officeName = fromOfficeList(this.offices, officeId); - - AppUserData user = new AppUserData(id, username, email, orgId, - officeId, officeName); - user.setLastname(lastname); - user.setFirstname(firstname); - - return user; - } - - public String schema() { - return " u.id as id, u.username as username, u.firstname as firstname, u.lastname as lastname, u.email as email, u.org_id as orgId, u.office_id as officeId from admin_appuser u "; - } - - private String fromOfficeList(final List officeList, - final Long officeId) { - String match = ""; - for (OfficeData office : officeList) { - if (office.getId().equals(officeId)) { - match = office.getName(); - } - } - - return match; - } - } - - @Override - public Collection retrieveAllRoles() { - AppUser currentUser = extractAuthenticatedUser(); - - RoleMapper mapper = new RoleMapper(); - String sql = "select " + mapper.schema() + " where r.org_id = ?"; - - return this.jdbcTemplate.query(sql, mapper, new Object[] { currentUser - .getOrganisation().getId() }); - } - - @Override - public RoleData retrieveRole(Long roleId) { - - Role role = this.roleRepository.findOne(roleId); - - return role.toData(); - } - - protected static final class RoleMapper implements RowMapper { - - @Override - public RoleData mapRow(final ResultSet rs, final int rowNum) - throws SQLException { - - Long id = rs.getLong("id"); - Long orgId = rs.getLong("orgId"); - String name = rs.getString("name"); - String description = rs.getString("description"); - - return new RoleData(id, orgId, name, description); - } - - public String schema() { - return " r.id as id, r.org_id as orgId, r.name as name, r.description as description from admin_role r "; - } - } - - @Override - public Collection retrieveAllPermissionGroups() { - - Collection options = new ArrayList(); - - for (PermissionGroup group : PermissionGroup.values()) { - options.add(new EnumOptionReadModel(group.name(), Integer.valueOf( - group.ordinal()).longValue())); - } - return options; - } - - @Override - public Collection retrieveAllPermissions() { - - AppUser currentUser = extractAuthenticatedUser(); - - PermissionMapper mapper = new PermissionMapper(); - String sql = "select " + mapper.schema() + " where p.org_id = ?"; - - return this.jdbcTemplate.query(sql, mapper, new Object[] { currentUser - .getOrganisation().getId() }); - } - @Override public ClientData retrieveNewClientDetails() { @@ -954,28 +688,4 @@ public class ReadPlatformServiceImpl implements ReadPlatformService { return clientData; } - - protected static final class PermissionMapper implements - RowMapper { - - @Override - public PermissionData mapRow(final ResultSet rs, final int rowNum) - throws SQLException { - - Long id = rs.getLong("id"); - Long orgId = rs.getLong("orgId"); - String name = rs.getString("name"); - String description = rs.getString("description"); - String code = rs.getString("code"); - int groupType = rs.getInt("groupType"); - - return new PermissionData(id, orgId, name, description, code, - groupType); - } - - public String schema() { - return " p.id as id, p.org_id as orgId, p.default_name as name, p.default_description as description, p.code as code, p.group_enum as groupType from admin_permission p "; - } - } - } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/RoleValidator.java b/mifosng-provider/src/main/java/org/mifosng/platform/RoleValidator.java deleted file mode 100644 index 0b9d9cba9..000000000 --- a/mifosng-provider/src/main/java/org/mifosng/platform/RoleValidator.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.mifosng.platform; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.StringUtils; -import org.mifosng.data.ErrorResponse; -import org.mifosng.data.command.RoleCommand; -import org.mifosng.platform.exceptions.NewDataValidationException; -import org.springframework.util.ObjectUtils; - -public class RoleValidator { - - private final RoleCommand command; - - public RoleValidator(RoleCommand command) { - this.command = command; - } - - public void validateForCreate() { - List dataValidationErrors = new ArrayList(); - - validate(dataValidationErrors); - - if (!dataValidationErrors.isEmpty()) { - throw new NewDataValidationException(dataValidationErrors, "Data validation errors exist."); - } - } - - public void validateForUpdate() { - List dataValidationErrors = new ArrayList(); - - if (command.getId() == null || command.getId() < 1) { - ErrorResponse error = new ErrorResponse("validation.msg.role.id.not.provided", "id"); - dataValidationErrors.add(error); - } - - validate(dataValidationErrors); - - if (!dataValidationErrors.isEmpty()) { - throw new NewDataValidationException(dataValidationErrors, "Data validation errors exist."); - } - } - - private void validate(List dataValidationErrors) { - if (StringUtils.isBlank(command.getName())) { - ErrorResponse error = new ErrorResponse("validation.msg.role.name.cannot.be.blank", "name"); - dataValidationErrors.add(error); - } - - if (StringUtils.isBlank(command.getDescription())) { - ErrorResponse error = new ErrorResponse("validation.msg.role.description.cannot.be.blank", "description"); - dataValidationErrors.add(error); - } else { - if (command.getDescription().trim().length() > 500) { - ErrorResponse error = new ErrorResponse("validation.msg.role.description.exceeds.max.length", "description"); - dataValidationErrors.add(error); - } - } - - if (ObjectUtils.isEmpty(command.getPermissionIds())) { - ErrorResponse error = new ErrorResponse("validation.msg.role.permissions.cannot.be.empty", "selectedItems"); - dataValidationErrors.add(error); - } - } -} diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformService.java index 6e4730511..62fe8ebb5 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformService.java @@ -6,7 +6,6 @@ import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.NoteCommand; -import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand; @@ -15,10 +14,6 @@ import org.springframework.security.access.prepost.PreAuthorize; public interface WritePlatformService { - Long createRole(RoleCommand command); - - Long updateRole(RoleCommand command); - void updateUsernamePasswordOnFirstTimeLogin(UpdateUsernamePasswordCommand command); @PreAuthorize(value = "hasAnyRole('PORTFOLIO_MANAGEMENT_SUPER_USER_ROLE', 'CAN_ENROLL_NEW_CLIENT_ROLE')") diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformServiceJpaRepositoryImpl.java index 54e51dc1c..951872c64 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/WritePlatformServiceJpaRepositoryImpl.java @@ -2,13 +2,11 @@ package org.mifosng.platform; import static org.mifosng.platform.Specifications.loansThatMatch; import static org.mifosng.platform.Specifications.officesThatMatch; -import static org.mifosng.platform.Specifications.rolesThatMatch; import static org.mifosng.platform.Specifications.usersThatMatch; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.List; import org.apache.commons.lang.StringUtils; @@ -24,7 +22,6 @@ import org.mifosng.data.command.EnrollClientCommand; import org.mifosng.data.command.LoanStateTransitionCommand; import org.mifosng.data.command.LoanTransactionCommand; import org.mifosng.data.command.NoteCommand; -import org.mifosng.data.command.RoleCommand; import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand; @@ -63,11 +60,7 @@ import org.mifosng.platform.organisation.domain.Office; import org.mifosng.platform.organisation.domain.OfficeRepository; import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUserRepository; -import org.mifosng.platform.user.domain.Permission; -import org.mifosng.platform.user.domain.PermissionRepository; import org.mifosng.platform.user.domain.PlatformUserRepository; -import org.mifosng.platform.user.domain.Role; -import org.mifosng.platform.user.domain.RoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.core.Authentication; @@ -87,8 +80,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformServi private final LoanRepository loanRepository; private final LoanStatusRepository loanStatusRepository; private final CalculationPlatformService calculationPlatformService; - private final RoleRepository roleRepository; - private final PermissionRepository permissionRepository; private final NoteRepository noteRepository; private final LoanTransactionRepository loanTransactionRepository; @@ -103,9 +94,8 @@ public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformServi final LoanRepository loanRepository, final LoanTransactionRepository loanTransactionRepository, final LoanStatusRepository loanStatusRepository, - final CalculationPlatformService calculationPlatformService, - final RoleRepository roleRepository, - final PermissionRepository permissionRepository) { + final CalculationPlatformService calculationPlatformService + ) { this.officeRepository = officeRepository; this.platformUserRepository = platformUserRepository; this.platformPasswordEncoder = platformPasswordEncoder; @@ -116,69 +106,6 @@ public class WritePlatformServiceJpaRepositoryImpl implements WritePlatformServi this.loanTransactionRepository = loanTransactionRepository; this.loanStatusRepository = loanStatusRepository; this.calculationPlatformService = calculationPlatformService; - this.roleRepository = roleRepository; - this.permissionRepository = permissionRepository; - } - - @Transactional - @Override - public Long createRole(final RoleCommand command) { - - AppUser currentUser = extractAuthenticatedUser(); - - RoleValidator validator = new RoleValidator(command); - validator.validateForCreate(); - - List selectedPermissionIds = new ArrayList(); - for (String selectedId : command.getPermissionIds()) { - selectedPermissionIds.add(Long.valueOf(selectedId)); - } - - List selectedPermissions = new ArrayList(); - Collection allPermissions = this.permissionRepository - .findAll(); - for (Permission permission : allPermissions) { - if (selectedPermissionIds.contains(permission.getId())) { - selectedPermissions.add(permission); - } - } - - Role entity = new Role(currentUser.getOrganisation(), command.getName(), command.getDescription(), selectedPermissions); - - this.roleRepository.save(entity); - - return entity.getId(); - } - - @Transactional - @Override - public Long updateRole(RoleCommand command) { - - AppUser currentUser = extractAuthenticatedUser(); - - RoleValidator validator = new RoleValidator(command); - validator.validateForUpdate(); - - List selectedPermissionIds = new ArrayList(); - for (String selectedId : command.getPermissionIds()) { - selectedPermissionIds.add(Long.valueOf(selectedId)); - } - - List selectedPermissions = new ArrayList(); - Collection allPermissions = this.permissionRepository - .findAll(); - for (Permission permission : allPermissions) { - if (selectedPermissionIds.contains(permission.getId())) { - selectedPermissions.add(permission); - } - } - - Role role = this.roleRepository.findOne(rolesThatMatch(currentUser.getOrganisation(), command.getId())); - role.update(command.getName(), command.getDescription(), selectedPermissions); - - this.roleRepository.save(role); - - return role.getId(); } @Transactional diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/user/PermissionApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/PermissionApiResource.java new file mode 100644 index 000000000..4d29b9ad7 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/PermissionApiResource.java @@ -0,0 +1,53 @@ +package org.mifosng.platform.api.user; + +import java.util.Collection; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.mifosng.data.PermissionData; +import org.mifosng.data.PermissionList; +import org.mifosng.platform.user.domain.AppUser; +import org.mifosng.platform.user.domain.AppUserRepository; +import org.mifosng.platform.user.service.PermissionReadPlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +@Path("/v1/permissions") +@Component +@Scope("singleton") +public class PermissionApiResource { + + @Autowired + private PermissionReadPlatformService permissionReadPlatformService; + + @Autowired + private AppUserRepository appUserRepository; + + private void hardcodeUserIntoSecurityContext() { + AppUser currentUser = this.appUserRepository.findOne(Long.valueOf(1)); + + Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, currentUser, currentUser.getAuthorities()); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(auth); + } + + @GET + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({MediaType.APPLICATION_JSON}) + public Response retrieveAllPermissions() { + + hardcodeUserIntoSecurityContext(); + Collection permissions = this.permissionReadPlatformService.retrieveAllPermissions(); + return Response.ok().entity(new PermissionList(permissions)).build(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/user/RoleApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/RoleApiResource.java new file mode 100644 index 000000000..87a7b9056 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/RoleApiResource.java @@ -0,0 +1,121 @@ +package org.mifosng.platform.api.user; + +import java.util.Collection; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.mifosng.data.EntityIdentifier; +import org.mifosng.data.PermissionData; +import org.mifosng.data.RoleData; +import org.mifosng.data.RoleList; +import org.mifosng.data.command.RoleCommand; +import org.mifosng.platform.user.domain.AppUser; +import org.mifosng.platform.user.domain.AppUserRepository; +import org.mifosng.platform.user.service.PermissionReadPlatformService; +import org.mifosng.platform.user.service.RoleReadPlatformService; +import org.mifosng.platform.user.service.RoleWritePlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +@Path("/v1/roles") +@Component +@Scope("singleton") +public class RoleApiResource { + + @Autowired + private RoleReadPlatformService roleReadPlatformService; + + @Autowired + private PermissionReadPlatformService permissionReadPlatformService; + + @Autowired + private RoleWritePlatformService roleWritePlatformService; + + @Autowired + private AppUserRepository appUserRepository; + + private void hardcodeUserIntoSecurityContext() { + AppUser currentUser = this.appUserRepository.findOne(Long.valueOf(1)); + + Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, currentUser, currentUser.getAuthorities()); + SecurityContext context = SecurityContextHolder.getContext(); + context.setAuthentication(auth); + } + + @GET + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({MediaType.APPLICATION_JSON}) + public Response retrieveAllRoles() { + + hardcodeUserIntoSecurityContext(); + Collection roles = this.roleReadPlatformService.retrieveAllRoles(); + return Response.ok().entity(new RoleList(roles)).build(); + } + + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({MediaType.APPLICATION_JSON}) + public Response retrieveNewRoleDetails() { + + hardcodeUserIntoSecurityContext(); + + Collection allPermissions = this.permissionReadPlatformService.retrieveAllPermissions(); + + RoleData role = new RoleData(); + role.setAvailablePermissions(allPermissions); + + return Response.ok().entity(role).build(); + } + + @POST + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON}) + public Response createRole(final RoleCommand command) { + hardcodeUserIntoSecurityContext(); + Long roleId = this.roleWritePlatformService.createRole(command); + return Response.ok().entity(new EntityIdentifier(roleId)).build(); + } + + @GET + @Path("{roleId}") + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({MediaType.APPLICATION_JSON}) + public Response retrieveRole(@PathParam("roleId") final Long roleId) { + + hardcodeUserIntoSecurityContext(); + + RoleData role = this.roleReadPlatformService.retrieveRole(roleId); + + Collection availablePermissions = this.permissionReadPlatformService.retrieveAllPermissions(); + availablePermissions.removeAll(role.getSelectedPermissions()); + role.setAvailablePermissions(availablePermissions); + + return Response.ok().entity(role).build(); + } + + @PUT + @Path("{roleId}") + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON}) + public Response updateRole(@PathParam("roleId") final Long roleId, final RoleCommand command) { + hardcodeUserIntoSecurityContext(); + + command.setId(roleId); + this.roleWritePlatformService.updateRole(command); + return Response.ok().entity(new EntityIdentifier(roleId)).build(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserAccountApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserAccountApiResource.java index 3b776e866..14085ffe4 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserAccountApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserAccountApiResource.java @@ -12,9 +12,9 @@ import org.mifosng.data.AppUserData; import org.mifosng.data.EntityIdentifier; import org.mifosng.data.command.ChangePasswordCommand; import org.mifosng.data.command.UserCommand; -import org.mifosng.platform.ReadPlatformService; import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUserRepository; +import org.mifosng.platform.user.service.AppUserReadPlatformService; import org.mifosng.platform.user.service.AppUserWritePlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; @@ -30,7 +30,7 @@ import org.springframework.stereotype.Component; public class UserAccountApiResource { @Autowired - private ReadPlatformService readPlatformService; + private AppUserReadPlatformService appUserReadPlatformService; @Autowired private AppUserWritePlatformService appUserWritePlatformService; @@ -54,7 +54,7 @@ public class UserAccountApiResource { hardcodeUserIntoSecurityContext(); - AppUserData user = this.readPlatformService.retrieveCurrentUser(); + AppUserData user = this.appUserReadPlatformService.retrieveCurrentUser(); return Response.ok().entity(user).build(); } diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserApiResource.java index f4c9565ab..6d974e42b 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/user/UserApiResource.java @@ -1,6 +1,5 @@ package org.mifosng.platform.api.user; -import java.util.Arrays; import java.util.Collection; import javax.ws.rs.Consumes; @@ -11,27 +10,19 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; -import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.mifosng.data.AppUserData; import org.mifosng.data.EntityIdentifier; -import org.mifosng.data.ErrorResponse; -import org.mifosng.data.ErrorResponseList; import org.mifosng.data.UserList; import org.mifosng.data.command.UserCommand; -import org.mifosng.platform.ReadPlatformService; -import org.mifosng.platform.exceptions.ApplicationDomainRuleException; -import org.mifosng.platform.exceptions.NewDataValidationException; -import org.mifosng.platform.exceptions.UnAuthenticatedUserException; import org.mifosng.platform.user.domain.AppUser; import org.mifosng.platform.user.domain.AppUserRepository; +import org.mifosng.platform.user.service.AppUserReadPlatformService; import org.mifosng.platform.user.service.AppUserWritePlatformService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; @@ -44,7 +35,7 @@ import org.springframework.stereotype.Component; public class UserApiResource { @Autowired - private ReadPlatformService readPlatformService; + private AppUserReadPlatformService appUserReadPlatformService; @Autowired private AppUserWritePlatformService appUserWritePlatformService; @@ -67,7 +58,7 @@ public class UserApiResource { hardcodeUserIntoSecurityContext(); - Collection users = this.readPlatformService.retrieveAllUsers(); + Collection users = this.appUserReadPlatformService.retrieveAllUsers(); return Response.ok().entity(new UserList(users)).build(); } @@ -80,7 +71,7 @@ public class UserApiResource { hardcodeUserIntoSecurityContext(); - AppUserData user = this.readPlatformService.retrieveUser(userId); + AppUserData user = this.appUserReadPlatformService.retrieveUser(userId); return Response.ok().entity(user).build(); } @@ -92,7 +83,7 @@ public class UserApiResource { public Response newUserDetails() { hardcodeUserIntoSecurityContext(); - AppUserData newUser = this.readPlatformService.retrieveNewUserDetails(); + AppUserData newUser = this.appUserReadPlatformService.retrieveNewUserDetails(); return Response.ok().entity(newUser).build(); } @@ -113,21 +104,9 @@ public class UserApiResource { @Produces({ MediaType.APPLICATION_JSON}) public Response deleteUser(@PathParam("userId") final Long userId) { - try { - this.appUserWritePlatformService.deleteUser(userId); + this.appUserWritePlatformService.deleteUser(userId); - return Response.ok().build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } + return Response.ok().build(); } @PUT @@ -144,83 +123,4 @@ public class UserApiResource { return Response.ok().entity(new EntityIdentifier(userId)).build(); } - - @GET - @Path("user/current") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - @Produces({ MediaType.APPLICATION_JSON}) - public Response retrieveCurrentUser() { - - try { - hardcodeUserIntoSecurityContext(); - - AppUserData user = this.readPlatformService.retrieveCurrentUser(); - - return Response.ok().entity(user).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - -// @POST -// @Path("user/current") -// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -// @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -// public Response updateCurrentUser(UserCommand command) { -// -// try { -// hardcodeUserIntoSecurityContext(); -// -// Long userId = this.appUserWritePlatformService.updateCurrentUser(command); -// -// return Response.ok().entity(new EntityIdentifier(userId)).build(); -// } catch (UnAuthenticatedUserException e) { -// throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); -// } catch (AccessDeniedException e) { -// ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); -// ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); -// } catch (ApplicationDomainRuleException e) { -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); -// } catch (NewDataValidationException e) { -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); -// } catch (DataIntegrityViolationException e) { -// ErrorResponse errorResponse = new ErrorResponse("error.msg.username.already.exists.in.organisation", "username", command.getUsername()); -// ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); -// } -// } -// -// @POST -// @Path("user/current/password") -// @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -// @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) -// public Response updateCurrentUserPassword(ChangePasswordCommand command) { -// -// try { -// hardcodeUserIntoSecurityContext(); -// -// Long userId = this.appUserWritePlatformService.updateCurrentUserPassword(command); -// -// return Response.ok().entity(new EntityIdentifier(userId)).build(); -// } catch (UnAuthenticatedUserException e) { -// throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); -// } catch (AccessDeniedException e) { -// ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); -// ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); -// } catch (ApplicationDomainRuleException e) { -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); -// } catch (NewDataValidationException e) { -// throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); -// } -// } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/rest/UserAdmistrationResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/rest/UserAdmistrationResource.java deleted file mode 100644 index b4ff17faa..000000000 --- a/mifosng-provider/src/main/java/org/mifosng/platform/rest/UserAdmistrationResource.java +++ /dev/null @@ -1,222 +0,0 @@ -package org.mifosng.platform.rest; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -import org.mifosng.data.EntityIdentifier; -import org.mifosng.data.EnumOptionList; -import org.mifosng.data.EnumOptionReadModel; -import org.mifosng.data.ErrorResponse; -import org.mifosng.data.ErrorResponseList; -import org.mifosng.data.PermissionData; -import org.mifosng.data.PermissionList; -import org.mifosng.data.RoleData; -import org.mifosng.data.RoleList; -import org.mifosng.data.command.RoleCommand; -import org.mifosng.platform.ReadPlatformService; -import org.mifosng.platform.WritePlatformService; -import org.mifosng.platform.exceptions.ApplicationDomainRuleException; -import org.mifosng.platform.exceptions.NewDataValidationException; -import org.mifosng.platform.exceptions.UnAuthenticatedUserException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.stereotype.Component; - -@Path("/protected/admin") -@Component -@Scope("singleton") -public class UserAdmistrationResource { - - @Autowired - private ReadPlatformService readPlatformService; - - @Autowired - private WritePlatformService writePlatformService; - - @GET - @Path("role/all") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response retrieveAllRoles() { - - try { - Collection roles = this.readPlatformService.retrieveAllRoles(); - return Response.ok().entity(new RoleList(roles)).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - - @GET - @Path("role/new") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response retrieveNewRoleDetails() { - - try { - Collection allPermissions = this.readPlatformService.retrieveAllPermissions(); - - RoleData role = new RoleData(); - role.setAvailablePermissions(allPermissions); - - return Response.ok().entity(role).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - - @GET - @Path("role/{roleId}") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response retrieveRole(@PathParam("roleId") final Long roleId) { - - try { - RoleData role = this.readPlatformService.retrieveRole(roleId); - - Collection availablePermissions = this.readPlatformService.retrieveAllPermissions(); - - availablePermissions.removeAll(role.getSelectedPermissions()); - - role.setAvailablePermissions(availablePermissions); - - return Response.ok().entity(role).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - - - @POST - @Path("role/{roleId}") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - public Response updateRole(@PathParam("roleId") final Long roleId, final RoleCommand command) { - - try { - this.writePlatformService.updateRole(command); - return Response.ok().entity(new EntityIdentifier(roleId)).build(); - - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - - @POST - @Path("role/new") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - public Response createRole(final RoleCommand command) { - - try { - Long roleId = this.writePlatformService.createRole(command); - return Response.ok().entity(new EntityIdentifier(roleId)).build(); - - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - - @GET - @Path("permissiongroup/all") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - public Response retrievePermissionGroups() { - - try { - Collection options = this.readPlatformService - .retrieveAllPermissionGroups(); - - return Response - .ok() - .entity(new EnumOptionList(new ArrayList( - options))).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } - - @GET - @Path("permissions/all") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - public Response retrievePermissions() { - - try { - Collection permissions = this.readPlatformService.retrieveAllPermissions(); - - return Response.ok().entity(new PermissionList(permissions)).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); - } - } -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/AppUserReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/AppUserReadPlatformService.java new file mode 100644 index 000000000..d6a928578 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/AppUserReadPlatformService.java @@ -0,0 +1,16 @@ +package org.mifosng.platform.user.service; + +import java.util.Collection; + +import org.mifosng.data.AppUserData; + +public interface AppUserReadPlatformService { + + Collection retrieveAllUsers(); + + AppUserData retrieveNewUserDetails(); + + AppUserData retrieveUser(Long userId); + + AppUserData retrieveCurrentUser(); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/AppUserReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/AppUserReadPlatformServiceImpl.java new file mode 100644 index 000000000..af0935e4e --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/AppUserReadPlatformServiceImpl.java @@ -0,0 +1,206 @@ +package org.mifosng.platform.user.service; + +import static org.mifosng.platform.Specifications.usersThatMatch; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import javax.sql.DataSource; + +import org.mifosng.data.AppUserData; +import org.mifosng.data.OfficeData; +import org.mifosng.data.RoleData; +import org.mifosng.platform.exceptions.PlatformResourceNotFoundException; +import org.mifosng.platform.organisation.service.OfficeReadPlatformService; +import org.mifosng.platform.security.PlatformSecurityContext; +import org.mifosng.platform.user.domain.AppUser; +import org.mifosng.platform.user.domain.AppUserRepository; +import org.mifosng.platform.user.domain.Role; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; +import org.springframework.stereotype.Service; + +@Service +public class AppUserReadPlatformServiceImpl implements AppUserReadPlatformService { + + private final SimpleJdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final OfficeReadPlatformService officeReadPlatformService; + private final RoleReadPlatformService roleReadPlatformService; + private final AppUserRepository appUserRepository; + + @Autowired + public AppUserReadPlatformServiceImpl(final PlatformSecurityContext context, final DataSource dataSource, + final OfficeReadPlatformService officeReadPlatformService, final RoleReadPlatformService roleReadPlatformService, + final AppUserRepository appUserRepository) { + this.context = context; + this.officeReadPlatformService = officeReadPlatformService; + this.roleReadPlatformService = roleReadPlatformService; + this.appUserRepository = appUserRepository; + this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); + } + + @Override + public Collection retrieveAllUsers() { + + AppUser currentUser = context.authenticatedUser(); + + List offices = new ArrayList(officeReadPlatformService.retrieveAllOffices()); + String officeIdsList = generateOfficeIdInClause(offices); + + AppUserMapper mapper = new AppUserMapper(offices); + String sql = "select " + mapper.schema() + + " where u.org_id = ? and u.office_id in (" + officeIdsList + + ")"; + + return this.jdbcTemplate.query(sql, mapper, new Object[] { currentUser + .getOrganisation().getId() }); + } + + private String generateOfficeIdInClause(List offices) { + String officeIdsList = ""; + for (int i = 0; i < offices.size(); i++) { + Long id = offices.get(i).getId(); + if (i == 0) { + officeIdsList = id.toString(); + } else { + officeIdsList += "," + id.toString(); + } + } + return officeIdsList; + } + + @Override + public AppUserData retrieveNewUserDetails() { + + List offices = new ArrayList(officeReadPlatformService.retrieveAllOffices()); + + List availableRoles = new ArrayList(this.roleReadPlatformService.retrieveAllRoles()); + + AppUserData userData = new AppUserData(); + userData.setAllowedOffices(offices); + userData.setAvailableRoles(availableRoles); + + return userData; + } + + @Override + public AppUserData retrieveUser(Long userId) { + + AppUser currentUser = context.authenticatedUser(); + + List offices = new ArrayList(officeReadPlatformService.retrieveAllOffices()); + + List availableRoles = new ArrayList(this.roleReadPlatformService.retrieveAllRoles()); + + AppUser user = this.appUserRepository.findOne(usersThatMatch(currentUser.getOrganisation(), userId)); + if (user == null) { + throw new PlatformResourceNotFoundException("error.msg.user.id.invalid", "User with identifier {0} does not exist.", userId); + } + + List userRoleData = new ArrayList(); + Set userRoles = user.getRoles(); + for (Role role : userRoles) { + userRoleData.add(role.toData()); + } + + AppUserData userData = new AppUserData(user.getId(), + user.getUsername(), user.getEmail(), user.getOrganisation() + .getId(), user.getOffice().getId(), user.getOffice() + .getName()); + userData.setFirstname(user.getFirstname()); + userData.setLastname(user.getLastname()); + + userData.setAllowedOffices(offices); + + availableRoles.removeAll(userRoleData); + userData.setAvailableRoles(availableRoles); + userData.setSelectedRoles(userRoleData); + + return userData; + } + + @Override + public AppUserData retrieveCurrentUser() { + AppUser currentUser = context.authenticatedUser(); + + List offices = new ArrayList(officeReadPlatformService.retrieveAllOffices()); + + List availableRoles = new ArrayList(this.roleReadPlatformService.retrieveAllRoles()); + + AppUser user = this.appUserRepository.findOne(usersThatMatch(currentUser.getOrganisation(), currentUser.getId())); + + List userRoleData = new ArrayList(); + Set userRoles = user.getRoles(); + for (Role role : userRoles) { + userRoleData.add(role.toData()); + } + + AppUserData userData = new AppUserData(user.getId(), + user.getUsername(), user.getEmail(), user.getOrganisation() + .getId(), user.getOffice().getId(), user.getOffice() + .getName()); + userData.setFirstname(user.getFirstname()); + userData.setLastname(user.getLastname()); + + userData.setAllowedOffices(offices); + + availableRoles.removeAll(userRoleData); + userData.setAvailableRoles(availableRoles); + userData.setSelectedRoles(userRoleData); + + return userData; + } + + private static final class AppUserMapper implements RowMapper { + + private final List offices; + + public AppUserMapper(final List offices) { + this.offices = offices; + } + + @Override + public AppUserData mapRow(final ResultSet rs, final int rowNum) + throws SQLException { + + Long id = rs.getLong("id"); + String username = rs.getString("username"); + String firstname = rs.getString("firstname"); + String lastname = rs.getString("lastname"); + String email = rs.getString("email"); + Long orgId = rs.getLong("orgId"); + Long officeId = rs.getLong("officeId"); + + String officeName = fromOfficeList(this.offices, officeId); + + AppUserData user = new AppUserData(id, username, email, orgId, + officeId, officeName); + user.setLastname(lastname); + user.setFirstname(firstname); + + return user; + } + + public String schema() { + return " u.id as id, u.username as username, u.firstname as firstname, u.lastname as lastname, u.email as email, u.org_id as orgId, u.office_id as officeId from admin_appuser u "; + } + + private String fromOfficeList(final List officeList, + final Long officeId) { + String match = ""; + for (OfficeData office : officeList) { + if (office.getId().equals(officeId)) { + match = office.getName(); + } + } + + return match; + } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/PermissionReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/PermissionReadPlatformService.java new file mode 100644 index 000000000..dfe4fd536 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/PermissionReadPlatformService.java @@ -0,0 +1,10 @@ +package org.mifosng.platform.user.service; + +import java.util.Collection; + +import org.mifosng.data.PermissionData; + +public interface PermissionReadPlatformService { + + Collection retrieveAllPermissions(); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/PermissionReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/PermissionReadPlatformServiceImpl.java new file mode 100644 index 000000000..e66177a94 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/PermissionReadPlatformServiceImpl.java @@ -0,0 +1,60 @@ +package org.mifosng.platform.user.service; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; + +import javax.sql.DataSource; + +import org.mifosng.data.PermissionData; +import org.mifosng.platform.security.PlatformSecurityContext; +import org.mifosng.platform.user.domain.AppUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; +import org.springframework.stereotype.Service; + +@Service +public class PermissionReadPlatformServiceImpl implements PermissionReadPlatformService { + + private final SimpleJdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + + @Autowired + public PermissionReadPlatformServiceImpl(final PlatformSecurityContext context, final DataSource dataSource) { + this.context = context; + this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); + } + + @Override + public Collection retrieveAllPermissions() { + + AppUser currentUser = context.authenticatedUser(); + + PermissionMapper mapper = new PermissionMapper(); + String sql = "select " + mapper.schema() + " where p.org_id = ?"; + + return this.jdbcTemplate.query(sql, mapper, new Object[] { currentUser + .getOrganisation().getId() }); + } + + private static final class PermissionMapper implements RowMapper { + + @Override + public PermissionData mapRow(final ResultSet rs, final int rowNum) throws SQLException { + + Long id = rs.getLong("id"); + Long orgId = rs.getLong("orgId"); + String name = rs.getString("name"); + String description = rs.getString("description"); + String code = rs.getString("code"); + int groupType = rs.getInt("groupType"); + + return new PermissionData(id, orgId, name, description, code, groupType); + } + + public String schema() { + return " p.id as id, p.org_id as orgId, p.default_name as name, p.default_description as description, p.code as code, p.group_enum as groupType from admin_permission p "; + } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleCommandValidator.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleCommandValidator.java new file mode 100644 index 000000000..95d7aef27 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleCommandValidator.java @@ -0,0 +1,66 @@ +package org.mifosng.platform.user.service; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.mifosng.data.ApiParameterError; +import org.mifosng.data.command.RoleCommand; +import org.mifosng.platform.exceptions.PlatformApiDataValidationException; +import org.springframework.util.ObjectUtils; + +public class RoleCommandValidator { + + private final RoleCommand command; + + public RoleCommandValidator(RoleCommand command) { + this.command = command; + } + + public void validateForCreate() { + List dataValidationErrors = new ArrayList(); + + validate(dataValidationErrors); + + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); + } + } + + public void validateForUpdate() { + List dataValidationErrors = new ArrayList(); + + if (command.getId() == null || command.getId() < 1) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.role.id.not.provided", "The parameter id cannot be blank.", "id"); + dataValidationErrors.add(error); + } + + validate(dataValidationErrors); + + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); + } + } + + private void validate(List dataValidationErrors) { + if (StringUtils.isBlank(command.getName())) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.role.name.cannot.be.blank", "The parameter name cannot be blank.", "name"); + dataValidationErrors.add(error); + } + + if (StringUtils.isBlank(command.getDescription())) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.role.description.cannot.be.blank", "The parameter description cannot be blank.", "description"); + dataValidationErrors.add(error); + } else { + if (command.getDescription().trim().length() > 500) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.role.description.exceeds.max.length", "The parameter description has data that exceeds its max allowed length of {0}.", "description", 500); + dataValidationErrors.add(error); + } + } + + if (ObjectUtils.isEmpty(command.getSelectedItems())) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.role.permissions.cannot.be.empty", "The parameter selectedItems cannot be blank. You must select at least one permission.", "selectedItems"); + dataValidationErrors.add(error); + } + } +} diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleReadPlatformService.java new file mode 100644 index 000000000..f748612b9 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleReadPlatformService.java @@ -0,0 +1,12 @@ +package org.mifosng.platform.user.service; + +import java.util.Collection; + +import org.mifosng.data.RoleData; + +public interface RoleReadPlatformService { + + Collection retrieveAllRoles(); + + RoleData retrieveRole(Long roleId); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleReadPlatformServiceImpl.java new file mode 100644 index 000000000..be2d11b2b --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleReadPlatformServiceImpl.java @@ -0,0 +1,71 @@ +package org.mifosng.platform.user.service; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; + +import javax.sql.DataSource; + +import org.mifosng.data.RoleData; +import org.mifosng.platform.security.PlatformSecurityContext; +import org.mifosng.platform.user.domain.AppUser; +import org.mifosng.platform.user.domain.Role; +import org.mifosng.platform.user.domain.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; +import org.springframework.stereotype.Service; + +@Service +public class RoleReadPlatformServiceImpl implements RoleReadPlatformService { + + private final SimpleJdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final RoleRepository roleRepository; + + @Autowired + public RoleReadPlatformServiceImpl(final PlatformSecurityContext context, final DataSource dataSource, final RoleRepository roleRepository) { + this.context = context; + this.roleRepository = roleRepository; + this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); + } + + @Override + public Collection retrieveAllRoles() { + AppUser currentUser = context.authenticatedUser(); + + RoleMapper mapper = new RoleMapper(); + String sql = "select " + mapper.schema() + " where r.org_id = ?"; + + return this.jdbcTemplate.query(sql, mapper, new Object[] { currentUser + .getOrganisation().getId() }); + } + + // FIXME - does it make sense to use JDBC over repository for this? + @Override + public RoleData retrieveRole(Long roleId) { + + Role role = this.roleRepository.findOne(roleId); + + return role.toData(); + } + + protected static final class RoleMapper implements RowMapper { + + @Override + public RoleData mapRow(final ResultSet rs, final int rowNum) + throws SQLException { + + Long id = rs.getLong("id"); + Long orgId = rs.getLong("orgId"); + String name = rs.getString("name"); + String description = rs.getString("description"); + + return new RoleData(id, orgId, name, description); + } + + public String schema() { + return " r.id as id, r.org_id as orgId, r.name as name, r.description as description from admin_role r "; + } + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleWritePlatformService.java new file mode 100644 index 000000000..f203b50cd --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleWritePlatformService.java @@ -0,0 +1,10 @@ +package org.mifosng.platform.user.service; + +import org.mifosng.data.command.RoleCommand; + +public interface RoleWritePlatformService { + + Long createRole(RoleCommand command); + + Long updateRole(RoleCommand command); +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java new file mode 100644 index 000000000..293289fcd --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/user/service/RoleWritePlatformServiceJpaRepositoryImpl.java @@ -0,0 +1,94 @@ +package org.mifosng.platform.user.service; + +import static org.mifosng.platform.Specifications.rolesThatMatch; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.mifosng.data.command.RoleCommand; +import org.mifosng.platform.security.PlatformSecurityContext; +import org.mifosng.platform.user.domain.AppUser; +import org.mifosng.platform.user.domain.Permission; +import org.mifosng.platform.user.domain.PermissionRepository; +import org.mifosng.platform.user.domain.Role; +import org.mifosng.platform.user.domain.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatformService { + + private final PlatformSecurityContext context; + private final RoleRepository roleRepository; + + private final PermissionRepository permissionRepository; + + @Autowired + public RoleWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final RoleRepository roleRepository, final PermissionRepository permissionRepository) { + this.context = context; + this.roleRepository = roleRepository; + this.permissionRepository = permissionRepository; + } + + @Transactional + @Override + public Long createRole(final RoleCommand command) { + + AppUser currentUser = context.authenticatedUser(); + + RoleCommandValidator validator = new RoleCommandValidator(command); + validator.validateForCreate(); + + List selectedPermissionIds = new ArrayList(); + for (String selectedId : command.getSelectedItems()) { + selectedPermissionIds.add(Long.valueOf(selectedId)); + } + + List selectedPermissions = new ArrayList(); + Collection allPermissions = this.permissionRepository.findAll(); + for (Permission permission : allPermissions) { + if (selectedPermissionIds.contains(permission.getId())) { + selectedPermissions.add(permission); + } + } + + Role entity = new Role(currentUser.getOrganisation(), command.getName(), command.getDescription(), selectedPermissions); + + this.roleRepository.save(entity); + + return entity.getId(); + } + + @Transactional + @Override + public Long updateRole(RoleCommand command) { + + AppUser currentUser = context.authenticatedUser(); + + RoleCommandValidator validator = new RoleCommandValidator(command); + validator.validateForUpdate(); + + List selectedPermissionIds = new ArrayList(); + for (String selectedId : command.getSelectedItems()) { + selectedPermissionIds.add(Long.valueOf(selectedId)); + } + + List selectedPermissions = new ArrayList(); + Collection allPermissions = this.permissionRepository + .findAll(); + for (Permission permission : allPermissions) { + if (selectedPermissionIds.contains(permission.getId())) { + selectedPermissions.add(permission); + } + } + + Role role = this.roleRepository.findOne(rolesThatMatch(currentUser.getOrganisation(), command.getId())); + role.update(command.getName(), command.getDescription(), selectedPermissions); + + this.roleRepository.save(role); + + return role.getId(); + } +} \ No newline at end of file