MIFOSX-1875

This commit is contained in:
Vishwas Babu A J
2015-03-28 00:07:20 +05:30
parent 3416a8dc8e
commit 064fb4845c
18 changed files with 306 additions and 234 deletions
+18 -17
View File
@@ -2033,11 +2033,11 @@
<td></td> <td></td>
</tr> </tr>
<tr> <tr>
<td><a href="#password_validation_policy">Password Validation Policy</a></td> <td><a href="#password_preferences">Password preferences</a></td>
<td>paswordValidationPolicy</td> <td>passwordpreferences</td>
<td><a href=""></a></td> <td><a href=""></a></td>
<td><a href="#password_validation_policy_list">List validation Policy</a></td> <td><a href="#password_preferences_list">Get Password Preferences</a></td>
<td><a href="#password_validation_policy_update">Activate policy</a></td> <td><a href="#password_preferences_update">Update Password Preferences</a></td>
<td></td> <td></td>
</tr> </tr>
</table> </table>
@@ -30862,17 +30862,17 @@ Request Body:
</div> </div>
<!-- start of password validation policy api docs --> <!-- start of password validation policy api docs -->
<a id="password_validation_policy" name="passwordValidationPolicy" class="old-syle-anchor">&nbsp;</a> <a id="password_preferences" name="passwordpreferences" class="old-syle-anchor">&nbsp;</a>
<div class="method-section"> <div class="method-section">
<div class="method-description"> <div class="method-description">
<h3>Password validation policy</h3> <h3>Password preferences</h3>
<p>An API capability to support management of application password validation policy for user administration.</p> <p>This API enables management of password policy for user administration.</p>
<p>There is no Mifos X functionality for creating or validation policy. The validation policies come pre-installed.</p> <p>There is no Mifos X functionality for creating a validation policy. The validation policies come pre-installed.</p>
<p>Validation policies are not updated, except in the case of enabling them</p> <p>Validation policies may be updated</p>
</div> </div>
</div> </div>
<a id="password_validation_policy_list" name="passwordValidationPolicy_list" <a id="password_preferences_list" name="passwordValidationPolicy_list"
class="old-syle-anchor">&nbsp;</a> class="old-syle-anchor">&nbsp;</a>
<div class="method-section"> <div class="method-section">
<div class="method-description"> <div class="method-description">
@@ -30883,11 +30883,11 @@ Request Body:
</dd> </dd>
</dl> </dl>
<p>Example Requests:</p> <p>Example Requests:</p>
<div class=apiClick>passwordValidationPolicy</div><br><br> <div class=apiClick>passwordpreferences</div><br><br>
</div> </div>
<div class="method-example"> <div class="method-example">
<code class="method-declaration"> <code class="method-declaration">
GET https://DomainName/api/v1/passwordValidationPolicy GET https://DomainName/api/v1/passwordpreferences
</code> </code>
<code class="method-response"> <code class="method-response">
[ [
@@ -30906,21 +30906,22 @@ Request Body:
</div> </div>
</div> </div>
<a id="password_validation_policy_update" name="passwordValidationPolicy_update" class="old-syle-anchor">&nbsp;</a> <a id="password_preferences_update" name="passwordValidationPolicy_update" class="old-syle-anchor">&nbsp;</a>
<div class="method-section"> <div class="method-section">
<div class="method-description"> <div class="method-description">
<h4>Enable Password validation policy</h4> <h4>Update password preferences</h4>
</div> </div>
<div class="method-example"> <div class="method-example">
<code class="method-declaration"> <code class="method-declaration">
PUT https://DomainName/api/v1/passwordValidationPolicy/{validationPolicyId} PUT https://DomainName/api/v1/passwordpreferences/
</code> </code>
<code class="method-request"> <code class="method-request">
PUT passwordValidationPolicy PUT passwordpreferences
Content-Type: application/json Content-Type: application/json
Request Body: Request Body:
{ {
"validationPolicyId" : 1,
"locale" : "en"
} }
</code> </code>
</div> </div>
@@ -8,6 +8,7 @@ package org.mifosplatform.commands.domain;
import org.mifosplatform.infrastructure.accountnumberformat.service.AccountNumberFormatConstants; import org.mifosplatform.infrastructure.accountnumberformat.service.AccountNumberFormatConstants;
import org.mifosplatform.portfolio.loanaccount.rescheduleloan.RescheduleLoansApiConstants; import org.mifosplatform.portfolio.loanaccount.rescheduleloan.RescheduleLoansApiConstants;
import org.mifosplatform.portfolio.savings.DepositsApiConstants; import org.mifosplatform.portfolio.savings.DepositsApiConstants;
import org.mifosplatform.useradministration.api.PasswordPreferencesApiConstants;
public class CommandWrapper { public class CommandWrapper {
@@ -200,7 +201,8 @@ public class CommandWrapper {
public boolean isUpdate() { public boolean isUpdate() {
// permissions resource has special update which involves no resource. // permissions resource has special update which involves no resource.
return isPermissionResource() && isUpdateOperation() || isCurrencyResource() && isUpdateOperation() || isCacheResource() return isPermissionResource() && isUpdateOperation() || isCurrencyResource() && isUpdateOperation() || isCacheResource()
&& isUpdateOperation() || isWorkingDaysResource() && isUpdateOperation() || isUpdateOperation() && this.entityId != null; && isUpdateOperation() || isWorkingDaysResource() && isUpdateOperation() || isPasswordPreferencesResource()
&& isUpdateOperation() || isUpdateOperation() && this.entityId != null;
} }
public boolean isUpdateOperation() { public boolean isUpdateOperation() {
@@ -1022,8 +1024,8 @@ public class CommandWrapper {
return this.entityName.equalsIgnoreCase("WORKINGDAYS"); return this.entityName.equalsIgnoreCase("WORKINGDAYS");
} }
public boolean isPasswordValidationPolicyResource() { public boolean isPasswordPreferencesResource() {
return this.entityName.equalsIgnoreCase("PASSWORD_VALIDATION_POLICY"); return this.entityName.equalsIgnoreCase(PasswordPreferencesApiConstants.ENTITY_NAME);
} }
} }
@@ -8,6 +8,7 @@ package org.mifosplatform.commands.service;
import org.mifosplatform.commands.domain.CommandWrapper; import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.infrastructure.accountnumberformat.service.AccountNumberFormatConstants; import org.mifosplatform.infrastructure.accountnumberformat.service.AccountNumberFormatConstants;
import org.mifosplatform.portfolio.savings.DepositsApiConstants; import org.mifosplatform.portfolio.savings.DepositsApiConstants;
import org.mifosplatform.useradministration.api.PasswordPreferencesApiConstants;
public class CommandWrapperBuilder { public class CommandWrapperBuilder {
@@ -2361,11 +2362,10 @@ public class CommandWrapperBuilder {
return this; return this;
} }
public CommandWrapperBuilder activatePasswordValidationPolicy(final Long validationPolicyId) { public CommandWrapperBuilder updatePasswordPreferences() {
this.actionName = "UPDATE"; this.actionName = "UPDATE";
this.entityName = "PASSWORD_VALIDATION_POLICY"; this.entityName = PasswordPreferencesApiConstants.ENTITY_NAME;
this.entityId = validationPolicyId; this.href = "/" + PasswordPreferencesApiConstants.RESOURCE_NAME;
this.href = "/passwordValidationPolicy/" + validationPolicyId;
return this; return this;
} }
@@ -929,9 +929,9 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
} }
} else if (wrapper.isPasswordValidationPolicyResource()) { } else if (wrapper.isPasswordPreferencesResource()) {
if (wrapper.isUpdate()) { if (wrapper.isUpdate()) {
handler = this.applicationContext.getBean("updatePasswordValidationPolicyCommandHandler", NewCommandSourceHandler.class); handler = this.applicationContext.getBean("updatePasswordPreferencesCommandHandler", NewCommandSourceHandler.class);
} else { } else {
throw new UnsupportedCommandException(wrapper.commandName()); throw new UnsupportedCommandException(wrapper.commandName());
@@ -5,8 +5,10 @@
*/ */
package org.mifosplatform.organisation.workingdays.data; package org.mifosplatform.organisation.workingdays.data;
import com.google.gson.JsonElement; import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken; import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.data.ApiParameterError; import org.mifosplatform.infrastructure.core.data.ApiParameterError;
@@ -18,10 +20,8 @@ import org.mifosplatform.organisation.workingdays.api.WorkingDaysApiConstants;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.lang.reflect.Type; import com.google.gson.JsonElement;
import java.util.ArrayList; import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
@Component @Component
public class WorkingDayValidator { public class WorkingDayValidator {
@@ -33,8 +33,7 @@ public class WorkingDayValidator {
this.fromApiJsonHelper = fromApiJsonHelper; this.fromApiJsonHelper = fromApiJsonHelper;
} }
public void validateForUpdate(final String json) {
public void validateForUpdate(final String json){
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType(); final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
@@ -44,23 +43,19 @@ public class WorkingDayValidator {
final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource( WorkingDaysApiConstants.WORKING_DAYS_RESOURCE_NAME); .resource(WorkingDaysApiConstants.WORKING_DAYS_RESOURCE_NAME);
final String recurrence = this.fromApiJsonHelper.extractStringNamed(WorkingDaysApiConstants.recurrence, element); final String recurrence = this.fromApiJsonHelper.extractStringNamed(WorkingDaysApiConstants.recurrence, element);
baseDataValidator.reset().parameter(WorkingDaysApiConstants.recurrence).value(recurrence).notNull(); baseDataValidator.reset().parameter(WorkingDaysApiConstants.recurrence).value(recurrence).notNull();
final Integer repaymentRescheduleType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("repaymentRescheduleType", element); final Integer repaymentRescheduleType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed("repaymentRescheduleType", element);
baseDataValidator.reset().parameter("repaymentRescheduleType").value(repaymentRescheduleType).ignoreIfNull().inMinMaxRange(1,4); baseDataValidator.reset().parameter("repaymentRescheduleType").value(repaymentRescheduleType).ignoreIfNull().inMinMaxRange(1, 4);
throwExceptionIfValidationWarningsExist(dataValidationErrors); throwExceptionIfValidationWarningsExist(dataValidationErrors);
} }
private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) { private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) {
if (!dataValidationErrors.isEmpty()) { if (!dataValidationErrors.isEmpty()) {
// //
@@ -0,0 +1,26 @@
package org.mifosplatform.useradministration.api;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class PasswordPreferencesApiConstants {
public static final String RESOURCE_NAME = "passwordpreferences";
public static final String ENTITY_NAME = "PASSWORD_PREFERENCES";
// response parameters
public static final String DESCRIPTION = "description";
public static final String ACTIVE = "active";
public static final String ID_PARAM_NAME = "id";
// request parameters
public static final String VALIDATION_POLICY_ID = "validationPolicyId";
public static final Set<String> REQUEST_DATA_PARAMETERS = new HashSet<>(Arrays.asList(VALIDATION_POLICY_ID));
public static final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList(ID_PARAM_NAME, ACTIVE, DESCRIPTION));
}
@@ -5,6 +5,17 @@
*/ */
package org.mifosplatform.useradministration.api; package org.mifosplatform.useradministration.api;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper; import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder; import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService; import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
@@ -14,37 +25,15 @@ import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSeriali
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.useradministration.data.PasswordValidationPolicyData; import org.mifosplatform.useradministration.data.PasswordValidationPolicyData;
import org.mifosplatform.useradministration.data.RoleData;
import org.mifosplatform.useradministration.data.RolePermissionsData;
import org.mifosplatform.useradministration.service.PasswordValidationPolicyReadPlatformService; import org.mifosplatform.useradministration.service.PasswordValidationPolicyReadPlatformService;
import org.mifosplatform.useradministration.service.PermissionReadPlatformService;
import org.mifosplatform.useradministration.service.RoleReadPlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.ws.rs.*; @Path("/" + PasswordPreferencesApiConstants.RESOURCE_NAME)
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@Path("/passwordValidationPolicy")
@Component @Component
@Scope("singleton") @Scope("singleton")
public class PasswordValidationPolicyApiResource { public class PasswordPreferencesApiResource {
/**
* The set of parameters that are supported in response for {@link org.mifosplatform.useradministration.data.RoleData}
*/
private final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "description",
"active"));
private final String resourceNameForPermissions = "Password_Validation_Policy";
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final PasswordValidationPolicyReadPlatformService passwordValidationPolicyReadPlatformService; private final PasswordValidationPolicyReadPlatformService passwordValidationPolicyReadPlatformService;
@@ -53,10 +42,11 @@ public class PasswordValidationPolicyApiResource {
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
@Autowired @Autowired
public PasswordValidationPolicyApiResource(final PlatformSecurityContext context, final PasswordValidationPolicyReadPlatformService readPlatformService, public PasswordPreferencesApiResource(final PlatformSecurityContext context,
final DefaultToApiJsonSerializer<PasswordValidationPolicyData> toApiJsonSerializer, final PasswordValidationPolicyReadPlatformService readPlatformService,
final ApiRequestParameterHelper apiRequestParameterHelper, final DefaultToApiJsonSerializer<PasswordValidationPolicyData> toApiJsonSerializer,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { final ApiRequestParameterHelper apiRequestParameterHelper,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
this.context = context; this.context = context;
this.passwordValidationPolicyReadPlatformService = readPlatformService; this.passwordValidationPolicyReadPlatformService = readPlatformService;
this.toApiJsonSerializer = toApiJsonSerializer; this.toApiJsonSerializer = toApiJsonSerializer;
@@ -67,24 +57,24 @@ public class PasswordValidationPolicyApiResource {
@GET @GET
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String retrieveAllPolicy(@Context final UriInfo uriInfo) { public String retrieve(@Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); this.context.authenticatedUser().validateHasReadPermission(PasswordPreferencesApiConstants.ENTITY_NAME);
final Collection<PasswordValidationPolicyData> validationPolicies = this.passwordValidationPolicyReadPlatformService.retrieveAll(); final PasswordValidationPolicyData passwordValidationPolicyData = this.passwordValidationPolicyReadPlatformService
.retrieveActiveValidationPolicy();
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize( settings,validationPolicies ,this.RESPONSE_DATA_PARAMETERS); return this.toApiJsonSerializer.serialize(settings, passwordValidationPolicyData,
PasswordPreferencesApiConstants.RESPONSE_DATA_PARAMETERS);
} }
@PUT @PUT
@Path("{validationPolicyId}")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON })
public String activate(@PathParam("validationPolicyId") final Long validationPolicyId, final String apiRequestBodyAsJson) { public String update(final String apiRequestBodyAsJson) {
final CommandWrapper commandRequest = new CommandWrapperBuilder() // final CommandWrapper commandRequest = new CommandWrapperBuilder() //
.activatePasswordValidationPolicy(validationPolicyId) //
.withJson(apiRequestBodyAsJson) // .withJson(apiRequestBodyAsJson) //
.build(); .build();
@@ -93,4 +83,17 @@ public class PasswordValidationPolicyApiResource {
return this.toApiJsonSerializer.serialize(result); return this.toApiJsonSerializer.serialize(result);
} }
@GET
@Path("/template")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String template(@Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(PasswordPreferencesApiConstants.ENTITY_NAME);
final Collection<PasswordValidationPolicyData> validationPolicies = this.passwordValidationPolicyReadPlatformService.retrieveAll();
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, validationPolicies, PasswordPreferencesApiConstants.RESPONSE_DATA_PARAMETERS);
}
} }
@@ -0,0 +1,58 @@
package org.mifosplatform.useradministration.data;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.mifosplatform.infrastructure.core.exception.InvalidJsonException;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper;
import org.mifosplatform.useradministration.api.PasswordPreferencesApiConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
@Component
public class PasswordPreferencesDataValidator {
private final FromJsonHelper fromApiJsonHelper;
@Autowired
public PasswordPreferencesDataValidator(FromJsonHelper fromApiJsonHelper) {
this.fromApiJsonHelper = fromApiJsonHelper;
}
public void validateForUpdate(final String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, PasswordPreferencesApiConstants.REQUEST_DATA_PARAMETERS);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(PasswordPreferencesApiConstants.RESOURCE_NAME);
final Long repaymentRescheduleType = this.fromApiJsonHelper.extractLongNamed(PasswordPreferencesApiConstants.VALIDATION_POLICY_ID,
element);
baseDataValidator.reset().parameter(PasswordPreferencesApiConstants.VALIDATION_POLICY_ID).value(repaymentRescheduleType).notNull()
.integerGreaterThanZero();
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) {
if (!dataValidationErrors.isEmpty()) {
//
throw new PlatformApiDataValidationException(dataValidationErrors);
}
}
}
@@ -5,22 +5,21 @@
*/ */
package org.mifosplatform.useradministration.domain; package org.mifosplatform.useradministration.domain;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import java.util.LinkedHashMap;
import org.slf4j.Logger; import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.domain.AbstractPersistable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Table; import javax.persistence.Table;
import java.util.LinkedHashMap;
import java.util.Map; import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity @Entity
@Table(name = "m_password_validation_policy") @Table(name = "m_password_validation_policy")
public class PasswordValidationPolicy extends AbstractPersistable<Long> { public class PasswordValidationPolicy extends AbstractPersistable<Long> {
private final static Logger logger = LoggerFactory.getLogger(PasswordValidationPolicy.class); // private final static Logger logger =
// LoggerFactory.getLogger(PasswordValidationPolicy.class);
@Column(name = "regex", nullable = false) @Column(name = "regex", nullable = false)
private String regex; private String regex;
@@ -29,19 +28,18 @@ public class PasswordValidationPolicy extends AbstractPersistable<Long> {
private String description; private String description;
@Column(name = "active", nullable = false) @Column(name = "active", nullable = false)
private boolean active ; private boolean active;
public PasswordValidationPolicy(final String regex, final String description, final boolean active ) { public PasswordValidationPolicy(final String regex, final String description, final boolean active) {
this.description = description; this.description = description;
this.regex = regex; this.regex = regex;
this.active = active; this.active = active;
} }
public PasswordValidationPolicy(){ public PasswordValidationPolicy() {
this.active = false; this.active = false;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
@@ -54,12 +52,12 @@ public class PasswordValidationPolicy extends AbstractPersistable<Long> {
return this.active; return this.active;
} }
public Map<String, Object> active(){ public Map<String, Object> activate() {
final Map<String, Object> actualChanges = new LinkedHashMap<>(1); final Map<String, Object> actualChanges = new LinkedHashMap<>(1);
final String active = "active"; final String active = "active";
if(!this.active){ if (!this.active) {
actualChanges.put(active, true); actualChanges.put(active, true);
this.active = true; this.active = true;
@@ -68,14 +66,12 @@ public class PasswordValidationPolicy extends AbstractPersistable<Long> {
return actualChanges; return actualChanges;
} }
public boolean isActive(){ public boolean isActive() {
return this.active; return this.active;
} }
public void deActive(){ public void deActivate() {
this.active = false; this.active = false;
} }
} }
@@ -13,6 +13,10 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN
public class PasswordValidationPolicyNotFoundException extends AbstractPlatformResourceNotFoundException { public class PasswordValidationPolicyNotFoundException extends AbstractPlatformResourceNotFoundException {
public PasswordValidationPolicyNotFoundException(final Long id) { public PasswordValidationPolicyNotFoundException(final Long id) {
super("error.msg.validation.policy.id.invalid", "Password Validation Policy with identifier " + id + " does not exist", id); super("error.msg.password.validation.policy.id.invalid", "Password Validation Policy with identifier " + id + " does not exist", id);
}
public PasswordValidationPolicyNotFoundException() {
super("error.msg.password.validation.policy.not.found", "An active password validation policy was not found");
} }
} }
@@ -8,26 +8,24 @@ package org.mifosplatform.useradministration.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler; import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.useradministration.service.PasswordValidationPolicyWritePlatformService; import org.mifosplatform.useradministration.service.PasswordPreferencesWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@Service @Service
public class UpdatePasswordValidationPolicyCommandHandler implements NewCommandSourceHandler { public class UpdatePasswordPreferencesCommandHandler implements NewCommandSourceHandler {
private final PasswordValidationPolicyWritePlatformService writePlatformService; private final PasswordPreferencesWritePlatformService writePlatformService;
@Autowired @Autowired
public UpdatePasswordValidationPolicyCommandHandler(final PasswordValidationPolicyWritePlatformService writePlatformService) { public UpdatePasswordPreferencesCommandHandler(final PasswordPreferencesWritePlatformService writePlatformService) {
this.writePlatformService = writePlatformService; this.writePlatformService = writePlatformService;
} }
@Transactional @Transactional
@Override @Override
public CommandProcessingResult processCommand(final JsonCommand command) { public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updatePreferences(command);
final Long validationPolicyId = command.entityId();
return this.writePlatformService.activate(validationPolicyId, command);
} }
} }
@@ -8,9 +8,8 @@ package org.mifosplatform.useradministration.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface PasswordValidationPolicyWritePlatformService { public interface PasswordPreferencesWritePlatformService {
CommandProcessingResult updatePreferences(JsonCommand command);
CommandProcessingResult activate(Long validationPolicyId, JsonCommand command); }
}
@@ -0,0 +1,84 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.useradministration.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.useradministration.api.PasswordPreferencesApiConstants;
import org.mifosplatform.useradministration.data.PasswordPreferencesDataValidator;
import org.mifosplatform.useradministration.domain.PasswordValidationPolicy;
import org.mifosplatform.useradministration.domain.PasswordValidationPolicyRepository;
import org.mifosplatform.useradministration.exception.PasswordValidationPolicyNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class PasswordPreferencesWritePlatformServiceJpaRepositoryImpl implements PasswordPreferencesWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(PasswordPreferencesWritePlatformServiceJpaRepositoryImpl.class);
private final PasswordValidationPolicyRepository validationRepository;
private final PasswordPreferencesDataValidator dataValidator;
@Autowired
public PasswordPreferencesWritePlatformServiceJpaRepositoryImpl(final PasswordValidationPolicyRepository validationPolicyRepository,
final PasswordPreferencesDataValidator dataValidator) {
this.validationRepository = validationPolicyRepository;
this.dataValidator = dataValidator;
}
@Transactional
@Override
public CommandProcessingResult updatePreferences(final JsonCommand command) {
this.dataValidator.validateForUpdate(command.json());
Long validationPolicyId = command.longValueOfParameterNamed(PasswordPreferencesApiConstants.VALIDATION_POLICY_ID);
try {
final List<PasswordValidationPolicy> validationPolicies = this.validationRepository.findAll();
Map<String, Object> changes = new HashMap<>(1);
boolean found = false;
for (PasswordValidationPolicy policy : validationPolicies) {
if (policy.getId().equals(validationPolicyId)) {
found = true;
if (!policy.isActive()) {
changes = policy.activate();
}
} else if (policy.isActive() && !policy.getId().equals(validationPolicyId)) {
policy.deActivate();
}
}
if (!found) { throw new PasswordValidationPolicyNotFoundException(validationPolicyId); }
if (!changes.isEmpty()) {
this.validationRepository.save(validationPolicies);
this.validationRepository.flush();
}
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) //
.with(changes) //
.build();
} catch (final DataIntegrityViolationException dve) {
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.password.validation.policy.unknown.data.integrity.issue",
"Unknown data integrity issue with resource.");
}
}
}
@@ -5,12 +5,13 @@
*/ */
package org.mifosplatform.useradministration.service; package org.mifosplatform.useradministration.service;
import org.mifosplatform.useradministration.data.PasswordValidationPolicyData;
import java.util.Collection; import java.util.Collection;
import org.mifosplatform.useradministration.data.PasswordValidationPolicyData;
public interface PasswordValidationPolicyReadPlatformService { public interface PasswordValidationPolicyReadPlatformService {
Collection<PasswordValidationPolicyData> retrieveAll(); Collection<PasswordValidationPolicyData> retrieveAll();
PasswordValidationPolicyData retrieveActiveValidationPolicy();
} }
@@ -5,18 +5,20 @@
*/ */
package org.mifosplatform.useradministration.service; package org.mifosplatform.useradministration.service;
import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.useradministration.data.PasswordValidationPolicyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Collection; import java.util.Collection;
import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.useradministration.data.PasswordValidationPolicyData;
import org.mifosplatform.useradministration.exception.PasswordValidationPolicyNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
@Service @Service
public class PasswordValidationPolicyReadPlatformServiceImpl implements PasswordValidationPolicyReadPlatformService { public class PasswordValidationPolicyReadPlatformServiceImpl implements PasswordValidationPolicyReadPlatformService {
@@ -36,7 +38,15 @@ public class PasswordValidationPolicyReadPlatformServiceImpl implements Password
return this.jdbcTemplate.query(sql, this.passwordValidationPolicyMapper); return this.jdbcTemplate.query(sql, this.passwordValidationPolicyMapper);
} }
@Override
public PasswordValidationPolicyData retrieveActiveValidationPolicy() {
try {
final String sql = "select " + this.passwordValidationPolicyMapper.schema() + " where pvp.active = true";
return this.jdbcTemplate.queryForObject(sql, this.passwordValidationPolicyMapper);
} catch (final EmptyResultDataAccessException e) {
throw new PasswordValidationPolicyNotFoundException();
}
}
protected static final class PasswordValidationPolicyMapper implements RowMapper<PasswordValidationPolicyData> { protected static final class PasswordValidationPolicyMapper implements RowMapper<PasswordValidationPolicyData> {
@@ -55,5 +65,4 @@ public class PasswordValidationPolicyReadPlatformServiceImpl implements Password
} }
} }
} }
@@ -1,109 +0,0 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.useradministration.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.useradministration.domain.PasswordValidationPolicy;
import org.mifosplatform.useradministration.domain.PasswordValidationPolicyRepository;
import org.mifosplatform.useradministration.domain.PermissionRepository;
import org.mifosplatform.useradministration.exception.PasswordValidationPolicyNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Service
public class PasswordValidationPolicyWritePlatformServiceJpaRepositoryImpl implements PasswordValidationPolicyWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(PasswordValidationPolicyWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final PasswordValidationPolicyRepository validationRepository;
@Autowired
public PasswordValidationPolicyWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final PasswordValidationPolicyRepository validationPolicyRepository,
final PermissionRepository permissionRepository) {
this.context = context;
this.validationRepository = validationPolicyRepository;
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue
* is.
*/
private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) {
logAsErrorUnexpectedDataIntegrityException(dve);
throw new PlatformDataIntegrityException("error.msg.role.unknown.data.integrity.issue",
"Unknown data integrity issue with resource.");
}
private void logAsErrorUnexpectedDataIntegrityException(final DataIntegrityViolationException dve) {
logger.error(dve.getMessage(), dve);
}
@Transactional
@Override
public CommandProcessingResult activate(final Long validationPolicyId, final JsonCommand command) {
try {
this.context.authenticatedUser();
final List<PasswordValidationPolicy> validationPolicies = this.validationRepository.findAll();
Map<String, Object> changes = new LinkedHashMap<>(1);
boolean found = false;
for(PasswordValidationPolicy policy:validationPolicies){
if(policy.getId().equals(validationPolicyId)){
found = true;
if(!policy.isActive()){
changes = policy.active();
}
}
else if(policy.isActive() && !policy.getId().equals(validationPolicyId)){
policy.deActive();
}
}
if(!found) { throw new PasswordValidationPolicyNotFoundException(validationPolicyId); }
if (!changes.isEmpty()) {
this.validationRepository.save(validationPolicies);
this.validationRepository.flush();
}
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) //
.withEntityId(validationPolicyId) //
.with(changes) //
.build();
} catch (final DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve);
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) //
.build();
}
}
}
@@ -1,7 +0,0 @@
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
VALUE ("authorisation","READ_PASSWORD_VALIDATION_POLICY","PASSWORD_VALIDATION_POLICY","READ",0);
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
VALUE ("authorisation","UPDATE_PASSWORD_VALIDATION_POLICY","PASSWORD_VALIDATION_POLICY","UPDATE",0);
@@ -5,7 +5,7 @@ CREATE TABLE IF NOT EXISTS `m_password_validation_policy` (
`description` text NOT NULL, `description` text NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '0', `active` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `m_password_validation_policy` ( INSERT INTO `m_password_validation_policy` (
@@ -28,4 +28,16 @@ VALUES (
NULL , '^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s).{6,50}$', 'Password must be at least 6 characters, no more than 50 characters long, must include at least one upper case letter, one lower case letter, one numeric digit and no space', '0' NULL , '^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s).{6,50}$', 'Password must be at least 6 characters, no more than 50 characters long, must include at least one upper case letter, one lower case letter, one numeric digit and no space', '0'
); );
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
VALUE ("authorisation","READ_PASSWORD_PREFERENCES","PASSWORD_PREFERENCES","READ",0);
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
VALUE ("authorisation","UPDATE_PASSWORD_PREFERENCES","PASSWORD_PREFERENCES","UPDATE",0);
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
VALUE ("authorisation","UPDATE_PASSWORD_PREFERENCES_CHECKER","PASSWORD_PREFERENCES","UPDATE_CHECKER",0);