Open Kilda Java Documentation
UserService.java
Go to the documentation of this file.
1 package org.usermanagement.service;
2 
3 import java.util.Calendar;
4 import java.util.Date;
5 import java.util.HashMap;
6 import java.util.HashSet;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Set;
10 
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21 import org.springframework.beans.factory.annotation.Autowired;
22 import org.springframework.security.core.GrantedAuthority;
23 import org.springframework.security.core.userdetails.UserDetails;
24 import org.springframework.security.core.userdetails.UserDetailsService;
25 import org.springframework.security.core.userdetails.UsernameNotFoundException;
26 import org.springframework.stereotype.Service;
27 import org.springframework.transaction.annotation.Propagation;
28 import org.springframework.transaction.annotation.Transactional;
45 
51 @Service
52 public class UserService implements UserDetailsService {
53 
55  private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);
56 
57  @Autowired
58  private RoleService roleService;
59 
60  @Autowired
61  private UserRepository userRepository;
62 
63  @Autowired
64  private RoleRepository roleRepository;
65 
66  @Autowired
67  private MessageUtils messageUtil;
68 
69  @Autowired
70  private UserValidator userValidator;
71 
72  @Autowired
73  private MailService mailService;
74 
75  @Autowired
76  private MailUtils mailUtils;
77 
78  @Autowired
79  private UserSettingRepository userSettingRepository;
80 
81  @Autowired
82  private ActivityLogger activityLogger;
83 
84  @Autowired
85  MessageCodeUtil messageCodeUtil;
86 
87  /*
88  * (non-Javadoc)
89  *
90  * @see org.springframework.security.core.userdetails.UserDetailsService#
91  * loadUserByUsername(java. lang.String)
92  */
93  @Override
94  public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
95  UserEntity user = userRepository.findByUsername(username);
96 
97  Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(0);
98  if (user == null) {
99  LOGGER.error("User with username '" + username + "' not found.");
100  throw new UsernameNotFoundException(username);
101  }
102 
103  return new org.springframework.security.core.userdetails.User(username, user.getPassword(),
104  authorities);
105  }
106 
113  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
114  public UserInfo createUser(final UserInfo userRequest) {
115  userValidator.validateCreateUser(userRequest);
116 
117  Set<RoleEntity> roleEntities = roleService.getRolesById(userRequest.getRoleIds());
118 
119  UserEntity userEntity = UserConversionUtil.toUserEntity(userRequest, roleEntities);
120  String password = ValidatorUtil.randomAlphaNumeric(16);
121  userEntity.setPassword(StringUtil.encodeString(password));
122  userEntity.setIs2FaEnabled(true);
123  userEntity = userRepository.save(userEntity);
124  LOGGER.info("User with username '" + userEntity.getUsername() + "' created successfully.");
125 
126  activityLogger.log(ActivityType.CREATE_USER, userRequest.getUsername());
127 
128  if (userEntity.getUserId() != null) {
129  Map<String, Object> map = new HashMap<String, Object>();
130  map.put("name", userEntity.getName());
131  map.put("username", userEntity.getUsername());
132  map.put("password", password);
133  mailService.send(userEntity.getEmail(), mailUtils.getSubjectAccountUsername(),
135  mailService.send(userEntity.getEmail(), mailUtils.getSubjectAccountPassword(),
137  LOGGER.info("Username and password email sent successfully to user(username: "
138  + userEntity.getUsername() + ").");
139  }
140  return UserConversionUtil.toUserInfo(userEntity);
141  }
142 
143 
151  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
152  public UserInfo updateUser(final UserInfo userInfo, final Long userId) {
153  UserEntity userEntity = userValidator.validateUpdateUser(userInfo);
154 
155  if (userInfo.getRoleIds() != null) {
156  userEntity.getRoles().clear();
157  Set<RoleEntity> roleEntities = roleService.getRolesById(userInfo.getRoleIds());
158  userEntity.getRoles().addAll(roleEntities);
159  }
160 
161  UserConversionUtil.toUpateUserEntity(userInfo, userEntity);
162  userEntity = userRepository.save(userEntity);
163 
164  activityLogger.log(ActivityType.UPDATE_USER, userEntity.getUsername());
165  LOGGER.info("User updated successfully (id: " + userId + ")");
166 
167  return UserConversionUtil.toUserInfo(userEntity);
168  }
169 
170 
176  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
177  public List<UserInfo> getAllUsers() {
178  List<UserEntity> userEntities = userRepository.findAll();
179  return UserConversionUtil.toAllUsers(userEntities);
180  }
181 
182 
189  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
190  public UserInfo getUserById(final Long userId) {
191  UserEntity userEntity = userValidator.validateUserId(userId);
192  return UserConversionUtil.toUserInfo(userEntity);
193  }
194 
195 
202  @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
203  public UserEntity getUserByUsername(final String userName) {
204  return userRepository.findByUsername(userName);
205  }
206 
213  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
214  public void updateUser2FAKey(final String userName, final String secretKey) {
215  UserEntity userEntity = userRepository.findByUsername(userName);
216  userEntity.setTwoFaKey(secretKey);
217  userRepository.save(userEntity);
218  LOGGER.info("User 2FA updated successfully (username: " + userName + ")");
219  }
220 
226  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
227  public void updateLoginDetail(final String userName) {
228  UserEntity userEntity = userRepository.findByUsername(userName);
229  if (ValidatorUtil.isNull(userEntity)) {
230  LOGGER.error("User with username '" + userName + "' not found. Error: "
231  + messageUtil.getAttributeInvalid("username", userName + ""));
232  throw new RequestValidationException(
233  messageUtil.getAttributeInvalid("username", userName + ""));
234  }
235  userEntity.setLoginTime(Calendar.getInstance().getTime());
236  userEntity.setIs2FaConfigured(true);
237  userRepository.save(userEntity);
238  LOGGER.info("User last login updated successfully (username: " + userName + ")");
239  }
240 
246  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
247  public void deleteUserById(final Long userId) {
248  UserEntity userEntity = userRepository.findByUserId(userId);
249  if (ValidatorUtil.isNull(userEntity)) {
250  LOGGER.error("User with user id '" + userId + "' not found. Error: "
251  + messageUtil.getAttributeInvalid("user_id", userId + ""));
252  throw new RequestValidationException(
253  messageUtil.getAttributeInvalid("user_id", userId + ""));
254  }
255 
256  userRepository.delete(userEntity);
257 
258  activityLogger.log(ActivityType.DELETE_USER, userEntity.getUsername());
259  LOGGER.info("User deleted successfully (userId: " + userId + ")");
260  }
261 
269  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
270  public Role assignUserByRoleId(final Long roleId, final Role role) {
271 
272  RoleEntity roleEntity = roleRepository.findByRoleId(roleId);
273  if (ValidatorUtil.isNull(roleEntity)) {
274  LOGGER.error("Role with role id '" + roleId + "' not found. Error: "
275  + messageUtil.getAttributeInvalid("role_id", roleId + ""));
276  throw new RequestValidationException(
277  messageUtil.getAttributeInvalid("role_id", roleId + ""));
278  }
279  roleEntity.getUsers().clear();
280  if (role.getUserInfo() != null) {
281  for (UserInfo user : role.getUserInfo()) {
282  UserEntity userEntity = userRepository.findByUserId(user.getUserId());
283  roleEntity.getUsers().add(userEntity);
284  }
285  }
286  roleEntity = roleRepository.save(roleEntity);
287 
288  activityLogger.log(ActivityType.ASSIGN_USERS_BY_ROLE, roleEntity.getName());
289  LOGGER.info("Users assigned with role successfully (role id: " + roleId + ")");
290  return RoleConversionUtil.toRole(roleEntity, false, true);
291  }
292 
300  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
301  public UserInfo changePassword(final UserInfo userInfo, final Long userId) {
302  userValidator.validateChangePassword(userInfo);
303 
304  UserEntity userEntity = userRepository.findByUserId(userId);
305  if (ValidatorUtil.isNull(userEntity)) {
306  LOGGER.error("User Entity not found for user(id: " + userId + ")");
307  throw new RequestValidationException(
308  messageUtil.getAttributeInvalid("user_id", userId + ""));
309  }
310 
311  if (!StringUtil.matches(userInfo.getPassword(), userEntity.getPassword())) {
312  LOGGER.error("Password not matched for user (id: " + userId + "). Error: "
313  + messageUtil.getAttributePasswordInvalid());
314  throw new RequestValidationException(messageUtil.getAttributePasswordInvalid());
315  }
316 
317  if (userEntity.getIs2FaEnabled()) {
318  if (!userEntity.getIs2FaConfigured()) {
319  LOGGER.error("2FA key is not configured for user(id: " + userId + "). Error: "
320  + messageUtil.getAttribute2faNotConfiured());
321  throw new TwoFaKeyNotSetException(messageUtil.getAttribute2faNotConfiured());
322  } else {
323  if (userInfo.getCode() == null || userInfo.getCode().isEmpty()) {
324  LOGGER.error("OTP code is madatory as 2FA is configured for user (id: " + userId + "). Error: "
325  + messageUtil.getAttributeNotNull("OTP"));
326  throw new OtpRequiredException(messageUtil.getAttributeNotNull("OTP"));
327  } else if (!TwoFactorUtility.validateOtp(userInfo.getCode(),
328  userEntity.getTwoFaKey())) {
329  LOGGER.error("Invalid OTP for user (id: " + userId + "). Error: "
330  + messageUtil.getAttributeNotvalid("OTP"));
331  throw new InvalidOtpException(
332  messageUtil.getAttributeNotvalid("OTP"));
333  }
334  }
335  }
336 
337  userEntity.setPassword(StringUtil.encodeString(userInfo.getNewPassword()));
338  userEntity.setUpdatedDate(new Date());
339  userEntity = userRepository.save(userEntity);
340 
341  activityLogger.log(ActivityType.CHANGE_PASSWORD, userEntity.getUsername());
342  LOGGER.info("User(userId: " + userId + ") password changed successfully.");
343 
344  Map<String, Object> context = new HashMap<>();
345  context.put("name", userEntity.getName());
346  mailService.send(userEntity.getEmail(), mailUtils.getSubjectChangePassword(),
348  LOGGER.info("Changed password mail sent successfully for user(userId: " + userId + ").");
349 
350  return UserConversionUtil.toUserInfo(userEntity);
351  }
352 
360  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
361  public UserInfo resetPassword(final long userId, final boolean adminFlag) {
362  UserInfo userinfo = new UserInfo();
363  userinfo.setUserId(userId);
364 
365  UserEntity userEntity = userRepository.findByUserId(userId);
366 
367  if (ValidatorUtil.isNull(userEntity)) {
368  LOGGER.error("User Entity not found for user(id: " + userId + ")");
369  throw new RequestValidationException(
370  messageUtil.getAttributeInvalid("user_id", userId + ""));
371  }
372  String randomPassword = ValidatorUtil.randomAlphaNumeric(16);
373  userEntity = UserConversionUtil.toResetPwdUserEntity(userEntity, randomPassword);
374  if (adminFlag) {
375  userEntity.setIs2FaConfigured(false);
376  userEntity.setTwoFaKey(null);
377  }
378  userEntity = userRepository.save(userEntity);
379  if (adminFlag) {
380  activityLogger.log(ActivityType.ADMIN_RESET_PASSWORD, userEntity.getUsername());
381  } else {
382  activityLogger.log(ActivityType.RESET_PASSWORD, userEntity.getUsername());
383  }
384 
385  LOGGER.info("Password reset successfully for user(userId: " + userId + ").");
386  if (!adminFlag) {
387  Map<String, Object> context = new HashMap<>();
388  context.put("name", userEntity.getName());
389  context.put("password", randomPassword);
390  mailService.send(userEntity.getEmail(), mailUtils.getSubjectResetPassword(),
392  LOGGER.info("Reset password mail sent successfully for user(userId: " + userId + ").");
393  }
394  userinfo.setPassword(randomPassword);
395  return userinfo;
396  }
397 
403  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
404  public void reset2fa(final long userId) {
405  UserEntity userEntity = userRepository.findByUserId(userId);
406 
407  if (ValidatorUtil.isNull(userEntity)) {
408  LOGGER.error("User Entity not found for user(user_id: " + userId + ")");
409  throw new RequestValidationException(
410  messageUtil.getAttributeInvalid("user_id", userId + ""));
411  }
412  userEntity.setIs2FaConfigured(false);
413  userEntity.setTwoFaKey(null);
414  userEntity = userRepository.save(userEntity);
415 
416  activityLogger.log(ActivityType.RESET_2FA, userEntity.getUsername());
417  LOGGER.info("2FA reset successfully for user(user_id: " + userId + ").");
418  if (!userEntity.getIs2FaConfigured()) {
419  Map<String, Object> context = new HashMap<>();
420  context.put("name", userEntity.getName());
421 
422  mailService.send(userEntity.getEmail(), mailUtils.getSubjectReset2fa(),
424  LOGGER.info("Reset 2FA mail sent successfully for user(user_id: " + userId + ").");
425  }
426  }
427 
428  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
430 
431  if (ValidatorUtil.isNull(userInfo.getUserId())) {
432  LOGGER.error("Validation failed for user (id: " + userInfo.getUserId() + "). Error: "
433  + messageUtil.getAttributeInvalid("user_id", userInfo.getUserId() + ""));
434  throw new RequestValidationException(messageUtil.getAttributeInvalid("user_id", userInfo.getUserId() + ""));
435  }
436 
437  UserSettingEntity userSettingEntity = userSettingRepository.findOneByUserId(userInfo.getUserId());
438  if (userSettingEntity == null) {
439  userSettingEntity = new UserSettingEntity();
440  userSettingEntity.setUserId(userInfo.getUserId());
441  }
442  userSettingEntity.setSettings(IConstants.SETTINGS.TOPOLOGY_SETTING);
443  userSettingEntity.setData(userInfo.getData());
444  userSettingEntity = userSettingRepository.save(userSettingEntity);
445 
446  //activityLogger.log(ActivityType.UPDATE_USER_SETTINGS, userInfo.getUserId() + "");
447  LOGGER.info("User Settings saved successfully for user(user_id: " + userInfo.getUserId() + ").");
448  return userInfo;
449  }
450 
451  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
452  public String getUserSettings(final long userId) {
453 
454  if (ValidatorUtil.isNull(userId)) {
455  LOGGER.error("Validation failed for user (id: " + userId + "). Error: "
456  + messageUtil.getAttributeInvalid("user_id", userId + ""));
457  throw new RequestValidationException(messageUtil.getAttributeInvalid("user_id", userId + ""));
458  }
459 
460  UserSettingEntity userSettingEntity = userSettingRepository.findOneByUserId(userId);
461  if (userSettingEntity == null) {
462  LOGGER.error("User settings not found for user(user_id: " + userId + ")" + messageCodeUtil.getAttributeNotFoundCode());
463  throw new RequestValidationException(messageCodeUtil.getAttributeNotFoundCode(),
464  messageUtil.getAttributeNotFound("User settings"));
465  }
466  return userSettingEntity.getData();
467  }
468 
469  public boolean validateOTP(final long userId, final String otp) {
470  UserEntity userEntity = userRepository.findByUserId(userId);
471  if (ValidatorUtil.isNull(userEntity)) {
472  LOGGER.error("User Entity not found for user(id: " + userId + ")");
473  throw new RequestValidationException(
474  messageUtil.getAttributeInvalid("user_id", userId + ""));
475  }
476 
477  if (userEntity.getIs2FaEnabled()) {
478  if (!userEntity.getIs2FaConfigured()) {
479  LOGGER.error("2FA key is not configured for user(id: " + userId
480  + "). Error: " + messageUtil.getAttribute2faNotConfiured());
481  throw new TwoFaKeyNotSetException(messageUtil.getAttribute2faNotConfiured());
482  } else {
483  if (otp == null || otp.isEmpty()) {
484  LOGGER.error("OTP code is madatory as 2FA is configured for user (id: "
485  + userId + "). Error: "
486  + messageUtil.getAttributeNotNull("OTP"));
487  throw new OtpRequiredException(messageUtil.getAttributeNotNull("OTP"));
488  } else if (!TwoFactorUtility.validateOtp(otp,
489  userEntity.getTwoFaKey())) {
490  LOGGER.error("Invalid OTP for user (id: " + userId + "). Error: "
491  + messageUtil.getAttributeNotvalid("OTP"));
492  throw new InvalidOtpException(messageUtil.getAttributeNotvalid("OTP"));
493  }
494  }
495  } else {
496  LOGGER.error("2FA is not enabled for user(id: " + userId + "). Error: "
497  + messageUtil.getAttribute2faNotEnabled());
498  throw new TwoFaKeyNotSetException(messageUtil.getAttribute2faNotEnabled());
499  }
500  return true;
501  }
502 }
503 
void setIs2FaConfigured(final boolean is2FaConfigured)
UserInfo changePassword(final UserInfo userInfo, final Long userId)
UserInfo updateUser(final UserInfo userInfo, final Long userId)
void setTwoFaKey(final String twoFaKey)
void setUpdatedDate(Date updatedDate)
static boolean validateOtp(final String otp, final String decryptKey)
String getUserSettings(final long userId)
void deleteUserById(final Long userId)
static boolean matches(String rawPassword, String encodedPassword)
Definition: StringUtil.java:55
static UserEntity toUserEntity(final UserInfo userInfo, final Set< RoleEntity > roleEntities)
void setIs2FaEnabled(final boolean is2FaEnabled)
UserDetails loadUserByUsername(final String username)
static String randomAlphaNumeric(final int count)
static boolean isNull(final Object obj)
void setPassword(final String password)
static String encodeString(String data)
Definition: StringUtil.java:44
static List< UserInfo > toAllUsers(final List< UserEntity > userEntityList)
UserInfo saveOrUpdateSettings(UserInfo userInfo)
static UserEntity toResetPwdUserEntity(final UserEntity userEntity, final String randomPassword)
void setLoginTime(final Date loginTime)
UserEntity getUserByUsername(final String userName)
void updateUser2FAKey(final String userName, final String secretKey)
Role assignUserByRoleId(final Long roleId, final Role role)
static void toUpateUserEntity(final UserInfo userInfo, final UserEntity userEntity)
UserInfo getUserById(final Long userId)
void setPassword(final String password)
Definition: UserInfo.java:227
boolean validateOTP(final long userId, final String otp)
static Role toRole(final RoleEntity roleEntity, final boolean withPermissions, final boolean withUsers)
static UserInfo toUserInfo(final UserEntity userEntity)
UserInfo resetPassword(final long userId, final boolean adminFlag)
UserInfo createUser(final UserInfo userRequest)
void updateLoginDetail(final String userName)
void setUserId(final Long userId)
Definition: UserInfo.java:79