com.github.iintelligas.service.impl.UserServiceImpl Maven / Gradle / Ivy
package com.github.iintelligas.service.impl;
import com.github.iintelligas.exception.DuplicateDataException;
import com.github.iintelligas.exception.InvalidDataException;
import com.github.iintelligas.persist.dto.Permission;
import com.github.iintelligas.persist.dto.Role;
import com.github.iintelligas.persist.dto.User;
import com.github.iintelligas.persist.dto.UserAutocompleteInfo;
import com.github.iintelligas.persist.entity.PermissionEntity;
import com.github.iintelligas.persist.entity.RoleEntity;
import com.github.iintelligas.persist.entity.UserEntity;
import com.github.iintelligas.repo.RoleRepository;
import com.github.iintelligas.repo.UserRepository;
import com.github.iintelligas.exception.UserNotEnabledException;
import com.github.iintelligas.service.LoginAttemptService;
import com.github.iintelligas.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
private static final Logger logger = org.slf4j.LoggerFactory.getLogger(UserServiceImpl.class);
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final LoginAttemptService loginAttemptService;
private final HttpServletRequest request;
@Autowired
public UserServiceImpl(UserRepository userRepository, RoleRepository roleRepository, LoginAttemptService loginAttemptService, HttpServletRequest request) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.loginAttemptService = loginAttemptService;
this.request = request;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.debug("Load user by username = " + username);
final String ip = getClientIP();
if (loginAttemptService.isBlocked(ip)) {
throw new RuntimeException("Too Many Login attempt. Blocking for Today");
}
UserEntity account = null;
try {
account= getUser(username);
} catch (UsernameNotFoundException e) {
logger.error("NO SUCH USER !! ");
}
if(account == null) {
logger.warn("NO SUCH USER!!");
throw new UsernameNotFoundException("UserEntity "+username + " has no authorities");
}
else if (!account.getEnabled())
{
throw new UserNotEnabledException("UserEntity " + username + " was not enabled");
}
account.setLastAccessDate(Calendar.getInstance().getTime());
updateUser(account);
//return account;
return new User(account);
}
@Override
public User addUser(User user) {
logger.debug("Adding user = " + user.getUsername());
try {
UserEntity userEntity = new UserEntity(user);
if(CollectionUtils.isNotEmpty(user.getRoles())) {
for(Role roleDto : user.getRoles()) {
RoleEntity role = roleRepository.findByName(roleDto.getName());
if(role == null) {
throw new InvalidDataException("Could not found RoleEntity "+roleDto.getName()+" from DB");
} else {
userEntity.addRole(role);
}
}
}
userRepository.save(userEntity);
user = new User(userEntity);
if(CollectionUtils.isNotEmpty(userEntity.getRoles())) {
for(RoleEntity role : userEntity.getRoles()) {
user.addRole(new Role(role));
}
}
return user;
}catch (DataIntegrityViolationException e) {
throw new DuplicateDataException("UserEntity "+user.getUsername()+" already present.");
}
}
@Override
public User getUser(Long userId) {
logger.debug("Get user by user id = " + userId);
return new User(userRepository.findOne(userId));
}
@Override
public UserEntity getUser(String username) {
logger.debug("Get user by username = " + username);
return userRepository.findByUsername(username);
}
@Override
public void updateUser(UserEntity user) {
logger.debug("Update user = " + user.getUsername());
userRepository.save(user);
}
@Override
public void updateUser(User user) {
logger.debug("Update user = " + user.getUsername());
UserEntity userEntity = new UserEntity(user);
if(user.getRoles() != null) {
for(Role roleDto : user.getRoles()) {
RoleEntity role = roleRepository.findByName(roleDto.getName());
if(role != null) {
userEntity.addRole(role);
} else {
throw new InvalidDataException("Could not found RoleEntity "+roleDto.getName()+" from DB");
}
}
}
userRepository.save(userEntity);
}
@Override
public void deleteUser(Long userId) {
User toBeDeletedUser = getUser(userId);
if(toBeDeletedUser != null) {
logger.debug("Deleting user = " + toBeDeletedUser.getUsername());
userRepository.delete(toBeDeletedUser.getId());
}
}
@Override
public List getUsers() {
logger.debug("Finding users");
List userEntities = userRepository.findAll();
List userDtos = new ArrayList<>(userEntities.size());
//TODO need to write mapper
for(UserEntity user : userEntities) {
User userDto = new User(user);
if(CollectionUtils.isNotEmpty(user.getRoles())) {
List roles = new ArrayList<>(user.getRoles().size());
for(RoleEntity role : user.getRoles()) {
Role roleDto = new Role(role);
roles.add(roleDto);
if(CollectionUtils.isNotEmpty(role.getPermissions())) {
List permissions = new ArrayList<>(role.getPermissions().size());
for(PermissionEntity permissionEntity : role.getPermissions()) {
permissions.add(new Permission(permissionEntity));
}
roleDto.setPermissions(permissions);
}
}
userDto.setRoles(roles);
}
userDtos.add(userDto);
}
return userDtos;
}
@Override
public void assignRoleToUser(Role role, User user) {
logger.debug("Assigning role= [ " +role.getName() + " ] to user -> " + user.getUsername());
RoleEntity assignedRole = roleRepository.findByName(role.getName());
if(assignedRole == null) {
throw new NoResultException("RoleEntity does not exist");
}
UserEntity assignedUser = userRepository.findByUsername(user.getUsername());
if(assignedUser == null) {
throw new NoResultException("UserEntity does not exist");
}
assignedUser.addRole(assignedRole);
userRepository.save(assignedUser);
}
private String getClientIP() {
final String xfHeader = request.getHeader("X-Forwarded-For");
if (xfHeader == null) {
return request.getRemoteAddr();
}
return xfHeader.split(",")[0];
}
@Override
public void updateProfile(User user) {
logger.debug("Update user = " + user.getUsername());
UserEntity storedUser = userRepository.findOne(user.getId());
storedUser.setPassword(user.getPassword());
storedUser.setLastName(user.getLastName());
storedUser.setFirstName(user.getFirstName());
userRepository.save(storedUser);
}
@Override
public List getMatchingNames(String name) {
List allUserEntities = userRepository.findByMatchingName(name);
List userInfos = new ArrayList<>();
if(CollectionUtils.isNotEmpty(allUserEntities)){
allUserEntities.forEach(user -> {
UserAutocompleteInfo userInfo = new UserAutocompleteInfo(user.getUsername(), new StringBuilder(StringUtils.trim(user.getFirstName())).append(" ").append(StringUtils.trim(user.getLastName())).toString());
userInfos.add(userInfo);
});
}
return userInfos;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy