PageRenderTime 130ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/fineract-provider/src/main/java/org/apache/fineract/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java

https://gitlab.com/skylabase/incubator-fineract
Java | 338 lines | 241 code | 67 blank | 30 comment | 36 complexity | 26e21041b9137e960324c47f8c8f0d2e MD5 | raw file
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package org.apache.fineract.useradministration.service;
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.HashSet;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Set;
  26. import org.apache.fineract.commands.service.CommandWrapperBuilder;
  27. import org.apache.fineract.infrastructure.core.api.JsonCommand;
  28. import org.apache.fineract.infrastructure.core.data.ApiParameterError;
  29. import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
  30. import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder;
  31. import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
  32. import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
  33. import org.apache.fineract.infrastructure.core.service.PlatformEmailSendException;
  34. import org.apache.fineract.infrastructure.security.service.PlatformPasswordEncoder;
  35. import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
  36. import org.apache.fineract.organisation.office.domain.Office;
  37. import org.apache.fineract.organisation.office.domain.OfficeRepository;
  38. import org.apache.fineract.organisation.office.exception.OfficeNotFoundException;
  39. import org.apache.fineract.organisation.staff.domain.Staff;
  40. import org.apache.fineract.organisation.staff.domain.StaffRepositoryWrapper;
  41. import org.apache.fineract.portfolio.client.domain.Client;
  42. import org.apache.fineract.portfolio.client.domain.ClientRepository;
  43. import org.apache.fineract.useradministration.api.AppUserApiConstant;
  44. import org.apache.fineract.useradministration.domain.AppUser;
  45. import org.apache.fineract.useradministration.domain.AppUserPreviousPassword;
  46. import org.apache.fineract.useradministration.domain.AppUserPreviousPasswordRepository;
  47. import org.apache.fineract.useradministration.domain.AppUserRepository;
  48. import org.apache.fineract.useradministration.domain.Role;
  49. import org.apache.fineract.useradministration.domain.RoleRepository;
  50. import org.apache.fineract.useradministration.domain.UserDomainService;
  51. import org.apache.fineract.useradministration.exception.PasswordPreviouslyUsedException;
  52. import org.apache.fineract.useradministration.exception.RoleNotFoundException;
  53. import org.apache.fineract.useradministration.exception.UserNotFoundException;
  54. import org.slf4j.Logger;
  55. import org.slf4j.LoggerFactory;
  56. import org.springframework.beans.factory.annotation.Autowired;
  57. import org.springframework.cache.annotation.CacheEvict;
  58. import org.springframework.cache.annotation.Caching;
  59. import org.springframework.dao.DataIntegrityViolationException;
  60. import org.springframework.data.domain.PageRequest;
  61. import org.springframework.data.domain.Sort;
  62. import org.springframework.stereotype.Service;
  63. import org.springframework.transaction.annotation.Transactional;
  64. import org.springframework.util.ObjectUtils;
  65. import com.google.gson.JsonArray;
  66. import com.google.gson.JsonElement;
  67. @Service
  68. public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWritePlatformService {
  69. private final static Logger logger = LoggerFactory.getLogger(AppUserWritePlatformServiceJpaRepositoryImpl.class);
  70. private final PlatformSecurityContext context;
  71. private final UserDomainService userDomainService;
  72. private final PlatformPasswordEncoder platformPasswordEncoder;
  73. private final AppUserRepository appUserRepository;
  74. private final OfficeRepository officeRepository;
  75. private final RoleRepository roleRepository;
  76. private final UserDataValidator fromApiJsonDeserializer;
  77. private final AppUserPreviousPasswordRepository appUserPreviewPasswordRepository;
  78. private final StaffRepositoryWrapper staffRepositoryWrapper;
  79. private final ClientRepository clientRepository;
  80. @Autowired
  81. public AppUserWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final AppUserRepository appUserRepository,
  82. final UserDomainService userDomainService, final OfficeRepository officeRepository, final RoleRepository roleRepository,
  83. final PlatformPasswordEncoder platformPasswordEncoder, final UserDataValidator fromApiJsonDeserializer,
  84. final AppUserPreviousPasswordRepository appUserPreviewPasswordRepository, final StaffRepositoryWrapper staffRepositoryWrapper,
  85. final ClientRepository clientRepository) {
  86. this.context = context;
  87. this.appUserRepository = appUserRepository;
  88. this.userDomainService = userDomainService;
  89. this.officeRepository = officeRepository;
  90. this.roleRepository = roleRepository;
  91. this.platformPasswordEncoder = platformPasswordEncoder;
  92. this.fromApiJsonDeserializer = fromApiJsonDeserializer;
  93. this.appUserPreviewPasswordRepository = appUserPreviewPasswordRepository;
  94. this.staffRepositoryWrapper = staffRepositoryWrapper;
  95. this.clientRepository = clientRepository;
  96. }
  97. @Transactional
  98. @Override
  99. @Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) })
  100. public CommandProcessingResult createUser(final JsonCommand command) {
  101. try {
  102. this.context.authenticatedUser();
  103. this.fromApiJsonDeserializer.validateForCreate(command.json());
  104. final String officeIdParamName = "officeId";
  105. final Long officeId = command.longValueOfParameterNamed(officeIdParamName);
  106. final Office userOffice = this.officeRepository.findOne(officeId);
  107. if (userOffice == null) { throw new OfficeNotFoundException(officeId); }
  108. final String[] roles = command.arrayValueOfParameterNamed("roles");
  109. final Set<Role> allRoles = assembleSetOfRoles(roles);
  110. AppUser appUser;
  111. final String staffIdParamName = "staffId";
  112. final Long staffId = command.longValueOfParameterNamed(staffIdParamName);
  113. Staff linkedStaff = null;
  114. if (staffId != null) {
  115. linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId, userOffice.getId());
  116. }
  117. Collection<Client> clients = null;
  118. if(command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)
  119. && command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER)
  120. && command.hasParameter(AppUserConstants.CLIENTS)){
  121. JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS);
  122. Collection<Long> clientIds = new HashSet<>();
  123. for(JsonElement clientElement : clientsArray){
  124. clientIds.add(clientElement.getAsLong());
  125. }
  126. clients = this.clientRepository.findAll(clientIds);
  127. }
  128. appUser = AppUser.fromJson(userOffice, linkedStaff, allRoles, clients, command);
  129. final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail");
  130. this.userDomainService.create(appUser, sendPasswordToEmail);
  131. return new CommandProcessingResultBuilder() //
  132. .withCommandId(command.commandId()) //
  133. .withEntityId(appUser.getId()) //
  134. .withOfficeId(userOffice.getId()) //
  135. .build();
  136. } catch (final DataIntegrityViolationException dve) {
  137. handleDataIntegrityIssues(command, dve);
  138. return CommandProcessingResult.empty();
  139. } catch (final PlatformEmailSendException e) {
  140. final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
  141. final String email = command.stringValueOfParameterNamed("email");
  142. final ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid",
  143. "The parameter email is invalid.", "email", email);
  144. dataValidationErrors.add(error);
  145. throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.",
  146. dataValidationErrors);
  147. }
  148. }
  149. @Transactional
  150. @Override
  151. @Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) })
  152. public CommandProcessingResult updateUser(final Long userId, final JsonCommand command) {
  153. try {
  154. this.context.authenticatedUser(new CommandWrapperBuilder().updateUser(null).build());
  155. this.fromApiJsonDeserializer.validateForUpdate(command.json());
  156. final AppUser userToUpdate = this.appUserRepository.findOne(userId);
  157. if (userToUpdate == null) { throw new UserNotFoundException(userId); }
  158. final AppUserPreviousPassword currentPasswordToSaveAsPreview = getCurrentPasswordToSaveAsPreview(userToUpdate, command);
  159. Collection<Client> clients = null;
  160. boolean isSelfServiceUser = userToUpdate.isSelfServiceUser();
  161. if(command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)){
  162. isSelfServiceUser = command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER);
  163. }
  164. if(isSelfServiceUser
  165. && command.hasParameter(AppUserConstants.CLIENTS)){
  166. JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS);
  167. Collection<Long> clientIds = new HashSet<>();
  168. for(JsonElement clientElement : clientsArray){
  169. clientIds.add(clientElement.getAsLong());
  170. }
  171. clients = this.clientRepository.findAll(clientIds);
  172. }
  173. final Map<String, Object> changes = userToUpdate.update(command, this.platformPasswordEncoder, clients);
  174. if (changes.containsKey("officeId")) {
  175. final Long officeId = (Long) changes.get("officeId");
  176. final Office office = this.officeRepository.findOne(officeId);
  177. if (office == null) { throw new OfficeNotFoundException(officeId); }
  178. userToUpdate.changeOffice(office);
  179. }
  180. if (changes.containsKey("staffId")) {
  181. final Long staffId = (Long) changes.get("staffId");
  182. Staff linkedStaff = null;
  183. if (staffId != null) {
  184. linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId, userToUpdate.getOffice().getId());
  185. }
  186. userToUpdate.changeStaff(linkedStaff);
  187. }
  188. if (changes.containsKey("roles")) {
  189. final String[] roleIds = (String[]) changes.get("roles");
  190. final Set<Role> allRoles = assembleSetOfRoles(roleIds);
  191. userToUpdate.updateRoles(allRoles);
  192. }
  193. if (!changes.isEmpty()) {
  194. this.appUserRepository.saveAndFlush(userToUpdate);
  195. if (currentPasswordToSaveAsPreview != null) {
  196. this.appUserPreviewPasswordRepository.save(currentPasswordToSaveAsPreview);
  197. }
  198. }
  199. return new CommandProcessingResultBuilder() //
  200. .withEntityId(userId) //
  201. .withOfficeId(userToUpdate.getOffice().getId()) //
  202. .with(changes) //
  203. .build();
  204. } catch (final DataIntegrityViolationException dve) {
  205. handleDataIntegrityIssues(command, dve);
  206. return CommandProcessingResult.empty();
  207. }
  208. }
  209. /**
  210. * encode the new submitted password retrieve the last n used password check
  211. * if the current submitted password, match with one of them
  212. *
  213. * @param user
  214. * @param command
  215. * @return
  216. */
  217. private AppUserPreviousPassword getCurrentPasswordToSaveAsPreview(final AppUser user, final JsonCommand command) {
  218. final String passWordEncodedValue = user.getEncodedPassword(command, this.platformPasswordEncoder);
  219. AppUserPreviousPassword currentPasswordToSaveAsPreview = null;
  220. if (passWordEncodedValue != null) {
  221. PageRequest pageRequest = new PageRequest(0, AppUserApiConstant.numberOfPreviousPasswords, Sort.Direction.DESC, "removalDate");
  222. final List<AppUserPreviousPassword> nLastUsedPasswords = this.appUserPreviewPasswordRepository.findByUserId(user.getId(),
  223. pageRequest);
  224. for (AppUserPreviousPassword aPreviewPassword : nLastUsedPasswords) {
  225. if (aPreviewPassword.getPassword().equals(passWordEncodedValue)) {
  226. throw new PasswordPreviouslyUsedException();
  227. }
  228. }
  229. currentPasswordToSaveAsPreview = new AppUserPreviousPassword(user);
  230. }
  231. return currentPasswordToSaveAsPreview;
  232. }
  233. private Set<Role> assembleSetOfRoles(final String[] rolesArray) {
  234. final Set<Role> allRoles = new HashSet<>();
  235. if (!ObjectUtils.isEmpty(rolesArray)) {
  236. for (final String roleId : rolesArray) {
  237. final Long id = Long.valueOf(roleId);
  238. final Role role = this.roleRepository.findOne(id);
  239. if (role == null) { throw new RoleNotFoundException(id); }
  240. allRoles.add(role);
  241. }
  242. }
  243. return allRoles;
  244. }
  245. @Transactional
  246. @Override
  247. @Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) })
  248. public CommandProcessingResult deleteUser(final Long userId) {
  249. final AppUser user = this.appUserRepository.findOne(userId);
  250. if (user == null || user.isDeleted()) { throw new UserNotFoundException(userId); }
  251. user.delete();
  252. this.appUserRepository.save(user);
  253. return new CommandProcessingResultBuilder().withEntityId(userId).withOfficeId(user.getOffice().getId()).build();
  254. }
  255. /*
  256. * Guaranteed to throw an exception no matter what the data integrity issue
  257. * is.
  258. */
  259. private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) {
  260. final Throwable realCause = dve.getMostSpecificCause();
  261. if (realCause.getMessage().contains("username_org")) {
  262. final String username = command.stringValueOfParameterNamed("username");
  263. final StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(username)
  264. .append(" already exists.");
  265. throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username",
  266. username);
  267. }
  268. logger.error(dve.getMessage(), dve);
  269. throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource.");
  270. }
  271. }