MIFOSX-751 updates

This commit is contained in:
Vishwas Babu A J
2014-02-10 09:07:10 +05:30
parent fe510e8e1a
commit ac932974f3
21 changed files with 237 additions and 346 deletions
@@ -5,7 +5,7 @@ ADD INDEX ( `last_time_password_updated` ) ;
UPDATE `m_appuser` SET `last_time_password_updated` = NOW() WHERE `m_appuser`.`last_time_password_updated` ='0000-00-00';
CREATE TABLE IF NOT EXISTS `m_appuser_previews_passwords` (
CREATE TABLE IF NOT EXISTS `m_appuser_previous_password` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL,
`password` varchar(255) NOT NULL,
@@ -13,5 +13,5 @@ CREATE TABLE IF NOT EXISTS `m_appuser_previews_passwords` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE m_appuser_previews_passwords
ALTER TABLE m_appuser_previous_password
ADD FOREIGN KEY (user_id) REFERENCES m_appuser(id);
@@ -4,19 +4,13 @@ import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Cieyou on 1/16/14.
*/
public class GlobalConfigurationApiConstant {
public static final String enabled = "enabled";
public static final String value = "value";
public static final String id ="id";
public static final String ENABLED = "enabled";
public static final String VALUE = "value";
public static final String ID = "id";
public static final String CONFIGURATION_RESOURCE_NAME = "globalConfiguration";
public static final Set<String> UPDATE_CONFIGURATION_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(enabled,
value));
public static final Set<String> UPDATE_CONFIGURATION_DATA_PARAMETERS = new HashSet<String>(Arrays.asList(ENABLED, VALUE));
}
@@ -6,14 +6,16 @@
package org.mifosplatform.infrastructure.configuration.api;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
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.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
@@ -22,7 +24,6 @@ import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationData;
import org.mifosplatform.infrastructure.configuration.service.ConfigurationReadPlatformService;
import org.mifosplatform.infrastructure.core.api.ApiParameterHelper;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
@@ -73,13 +74,11 @@ public class GlobalConfigurationApiResource {
return this.toApiJsonSerializer.serialize(settings, configurationData, this.RESPONSE_DATA_PARAMETERS);
}
@PUT
@Path("{configId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String updateConfiguration(@PathParam("configId") final Long configId,final String apiRequestBodyAsJson) {
public String updateConfiguration(@PathParam("configId") final Long configId, final String apiRequestBodyAsJson) {
final CommandWrapper commandRequest = new CommandWrapperBuilder() //
.updateGlobalConfiguration(configId) //
@@ -89,5 +88,5 @@ public class GlobalConfigurationApiResource {
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
}
}
}
@@ -1,30 +1,28 @@
package org.mifosplatform.infrastructure.configuration.data;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
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.serialization.FromJsonHelper;
import org.springframework.beans.factory.annotation.Autowired;
import static org.mifosplatform.infrastructure.configuration.api.GlobalConfigurationApiConstant.CONFIGURATION_RESOURCE_NAME;
import static org.mifosplatform.infrastructure.configuration.api.GlobalConfigurationApiConstant.ENABLED;
import static org.mifosplatform.infrastructure.configuration.api.GlobalConfigurationApiConstant.UPDATE_CONFIGURATION_DATA_PARAMETERS;
import static org.mifosplatform.infrastructure.configuration.api.GlobalConfigurationApiConstant.VALUE;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.mifosplatform.infrastructure.configuration.api.GlobalConfigurationApiConstant.*;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by Cieyou on 1/16/14.
*/
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
@Component
public class GlobalConfigurationDataValidator {
@@ -40,27 +38,22 @@ public class GlobalConfigurationDataValidator {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,UPDATE_CONFIGURATION_DATA_PARAMETERS);
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, UPDATE_CONFIGURATION_DATA_PARAMETERS);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(CONFIGURATION_RESOURCE_NAME);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final JsonObject jsonElement = element.getAsJsonObject();
if(this.fromApiJsonHelper.parameterExists(enabled, element))
{
final boolean enabledBool = this.fromApiJsonHelper.extractBooleanNamed(enabled,element);
baseDataValidator.reset().parameter(enabled).value(enabledBool).validateForBooleanValue();
if (this.fromApiJsonHelper.parameterExists(ENABLED, element)) {
final boolean enabledBool = this.fromApiJsonHelper.extractBooleanNamed(ENABLED, element);
baseDataValidator.reset().parameter(ENABLED).value(enabledBool).validateForBooleanValue();
}
if(this.fromApiJsonHelper.parameterExists(value, element))
{
final Long valueStr = this.fromApiJsonHelper.extractLongNamed(value,element);
baseDataValidator.reset().parameter(enabled).value(valueStr).zeroOrPositiveAmount();
if (this.fromApiJsonHelper.parameterExists(VALUE, element)) {
final Long valueStr = this.fromApiJsonHelper.extractLongNamed(VALUE, element);
baseDataValidator.reset().parameter(ENABLED).value(valueStr).zeroOrPositiveAmount();
}
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
@@ -9,7 +9,6 @@ import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.cache.domain.CacheType;
import org.mifosplatform.infrastructure.cache.domain.PlatformCache;
import org.mifosplatform.infrastructure.cache.domain.PlatformCacheRepository;
import org.mifosplatform.infrastructure.configuration.exception.GlobalConfigurationPropertyNotFoundException;
import org.mifosplatform.useradministration.domain.Permission;
import org.mifosplatform.useradministration.domain.PermissionRepository;
import org.mifosplatform.useradministration.exception.PermissionNotFoundException;
@@ -21,12 +20,12 @@ import org.springframework.transaction.annotation.Transactional;
public class ConfigurationDomainServiceJpa implements ConfigurationDomainService {
private final PermissionRepository permissionRepository;
private final GlobalConfigurationRepository globalConfigurationRepository;
private final GlobalConfigurationRepositoryWrapper globalConfigurationRepository;
private final PlatformCacheRepository cacheTypeRepository;
@Autowired
public ConfigurationDomainServiceJpa(final PermissionRepository permissionRepository,
final GlobalConfigurationRepository globalConfigurationRepository, final PlatformCacheRepository cacheTypeRepository) {
final GlobalConfigurationRepositoryWrapper globalConfigurationRepository, final PlatformCacheRepository cacheTypeRepository) {
this.permissionRepository = permissionRepository;
this.globalConfigurationRepository = globalConfigurationRepository;
this.cacheTypeRepository = cacheTypeRepository;
@@ -40,62 +39,58 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
if (thisTask == null) { throw new PermissionNotFoundException(taskPermissionCode); }
final String makerCheckerConfigurationProperty = "maker-checker";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByName(makerCheckerConfigurationProperty);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(makerCheckerConfigurationProperty); }
final GlobalConfigurationProperty property = this.globalConfigurationRepository
.findOneByNameWithNotFoundDetection(makerCheckerConfigurationProperty);
return thisTask.hasMakerCheckerEnabled() && property.isEnabled();
}
@Override
public boolean isAmazonS3Enabled() {
return this.globalConfigurationRepository.findOneByName("amazon-S3").isEnabled();
return this.globalConfigurationRepository.findOneByNameWithNotFoundDetection("amazon-S3").isEnabled();
}
@Override
public boolean isRescheduleFutureRepaymentsEnabled() {
final String rescheduleRepaymentsConfigurationProperty = "reschedule-future-repayments";
final GlobalConfigurationProperty property = this.globalConfigurationRepository
.findOneByName(rescheduleRepaymentsConfigurationProperty);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(rescheduleRepaymentsConfigurationProperty); }
.findOneByNameWithNotFoundDetection(rescheduleRepaymentsConfigurationProperty);
return property.isEnabled();
}
/*
* (non-Javadoc)
*
*
* @see org.mifosplatform.infrastructure.configuration.domain.
* ConfigurationDomainService#isHolidaysEnabled()
*/
@Override
public boolean isRescheduleRepaymentsOnHolidaysEnabled() {
final String holidaysConfigurationProperty = "reschedule-repayments-on-holidays";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByName(holidaysConfigurationProperty);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(holidaysConfigurationProperty); }
final GlobalConfigurationProperty property = this.globalConfigurationRepository
.findOneByNameWithNotFoundDetection(holidaysConfigurationProperty);
return property.isEnabled();
}
@Override
public boolean allowTransactionsOnHolidayEnabled() {
final String allowTransactionsOnHolidayProperty = "allow-transactions-on-holiday";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByName(allowTransactionsOnHolidayProperty);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(allowTransactionsOnHolidayProperty); }
final GlobalConfigurationProperty property = this.globalConfigurationRepository
.findOneByNameWithNotFoundDetection(allowTransactionsOnHolidayProperty);
return property.isEnabled();
}
@Override
public boolean allowTransactionsOnNonWorkingDayEnabled() {
final String propertyName = "allow-transactions-on-non_workingday";
final GlobalConfigurationProperty property = this.globalConfigurationRepository
.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByNameWithNotFoundDetection(propertyName);
return property.isEnabled();
}
@Override
public boolean isConstraintApproachEnabledForDatatables() {
final String propertyName = "constraint_approach_for_datatables";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByNameWithNotFoundDetection(propertyName);
return property.isEnabled();
}
@@ -109,35 +104,27 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
public void updateCache(final CacheType cacheType) {
final PlatformCache cache = this.cacheTypeRepository.findOne(Long.valueOf(1));
cache.update(cacheType);
this.cacheTypeRepository.save(cache);
}
@Override
public Long retrievePenaltyWaitPeriod() {
final String propertyName ="penalty-wait-period";
final GlobalConfigurationProperty property= this.globalConfigurationRepository.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
final String propertyName = "penalty-wait-period";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByNameWithNotFoundDetection(propertyName);
return property.getValue();
}
@Override
public boolean isPasswordForcedResetEnable(){
final String propertyName ="force-password-reset-days";
final GlobalConfigurationProperty property= this.globalConfigurationRepository.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
public boolean isPasswordForcedResetEnable() {
final String propertyName = "force-password-reset-days";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByNameWithNotFoundDetection(propertyName);
return property.isEnabled();
}
@Override
public Long retrievePasswordLiveTime(){
final String propertyName ="force-password-reset-days";
final GlobalConfigurationProperty property= this.globalConfigurationRepository.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
public Long retrievePasswordLiveTime() {
final String propertyName = "force-password-reset-days";
final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByNameWithNotFoundDetection(propertyName);
return property.getValue();
}
}
@@ -5,18 +5,15 @@
*/
package org.mifosplatform.infrastructure.configuration.domain;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.springframework.data.jpa.domain.AbstractPersistable;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "c_configuration")
@@ -28,7 +25,7 @@ public class GlobalConfigurationProperty extends AbstractPersistable<Long> {
@Column(name = "enabled", nullable = false)
private boolean enabled;
@Column(name= "value", nullable= true)
@Column(name = "value", nullable = true)
private Long value;
protected GlobalConfigurationProperty() {
@@ -37,7 +34,7 @@ public class GlobalConfigurationProperty extends AbstractPersistable<Long> {
this.value = null;
}
public GlobalConfigurationProperty(final String name, final boolean enabled,final Long value) {
public GlobalConfigurationProperty(final String name, final boolean enabled, final Long value) {
this.name = name;
this.enabled = enabled;
this.value = value;
@@ -57,19 +54,13 @@ public class GlobalConfigurationProperty extends AbstractPersistable<Long> {
return updated;
}
public Map<String, Object> update(final JsonCommand command)
{
public Map<String, Object> update(final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(7);
// final String localeAsInput = command.locale();
// final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
// final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("c");
final String enabledParamName = "enabled";
if (command.isChangeInBooleanParameterNamed(enabledParamName, this.enabled)) {
final Boolean newValue = command.booleanPrimitiveValueOfParameterNamed (enabledParamName);
final Boolean newValue = command.booleanPrimitiveValueOfParameterNamed(enabledParamName);
actualChanges.put(enabledParamName, newValue);
this.enabled = newValue;
}
@@ -0,0 +1,52 @@
/**
* 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.infrastructure.configuration.domain;
import org.mifosplatform.infrastructure.configuration.exception.GlobalConfigurationPropertyNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* Wrapper for {@link GlobalConfigurationRepository} that adds NULL checking and
* Error handling capabilities
* </p>
*/
@Service
public class GlobalConfigurationRepositoryWrapper {
private final GlobalConfigurationRepository repository;
@Autowired
public GlobalConfigurationRepositoryWrapper(final GlobalConfigurationRepository repository) {
this.repository = repository;
}
public GlobalConfigurationProperty findOneByNameWithNotFoundDetection(final String propertyName) {
final GlobalConfigurationProperty property = this.repository.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
return property;
}
public GlobalConfigurationProperty findOneWithNotFoundDetection(final Long configId) {
final GlobalConfigurationProperty property = this.repository.findOne(configId);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(configId); }
return property;
}
public void save(final GlobalConfigurationProperty globalConfigurationProperty) {
this.repository.save(globalConfigurationProperty);
}
public void saveAndFlush(final GlobalConfigurationProperty globalConfigurationProperty) {
this.repository.saveAndFlush(globalConfigurationProperty);
}
public void delete(final GlobalConfigurationProperty globalConfigurationProperty) {
this.repository.delete(globalConfigurationProperty);
}
}
@@ -27,6 +27,6 @@ public class UpdateGlobalConfigurationCommandHandler implements NewCommandSource
@Override
public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.update(command.entityId(),command);
return this.writePlatformService.update(command.entityId(), command);
}
}
@@ -10,7 +10,5 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface GlobalConfigurationWritePlatformService {
//CommandProcessingResult update(JsonCommand command);
CommandProcessingResult update(Long configId, JsonCommand command);
}
@@ -5,14 +5,11 @@
*/
package org.mifosplatform.infrastructure.configuration.service;
import java.util.LinkedHashMap;
import java.util.Map;
import org.mifosplatform.infrastructure.configuration.command.UpdateGlobalConfigurationCommand;
import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationDataValidator;
import org.mifosplatform.infrastructure.configuration.domain.GlobalConfigurationProperty;
import org.mifosplatform.infrastructure.configuration.domain.GlobalConfigurationRepository;
import org.mifosplatform.infrastructure.configuration.exception.GlobalConfigurationPropertyNotFoundException;
import org.mifosplatform.infrastructure.configuration.serialization.GlobalConfigurationCommandFromApiJsonDeserializer;
import org.mifosplatform.infrastructure.configuration.domain.GlobalConfigurationRepositoryWrapper;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
@@ -21,10 +18,9 @@ import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext
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;
import org.mifosplatform.infrastructure.configuration.data.GlobalConfigurationDataValidator;
import org.springframework.dao.DataIntegrityViolationException;
@Service
public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements GlobalConfigurationWritePlatformService {
@@ -32,67 +28,28 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements
private final static Logger logger = LoggerFactory.getLogger(GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final GlobalConfigurationRepository repository;
private final GlobalConfigurationCommandFromApiJsonDeserializer fromApiJsonDeserializer;
private final GlobalConfigurationDataValidator globalConfigurationDataValidator ;
private final GlobalConfigurationRepositoryWrapper repository;
private final GlobalConfigurationDataValidator globalConfigurationDataValidator;
@Autowired
public GlobalConfigurationWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context,
final GlobalConfigurationRepository codeRepository,
final GlobalConfigurationCommandFromApiJsonDeserializer fromApiJsonDeserializer,
final GlobalConfigurationDataValidator dataValidator) {
final GlobalConfigurationRepositoryWrapper codeRepository, final GlobalConfigurationDataValidator dataValidator) {
this.context = context;
this.repository = codeRepository;
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.globalConfigurationDataValidator = dataValidator;
}
// @Transactional
// @Override
// public CommandProcessingResult update(final JsonCommand command) {
//
// this.context.authenticatedUser();
//
// final UpdateGlobalConfigurationCommand configurationCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json());
//
// final Map<String, Boolean> params = configurationCommand.getGlobalConfiguration();
//
// final Map<String, Object> changes = new LinkedHashMap<String, Object>(params.size());
// final Map<String, Boolean> propertiesMap = new LinkedHashMap<String, Boolean>(1);
// for (final String propertyName : params.keySet()) {
// final GlobalConfigurationProperty property = retrieveBy(propertyName);
//
// final Boolean value = params.get(propertyName);
// final boolean updated = property.updateTo(value);
//
// if (updated) {
// propertiesMap.put(propertyName, value);
// this.repository.save(property);
// }
// }
//
// if (!propertiesMap.isEmpty()) {
// changes.put("globalConfiguration", propertiesMap);
// }
//
// return new CommandProcessingResultBuilder().withCommandId(command.commandId()).with(changes).build();
// }
@Transactional
@Override
public CommandProcessingResult update(final Long configId , final JsonCommand command) {
public CommandProcessingResult update(final Long configId, final JsonCommand command) {
this.context.authenticatedUser();
try {
this.globalConfigurationDataValidator.validateForUpdate(command);
final GlobalConfigurationProperty configItemForUpdate = this.repository.findOne(configId);
if (configItemForUpdate == null) {
throw new GlobalConfigurationPropertyNotFoundException(configId);
}
final GlobalConfigurationProperty configItemForUpdate = this.repository.findOneWithNotFoundDetection(configId);
final Map<String, Object> changes = configItemForUpdate.update(command);
@@ -103,23 +60,17 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements
return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(configId).with(changes).build();
} catch (final DataIntegrityViolationException dve) {
handleDataIntegrityIssues(command, dve);
handleDataIntegrityIssues(dve);
return CommandProcessingResult.empty();
}
}
private GlobalConfigurationProperty retrieveBy(final String propertyName) {
final GlobalConfigurationProperty property = this.repository.findOneByName(propertyName);
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(propertyName); }
return property;
}
/*
* Guaranteed to throw an exception no matter what the data integrity issue
* is.
*/
private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) {
private void handleDataIntegrityIssues(final DataIntegrityViolationException dve) {
final Throwable realCause = dve.getMostSpecificCause();
logger.error(dve.getMessage(), dve);
@@ -18,13 +18,10 @@ import javax.ws.rs.core.MediaType;
import org.mifosplatform.infrastructure.core.data.EnumOptionData;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.data.AuthenticatedUserData;
import org.mifosplatform.infrastructure.security.exception.ResetPasswordException;
import org.mifosplatform.infrastructure.security.service.SpringSecurityPlatformSecurityContext;
import org.mifosplatform.useradministration.data.RoleData;
import org.mifosplatform.useradministration.domain.AppUser;
import org.mifosplatform.useradministration.domain.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
@@ -45,12 +42,11 @@ public class AuthenticationApiResource {
private final ToApiJsonSerializer<AuthenticatedUserData> apiJsonSerializerService;
private final SpringSecurityPlatformSecurityContext springSecurityPlatformSecurityContext;
private final static Logger logger = LoggerFactory.getLogger(AuthenticationApiResource.class);
@Autowired
public AuthenticationApiResource(
@Qualifier("customAuthenticationProvider") final DaoAuthenticationProvider customAuthenticationProvider,
final ToApiJsonSerializer<AuthenticatedUserData> apiJsonSerializerService,final SpringSecurityPlatformSecurityContext springSecurityPlatformSecurityContext) {
final ToApiJsonSerializer<AuthenticatedUserData> apiJsonSerializerService,
final SpringSecurityPlatformSecurityContext springSecurityPlatformSecurityContext) {
this.customAuthenticationProvider = customAuthenticationProvider;
this.apiJsonSerializerService = apiJsonSerializerService;
this.springSecurityPlatformSecurityContext = springSecurityPlatformSecurityContext;
@@ -80,8 +76,6 @@ public class AuthenticationApiResource {
roles.add(role.toData());
}
final Long officeId = principal.getOffice().getId();
final String officeName = principal.getOffice().getName();
@@ -90,17 +84,14 @@ public class AuthenticationApiResource {
final EnumOptionData organisationalRole = principal.organisationalRoleData();
if(this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)){
//throw new ResetPasswordException(principal.getId());
authenticatedUserData = new AuthenticatedUserData(username,principal.getId(), new String(base64EncodedAuthenticationKey));
}
else{
if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) {
authenticatedUserData = new AuthenticatedUserData(username, principal.getId(), new String(base64EncodedAuthenticationKey));
} else {
authenticatedUserData = new AuthenticatedUserData(username, officeId, officeName, staffId, staffDisplayName,
organisationalRole, roles, permissions, principal.getId(), new String(base64EncodedAuthenticationKey));
}
}
return this.apiJsonSerializerService.serialize(authenticatedUserData);
@@ -5,12 +5,10 @@
*/
package org.mifosplatform.infrastructure.security.exception;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformServiceUnavailableException;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
import java.util.ArrayList;
import java.util.List;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
/**
* A {@link RuntimeException} that is thrown in the case where a user does not
@@ -18,27 +16,20 @@ import java.util.List;
*/
public class ResetPasswordException extends PlatformApiDataValidationException {
public ResetPasswordException(final Long userId) {
super(
"error.msg.password.outdated",
"The password of the user with id "+userId+" has expired, please reset it it",
new ArrayList<ApiParameterError>(){
{
add (ApiParameterError.parameterError(
"error.msg.password.outdated",
"The password of the user with id "+userId+" has expired, please reset it it",
"userId",userId)
);
super("error.msg.password.outdated", "The password of the user with id " + userId + " has expired, please reset it",
new ArrayList<ApiParameterError>() {
{
add(ApiParameterError.parameterError("error.msg.password.outdated", "The password of the user with id " + userId
+ " has expired, please reset it", "userId", userId));
}
}
}
);
}
}
@@ -6,7 +6,6 @@
package org.mifosplatform.infrastructure.security.service;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.useradministration.domain.AppUser;
public interface PlatformSecurityContext {
@@ -5,29 +5,24 @@
*/
package org.mifosplatform.infrastructure.security.service;
import com.sun.jersey.api.spring.Autowire;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.infrastructure.configuration.domain.ConfigurationDomainService;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.service.DateUtils;
import org.mifosplatform.infrastructure.security.exception.NoAuthorizationException;
import org.mifosplatform.infrastructure.security.exception.ResetPasswordException;
import org.mifosplatform.useradministration.domain.AppUser;
import org.mifosplatform.useradministration.exception.UnAuthenticatedUserException;
import org.mifosplatform.infrastructure.configuration.domain.ConfigurationDomainServiceJpa;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import sun.print.resources.serviceui_zh_TW;
import java.lang.reflect.Array;
import java.util.*;
/**
* Wrapper around spring security's {@link SecurityContext} for extracted the
@@ -37,18 +32,17 @@ import java.util.*;
@Service
public class SpringSecurityPlatformSecurityContext implements PlatformSecurityContext {
private final ConfigurationDomainService configurationDomainService ;
private final ConfigurationDomainService configurationDomainService;
private final static Logger logger = LoggerFactory.getLogger(SpringSecurityPlatformSecurityContext.class);
public static final List<CommandWrapper> EXEMPT_FROM_PASSWORD_RESET_CHECK = new ArrayList<CommandWrapper>() {
public static final List<CommandWrapper> EXEMPT_FROM_PASSWORD_RESET_CHECK = new ArrayList<CommandWrapper>(){
{
add(new CommandWrapperBuilder().updateUser(null).build());
}
};
@Autowired
SpringSecurityPlatformSecurityContext(final ConfigurationDomainService configurationDomainService){
SpringSecurityPlatformSecurityContext(final ConfigurationDomainService configurationDomainService) {
this.configurationDomainService = configurationDomainService;
}
@@ -66,14 +60,13 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
if (currentUser == null) { throw new UnAuthenticatedUserException(); }
if(this.doesPasswordHasToBeRenewed(currentUser)) { throw new ResetPasswordException(currentUser.getId());}
if (this.doesPasswordHasToBeRenewed(currentUser)) { throw new ResetPasswordException(currentUser.getId()); }
return currentUser;
}
public AppUser authenticatedUser(CommandWrapper commandWrapper)
{
@Override
public AppUser authenticatedUser(CommandWrapper commandWrapper) {
AppUser currentUser = null;
final SecurityContext context = SecurityContextHolder.getContext();
@@ -84,16 +77,15 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
}
}
if (currentUser == null) { throw new UnAuthenticatedUserException(); }
if(this.shouldCheckForPasswordForceReset(commandWrapper) && this.doesPasswordHasToBeRenewed(currentUser)) { throw new ResetPasswordException(currentUser.getId());}
if (this.shouldCheckForPasswordForceReset(commandWrapper) && this.doesPasswordHasToBeRenewed(currentUser)) { throw new ResetPasswordException(
currentUser.getId()); }
return currentUser;
}
@Override
public void validateAccessRights(final String resourceOfficeHierarchy) {
@@ -111,49 +103,31 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
}
@Override
public boolean doesPasswordHasToBeRenewed(AppUser currentUser )
{
public boolean doesPasswordHasToBeRenewed(AppUser currentUser) {
if( this.configurationDomainService.isPasswordForcedResetEnable()){
if (this.configurationDomainService.isPasswordForcedResetEnable()) {
Long passwordDurationDays = this.configurationDomainService.retrievePasswordLiveTime();
final Date passWordLastUpdateDate = currentUser .getLastTimePasswordUpdated();
Long passwordDurationDays = this.configurationDomainService.retrievePasswordLiveTime();
final Date passWordLastUpdateDate = currentUser.getLastTimePasswordUpdated();
Calendar c = Calendar.getInstance();
c.setTime(passWordLastUpdateDate);
c.add(Calendar.DATE,passwordDurationDays.intValue());
Calendar c = Calendar.getInstance();
c.setTime(passWordLastUpdateDate);
c.add(Calendar.DATE, passwordDurationDays.intValue());
final Date passwordExpirationDate = c.getTime();
final Date passwordExpirationDate = c.getTime();
if(DateUtils.getDateOfTenant().after(passwordExpirationDate)){
return true ;
}
else { return false; }
}
else{
return false;
}
if (DateUtils.getDateOfTenant().after(passwordExpirationDate)) { return true; }
}
return false;
}
private boolean shouldCheckForPasswordForceReset(CommandWrapper commandWrapper)
{
for( CommandWrapper commandItem : this.EXEMPT_FROM_PASSWORD_RESET_CHECK )
{
if(commandItem.actionName().equals(commandWrapper.actionName())
&& commandItem.getEntityName().equals(commandWrapper.getEntityName()))
{
return false;
}
private boolean shouldCheckForPasswordForceReset(CommandWrapper commandWrapper) {
for (CommandWrapper commandItem : EXEMPT_FROM_PASSWORD_RESET_CHECK) {
if (commandItem.actionName().equals(commandWrapper.actionName())
&& commandItem.getEntityName().equals(commandWrapper.getEntityName())) { return false; }
}
return true;
}
}
@@ -15,7 +15,6 @@ import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.staff.data.StaffData;
import org.mifosplatform.organisation.staff.exception.StaffNotFoundException;
import org.omg.PortableInterceptor.ACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -5,12 +5,8 @@
*/
package org.mifosplatform.portfolio.collectionsheet.service;
import java.util.Collection;
import org.joda.time.LocalDate;
import org.mifosplatform.infrastructure.core.api.JsonQuery;
import org.mifosplatform.portfolio.collectionsheet.data.JLGCollectionSheetData;
import org.mifosplatform.portfolio.collectionsheet.data.JLGCollectionSheetFlatData;
public interface CollectionSheetReadPlatformService {
@@ -1,12 +1,5 @@
package org.mifosplatform.useradministration.api;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Cieyou on 1/16/14.
*/
public class AppUserApiConstant {
public static final int numberOfPreviousPasswords = 3;
@@ -1,24 +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.domain;
import org.mifosplatform.infrastructure.security.domain.PlatformUserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface AppUserPreviewPasswordRepository extends JpaRepository<AppUserPreviewPassword, Long>, JpaSpecificationExecutor<AppUserPreviewPassword> {
// no behaviour added
// @Query("SELECT upp FROM AppUserPreviewPassword upp WHERE upp.userId = :userId order by upp.removalDate ASC ")
public List<AppUserPreviewPassword> findByUserId(Long userId,Pageable pageable);
}
@@ -5,21 +5,20 @@
*/
package org.mifosplatform.useradministration.domain;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.mifosplatform.infrastructure.core.service.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.domain.AbstractPersistable;
import javax.persistence.*;
import java.util.*;
@Entity
@Table(name = "m_appuser_previews_passwords")
public class AppUserPreviewPassword extends AbstractPersistable<Long> {
private final static Logger logger = LoggerFactory.getLogger(AppUserPreviewPassword.class);
@Table(name = "m_appuser_previous_password")
public class AppUserPreviousPassword extends AbstractPersistable<Long> {
@Column(name = "user_id", nullable = false)
private Long userId;
@@ -31,23 +30,18 @@ public class AppUserPreviewPassword extends AbstractPersistable<Long> {
@Column(name = "password", nullable = false)
private String password;
protected AppUserPreviewPassword() {
protected AppUserPreviousPassword() {
}
public AppUserPreviewPassword(final AppUser user) {
this.userId = user.getId();
this.password = user.getPassword().trim();
this.removalDate = DateUtils.getDateOfTenant();
public AppUserPreviousPassword(final AppUser user) {
this.userId = user.getId();
this.password = user.getPassword().trim();
this.removalDate = DateUtils.getDateOfTenant();
}
public String getPassword()
{
public String getPassword() {
return this.password;
}
}
@@ -0,0 +1,18 @@
/**
* 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.domain;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface AppUserPreviousPasswordRepository extends JpaRepository<AppUserPreviousPassword, Long>,
JpaSpecificationExecutor<AppUserPreviousPassword> {
public List<AppUserPreviousPassword> findByUserId(Long userId, Pageable pageable);
}
@@ -11,7 +11,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
@@ -26,7 +25,13 @@ import org.mifosplatform.organisation.office.domain.Office;
import org.mifosplatform.organisation.office.domain.OfficeRepository;
import org.mifosplatform.organisation.office.exception.OfficeNotFoundException;
import org.mifosplatform.useradministration.api.AppUserApiConstant;
import org.mifosplatform.useradministration.domain.*;
import org.mifosplatform.useradministration.domain.AppUser;
import org.mifosplatform.useradministration.domain.AppUserPreviousPassword;
import org.mifosplatform.useradministration.domain.AppUserPreviousPasswordRepository;
import org.mifosplatform.useradministration.domain.AppUserRepository;
import org.mifosplatform.useradministration.domain.Role;
import org.mifosplatform.useradministration.domain.RoleRepository;
import org.mifosplatform.useradministration.domain.UserDomainService;
import org.mifosplatform.useradministration.exception.PasswordPreviouslyUsedException;
import org.mifosplatform.useradministration.exception.RoleNotFoundException;
import org.mifosplatform.useradministration.exception.UserNotFoundException;
@@ -54,12 +59,13 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
private final OfficeRepository officeRepository;
private final RoleRepository roleRepository;
private final UserDataValidator fromApiJsonDeserializer;
private final AppUserPreviewPasswordRepository appUserPreviewPasswordRepository;
private final AppUserPreviousPasswordRepository appUserPreviewPasswordRepository;
@Autowired
public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository,
final UserDomainService userDomainService, final OfficeRepository officeRepository, final RoleRepository roleRepository,
final PlatformPasswordEncoder platformPasswordEncoder, final UserDataValidator fromApiJsonDeserializer,final AppUserPreviewPasswordRepository appUserPreviewPasswordRepository) {
final PlatformPasswordEncoder platformPasswordEncoder, final UserDataValidator fromApiJsonDeserializer,
final AppUserPreviousPasswordRepository appUserPreviewPasswordRepository) {
this.context = context;
this.appUserRepository = appUserRepository;
this.userDomainService = userDomainService;
@@ -72,9 +78,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
@Transactional
@Override
@Caching(evict = {
@CacheEvict(value = "users", allEntries = true),
@CacheEvict(value = "usersByUsername", allEntries = true)})
@Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult createUser(final JsonCommand command) {
try {
@@ -118,26 +122,20 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
@Transactional
@Override
@Caching(evict = {
@CacheEvict(value = "users", allEntries = true),
@CacheEvict(value = "usersByUsername", allEntries = true)})
@Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult updateUser(final Long userId, final JsonCommand command) {
try {
this.context.authenticatedUser(new CommandWrapperBuilder().updateUser(null).build());
this.fromApiJsonDeserializer.validateForUpdate(command.json());
final AppUser userToUpdate = this.appUserRepository.findOne(userId);
if (userToUpdate == null) { throw new UserNotFoundException(userId); }
final AppUserPreviewPassword currentPasswordToSaveAsPreview = getCurrentPasswordToSaveAsPreview(userToUpdate,command);
final AppUserPreviousPassword currentPasswordToSaveAsPreview = getCurrentPasswordToSaveAsPreview(userToUpdate, command);
final Map<String, Object> changes = userToUpdate.update(command, this.platformPasswordEncoder);
@@ -159,7 +157,9 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
if (!changes.isEmpty()) {
this.appUserRepository.saveAndFlush(userToUpdate);
if(currentPasswordToSaveAsPreview!=null) {this.appUserPreviewPasswordRepository.save(currentPasswordToSaveAsPreview);}
if (currentPasswordToSaveAsPreview != null) {
this.appUserPreviewPasswordRepository.save(currentPasswordToSaveAsPreview);
}
}
@@ -176,43 +176,40 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
}
/**
* encode the new submitted password
* retrieve the last n used password
* check if the current submitted password, match with one of them
* encode the new submitted password retrieve the last n used password check
* if the current submitted password, match with one of them
*
* @param user
* @param command
* @return
*/
private AppUserPreviewPassword getCurrentPasswordToSaveAsPreview(final AppUser user,final JsonCommand command)
{
private AppUserPreviousPassword getCurrentPasswordToSaveAsPreview(final AppUser user, final JsonCommand command) {
final String passWordEncodedValue = user.getEncodedPassword(command,this.platformPasswordEncoder);
final String passWordEncodedValue = user.getEncodedPassword(command, this.platformPasswordEncoder);
AppUserPreviewPassword currentPasswordToSaveAsPreview = null;
AppUserPreviousPassword currentPasswordToSaveAsPreview = null;
if(passWordEncodedValue!=null )
{
if (passWordEncodedValue != null) {
PageRequest pageRequest = new PageRequest(0, AppUserApiConstant.numberOfPreviousPasswords, Sort.Direction.DESC,"removalDate");
PageRequest pageRequest = new PageRequest(0, AppUserApiConstant.numberOfPreviousPasswords, Sort.Direction.DESC, "removalDate");
final List<AppUserPreviewPassword> nLastUsedPasswords = this.appUserPreviewPasswordRepository.findByUserId(user.getId(),pageRequest);
final List<AppUserPreviousPassword> nLastUsedPasswords = this.appUserPreviewPasswordRepository.findByUserId(user.getId(),
pageRequest);
for(AppUserPreviewPassword aPreviewPassword : nLastUsedPasswords)
{
for (AppUserPreviousPassword aPreviewPassword : nLastUsedPasswords) {
if(aPreviewPassword.getPassword().equals(passWordEncodedValue)){
if (aPreviewPassword.getPassword().equals(passWordEncodedValue)) {
throw new PasswordPreviouslyUsedException();
throw new PasswordPreviouslyUsedException();
}
}
currentPasswordToSaveAsPreview = new AppUserPreviewPassword(user);
currentPasswordToSaveAsPreview = new AppUserPreviousPassword(user);
}
return currentPasswordToSaveAsPreview ;
return currentPasswordToSaveAsPreview;
}
@@ -234,9 +231,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit
@Transactional
@Override
@Caching(evict = {
@CacheEvict(value = "users", allEntries = true),
@CacheEvict(value = "usersByUsername", allEntries = true)})
@Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult deleteUser(final Long userId) {
final AppUser user = this.appUserRepository.findOne(userId);