Guest User

Untitled

a guest
May 30th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.28 KB | None | 0 0
  1. package com.projectname.service;
  2.  
  3. import com.projectname.domain.*;
  4. import com.projectname.repository.AuthorityRepository;
  5. import com.projectname.repository.PersistentTokenRepository;
  6. import com.projectname.config.Constants;
  7. import com.projectname.repository.UserRepository;
  8. import com.projectname.repository.search.UserSearchRepository;
  9. import com.projectname.security.AuthoritiesConstants;
  10. import com.projectname.security.SecurityUtils;
  11. import com.projectname.service.dto.*;
  12. import com.projectname.service.mapper.*;
  13. import com.projectname.service.util.RandomUtil;
  14.  
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import org.springframework.data.domain.Page;
  18. import org.springframework.data.domain.Pageable;
  19. import org.springframework.scheduling.annotation.Scheduled;
  20. import org.springframework.security.crypto.password.PasswordEncoder;
  21. import org.springframework.stereotype.Service;
  22. import org.springframework.transaction.annotation.Transactional;
  23.  
  24. import javax.inject.Inject;
  25. import java.time.LocalDate;
  26. import java.time.Instant;
  27. import java.time.temporal.ChronoUnit;
  28. import java.util.*;
  29. import java.util.stream.Collectors;
  30.  
  31. /**
  32. * Service class for managing users.
  33. */
  34. @Service
  35. @Transactional
  36. public class UserService {
  37.  
  38. private final Logger log = LoggerFactory.getLogger(UserService.class);
  39. private final UserRepository userRepository;
  40. private final PasswordEncoder passwordEncoder;
  41. private final SocialService socialService;
  42. private final UserSearchRepository userSearchRepository;
  43. private final PersistentTokenRepository persistentTokenRepository;
  44. private final AuthorityRepository authorityRepository;
  45.  
  46. @Inject
  47. private CustomerAccountService customerAccountService;
  48. @Inject
  49. private ManagerAccountService managerAccountService;
  50. @Inject
  51. private PersonalInformationService personalInformationService;
  52. @Inject
  53. private CustomerService customerService;
  54. @Inject
  55. private AddressService addressService;
  56. @Inject
  57. private AvatarService avatarService;
  58. @Inject
  59. private BucketService bucketService;
  60. @Inject
  61. private WishListService wishListService;
  62. @Inject
  63. private SeenService seenService;
  64. @Inject
  65. private ManagerService managerService;
  66.  
  67. private CustomerAccountMapper customerAccountMapper;
  68. private ManagerAccountMapper managerAccountMapper;
  69. private CustomerMapper customerMapper;
  70. private PersonalInformationMapper personalInformationMapper;
  71. private AvatarMapper avatarMapper;
  72. private AddressMapper addressMapper;
  73. private BucketMapper bucketMapper;
  74. private WishListMapper wishListMapper;
  75. private SeenMapper seenMapper;
  76. private ManagerMapper managerMapper;
  77.  
  78. public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, SocialService socialService,
  79. UserSearchRepository userSearchRepository, PersistentTokenRepository persistentTokenRepository,
  80. AuthorityRepository authorityRepository, CustomerAccountMapper customerAccountMapper,
  81. ManagerAccountMapper managerAccountMapper, CustomerMapper customerMapper,
  82. PersonalInformationMapper personalInformationMapper, AvatarMapper avatarMapper,
  83. AddressMapper addressMapper, BucketMapper bucketMapper, WishListMapper wishListMapper,
  84. SeenMapper seenMapper, ManagerMapper managerMapper) {
  85. this.userRepository = userRepository;
  86. this.passwordEncoder = passwordEncoder;
  87. this.socialService = socialService;
  88. this.userSearchRepository = userSearchRepository;
  89. this.persistentTokenRepository = persistentTokenRepository;
  90. this.authorityRepository = authorityRepository;
  91. this.customerAccountMapper = customerAccountMapper;
  92. this.managerAccountMapper = managerAccountMapper;
  93. this.customerMapper = customerMapper;
  94. this.personalInformationMapper = personalInformationMapper;
  95. this.avatarMapper = avatarMapper;
  96. this.addressMapper = addressMapper;
  97. this.bucketMapper = bucketMapper;
  98. this.wishListMapper = wishListMapper;
  99. this.seenMapper = seenMapper;
  100. this.managerMapper = managerMapper;
  101. }
  102.  
  103. public Optional<User> activateRegistration(String key) {
  104. log.debug("Activating user for activation key {}", key);
  105. return userRepository.findOneByActivationKey(key)
  106. .map(user -> {
  107. // activate given user for the registration key.
  108. user.setActivated(true);
  109. user.setActivationKey(null);
  110. userSearchRepository.save(user);
  111. log.debug("Activated user: {}", user);
  112. return user;
  113. });
  114. }
  115.  
  116. private void createdCustomerAccount (User user){
  117.  
  118. CustomerAccount customerAccount = new CustomerAccount(user.getId());
  119. Customer customer = new Customer(user.getId());
  120.  
  121. PersonalInformation personalInformation = new PersonalInformation();
  122. personalInformation.setId(user.getId());
  123.  
  124. Avatar avatar = new Avatar();
  125. avatar.setId(user.getId());
  126.  
  127. Address address = new Address();
  128. address.setId(user.getId());
  129.  
  130. Bucket bucket = new Bucket();
  131. bucket.setId(user.getId());
  132.  
  133. WishList wishList = new WishList();
  134. wishList.setId(user.getId());
  135.  
  136. Seen seen = new Seen();
  137. seen.setId(user.getId());
  138.  
  139. customerAccount.setUser(user);
  140. CustomerAccountDTO customerAccountDTO = customerAccountMapper.toDto(customerAccount);
  141. customerAccountService.save(customerAccountDTO);
  142.  
  143. customer.setCustomerAccount(customerAccount);
  144. CustomerDTO customerDTO = customerMapper.toDto(customer);
  145. customerService.save(customerDTO);
  146.  
  147. personalInformation.setCustomer(customer);
  148. PersonalInformationDTO personalInformationDTO = personalInformationMapper.toDto(personalInformation);
  149. personalInformationService.save(personalInformationDTO);
  150.  
  151. bucket.setCustomer(customer);
  152. BucketDTO bucketDTO = bucketMapper.toDto(bucket);
  153. bucketService.save(bucketDTO);
  154.  
  155. address.setCustomer(customer);
  156. AddressDTO addressDTO = addressMapper.toDto(address);
  157. addressService.save(addressDTO);
  158.  
  159. avatar.setCustomer(customer);
  160. AvatarDTO avatarDTO = avatarMapper.toDto(avatar);
  161. avatarService.save(avatarDTO);
  162.  
  163. wishList.setCustomer(customer);
  164. WishListDTO wishListDTO = wishListMapper.toDto(wishList);
  165. wishListService.save(wishListDTO);
  166.  
  167. seen.setCustomer(customer);
  168. SeenDTO seenDTO = seenMapper.toDto(seen);
  169. seenService.save(seenDTO);
  170.  
  171. customerAccount.setCustomer(customer);
  172. customerAccountDTO = customerAccountMapper.toDto(customerAccount);
  173. customerAccountService.save(customerAccountDTO);
  174.  
  175. customer.setPersonalInfo(personalInformation);
  176. customerDTO = customerMapper.toDto(customer);
  177. customerService.save(customerDTO);
  178.  
  179. customer.setAvatar(avatar);
  180. customerDTO = customerMapper.toDto(customer);
  181. customerService.save(customerDTO);
  182.  
  183. customer.setAddress(address);
  184. customerDTO = customerMapper.toDto(customer);
  185. customerService.save(customerDTO);
  186. }
  187.  
  188.  
  189. public Optional<User> completePasswordReset(String newPassword, String key) {
  190. log.debug("Reset user password for reset key {}", key);
  191.  
  192. return userRepository.findOneByResetKey(key)
  193. .filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400)))
  194. .map(user -> {
  195. user.setPassword(passwordEncoder.encode(newPassword));
  196. user.setResetKey(null);
  197. user.setResetDate(null);
  198. return user;
  199. });
  200. }
  201.  
  202. public Optional<User> requestPasswordReset(String mail) {
  203. return userRepository.findOneByEmail(mail)
  204. .filter(User::getActivated)
  205. .map(user -> {
  206. user.setResetKey(RandomUtil.generateResetKey());
  207. user.setResetDate(Instant.now());
  208. return user;
  209. });
  210. }
  211.  
  212. public User createUser(String login, String password, String firstName, String lastName, String email,
  213. String imageUrl, String langKey) {
  214.  
  215. User newUser = new User();
  216. Authority authority = authorityRepository.findOne(AuthoritiesConstants.USER);
  217. Set<Authority> authorities = new HashSet<>();
  218. String encryptedPassword = passwordEncoder.encode(password);
  219. newUser.setLogin(login);
  220. // new user gets initially a generated password
  221. newUser.setPassword(encryptedPassword);
  222. newUser.setFirstName(firstName);
  223. newUser.setLastName(lastName);
  224. newUser.setEmail(email);
  225. newUser.setImageUrl(imageUrl);
  226. newUser.setLangKey(langKey);
  227. // new user is not active
  228. newUser.setActivated(true); //in the future change to false
  229. // new user gets registration key
  230. newUser.setActivationKey(RandomUtil.generateActivationKey());
  231. authorities.add(authority);
  232. newUser.setAuthorities(authorities);
  233. userRepository.save(newUser);
  234. userSearchRepository.save(newUser);
  235. log.debug("Created Information for User: {}", newUser);
  236. switch (newUser.getLogin()) {
  237. case "managers" : createdManagerAccount(newUser);
  238. break;
  239. default: createdCustomerAccount (newUser);
  240. break;
  241. }
  242. return newUser;
  243. }
  244.  
  245. private void createdManagerAccount(User user) {
  246. ManagerAccount managerAccount = new ManagerAccount(user.getId());
  247. Manager manager = new Manager(user.getId());
  248.  
  249. PersonalInformation personalInformation = new PersonalInformation();
  250. personalInformation.setId(user.getId());
  251.  
  252. Avatar avatar = new Avatar();
  253. avatar.setId(user.getId());
  254.  
  255. Address address = new Address();
  256. address.setId(user.getId());
  257.  
  258. managerAccount.setUser(user);
  259. ManagerAccountDTO managerAccountDTO = managerAccountMapper.toDto(managerAccount);
  260. managerAccountService.save(managerAccountDTO);
  261.  
  262. manager.setManagerAccount(managerAccount);
  263. ManagerDTO managerDTO = managerMapper.toDto(manager);
  264. managerService.save(managerDTO);
  265.  
  266. personalInformation.setManager(manager);
  267. PersonalInformationDTO personalInformationDTO = personalInformationMapper.toDto(personalInformation);
  268. personalInformationService.save(personalInformationDTO);
  269.  
  270. address.setManager(manager);
  271. AddressDTO addressDTO = addressMapper.toDto(address);
  272. addressService.save(addressDTO);
  273.  
  274. avatar.setManager(manager);
  275. AvatarDTO avatarDTO = avatarMapper.toDto(avatar);
  276. avatarService.save(avatarDTO);
  277.  
  278. managerAccount.setManager(manager);
  279. managerAccountDTO = managerAccountMapper.toDto(managerAccount);
  280. managerAccountService.save(managerAccountDTO);
  281.  
  282. manager.setPersonalInfo(personalInformation);
  283. managerDTO = managerMapper.toDto(manager);
  284. managerService.save(managerDTO);
  285.  
  286. manager.setAvatar(avatar);
  287. managerDTO = managerMapper.toDto(manager);
  288. managerService.save(managerDTO);
  289.  
  290. manager.setAddress(address);
  291. managerDTO = managerMapper.toDto(manager);
  292. managerService.save(managerDTO);
  293.  
  294. }
  295.  
  296.  
  297. public User createUser(UserDTO userDTO) {
  298. User user = new User();
  299. user.setLogin(userDTO.getLogin());
  300. user.setFirstName(userDTO.getFirstName());
  301. user.setLastName(userDTO.getLastName());
  302. user.setEmail(userDTO.getEmail());
  303. user.setImageUrl(userDTO.getImageUrl());
  304. if (userDTO.getLangKey() == null) {
  305. user.setLangKey("en"); // default language
  306. } else {
  307. user.setLangKey(userDTO.getLangKey());
  308. }
  309. if (userDTO.getAuthorities() != null) {
  310. Set<Authority> authorities = new HashSet<>();
  311. userDTO.getAuthorities().forEach(
  312. authority -> authorities.add(authorityRepository.findOne(authority))
  313. );
  314. user.setAuthorities(authorities);
  315. }
  316. String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
  317. user.setPassword(encryptedPassword);
  318. user.setResetKey(RandomUtil.generateResetKey());
  319. user.setResetDate(Instant.now());
  320. user.setActivated(true);
  321. userRepository.save(user);
  322. userSearchRepository.save(user);
  323. log.debug("Created Information for User: {}", user);
  324. return user;
  325. }
  326.  
  327. /**
  328. * Update basic information (first name, last name, email, language) for the current user.
  329. *
  330. * @param firstName first name of user
  331. * @param lastName last name of user
  332. * @param email email id of user
  333. * @param langKey language key
  334. * @param imageUrl image URL of user
  335. */
  336. public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
  337. userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> {
  338. user.setFirstName(firstName);
  339. user.setLastName(lastName);
  340. user.setEmail(email);
  341. user.setLangKey(langKey);
  342. user.setImageUrl(imageUrl);
  343. userSearchRepository.save(user);
  344. log.debug("Changed Information for User: {}", user);
  345. });
  346. }
  347.  
  348. /**
  349. * Update all information for a specific user, and return the modified user.
  350. *
  351. * @param userDTO user to update
  352. * @return updated user
  353. */
  354. public Optional<UserDTO> updateUser(UserDTO userDTO) {
  355. return Optional.of(userRepository
  356. .findOne(userDTO.getId()))
  357. .map(user -> {
  358. user.setLogin(userDTO.getLogin());
  359. user.setFirstName(userDTO.getFirstName());
  360. user.setLastName(userDTO.getLastName());
  361. user.setEmail(userDTO.getEmail());
  362. user.setImageUrl(userDTO.getImageUrl());
  363. user.setActivated(userDTO.isActivated());
  364. user.setLangKey(userDTO.getLangKey());
  365. Set<Authority> managedAuthorities = user.getAuthorities();
  366. managedAuthorities.clear();
  367. userDTO.getAuthorities().stream()
  368. .map(authorityRepository::findOne)
  369. .forEach(managedAuthorities::add);
  370. userSearchRepository.save(user);
  371. log.debug("Changed Information for User: {}", user);
  372. return user;
  373. })
  374. .map(UserDTO::new);
  375. }
  376.  
  377.  
  378.  
  379. public void deleteUser(String login) {
  380. userRepository.findOneByLogin(login).ifPresent(user -> {
  381. socialService.deleteUserSocialConnection(user.getLogin());
  382. userRepository.delete(user);
  383. userSearchRepository.delete(user);
  384. log.debug("Deleted User: {}", user);
  385. });
  386. }
  387.  
  388. public void changePassword(String password) {
  389. userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> {
  390. String encryptedPassword = passwordEncoder.encode(password);
  391. user.setPassword(encryptedPassword);
  392. log.debug("Changed password for User: {}", user);
  393. });
  394. }
  395.  
  396. @Transactional(readOnly = true)
  397. public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
  398. return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
  399. }
  400.  
  401. @Transactional(readOnly = true)
  402. public Optional<User> getUserWithAuthoritiesByLogin(String login) {
  403. return userRepository.findOneWithAuthoritiesByLogin(login);
  404. }
  405.  
  406. @Transactional(readOnly = true)
  407. public User getUserWithAuthorities(Long id) {
  408. return userRepository.findOneWithAuthoritiesById(id);
  409. }
  410.  
  411. @Transactional(readOnly = true)
  412. public User getUserWithAuthorities() {
  413. return userRepository.findOneWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin()).orElse(null);
  414. }
  415.  
  416. /**
  417. * Persistent Token are used for providing automatic authentication, they should be automatically deleted after
  418. * 30 days.
  419. * <p>
  420. * This is scheduled to get fired everyday, at midnight.
  421. */
  422. @Scheduled(cron = "0 0 0 * * ?")
  423. public void removeOldPersistentTokens() {
  424. LocalDate now = LocalDate.now();
  425. persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).forEach(token -> {
  426. log.debug("Deleting token {}", token.getSeries());
  427. User user = token.getUser();
  428. user.getPersistentTokens().remove(token);
  429. persistentTokenRepository.delete(token);
  430. });
  431. }
  432.  
  433. /**
  434. * Not activated users should be automatically deleted after 3 days.
  435. * <p>
  436. * This is scheduled to get fired everyday, at 01:00 (am).
  437. */
  438. @Scheduled(cron = "0 0 1 * * ?")
  439. public void removeNotActivatedUsers() {
  440. List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS));
  441. for (User user : users) {
  442. log.debug("Deleting not activated user {}", user.getLogin());
  443. userRepository.delete(user);
  444. userSearchRepository.delete(user);
  445. }
  446. }
  447.  
  448. /**
  449. * @return a list of all the authorities
  450. */
  451. public List<String> getAuthorities() {
  452. return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
  453. }
  454. }
Add Comment
Please, Sign In to add comment