public static User convertToEntity(UserVO dc) { User vo = null; if (dc != null) { vo = new User(); vo.setData(dc.getData()); vo.setId(dc.getId()); vo.setLastLogin(dc.getLastLogin()); vo.setLogin(dc.getLogin()); vo.setLoginAttempts(dc.getLoginAttempts()); //TODO [rafa] ??? vo.setNetworks(dc.getN); vo.setPasswordHash(dc.getPasswordHash()); vo.setPasswordSalt(dc.getPasswordSalt()); vo.setRole(dc.getRole()); vo.setStatus(dc.getStatus()); vo.setIntroReviewed(dc.getIntroReviewed()); vo.setAllDeviceTypesAvailable(dc.getAllDeviceTypesAvailable()); } return vo; }
@Transactional(propagation = Propagation.REQUIRED) public UserVO createUser(@NotNull UserVO user, String password) { hiveValidator.validate(user); if (user.getId() != null) { throw new IllegalParametersException(Messages.ID_NOT_ALLOWED); if (user.getRole() == null ) { throw new IllegalParametersException(Messages.INVALID_USER_ROLE); if (user.getStatus() == null) { user.setStatus(UserStatus.ACTIVE); final String userLogin = StringUtils.trim(user.getLogin()); user.setLogin(userLogin); Optional<UserVO> existing = userDao.findByName(user.getLogin()); if (existing.isPresent()) { throw new ActionNotAllowedException(Messages.DUPLICATE_LOGIN); String salt = passwordService.generateSalt(); String hash = passwordService.hashPassword(password, salt); user.setPasswordSalt(salt); user.setPasswordHash(hash); } else { throw new IllegalParametersException(Messages.PASSWORD_VALIDATION_FAILED); user.setLoginAttempts(Constants.INITIAL_LOGIN_ATTEMPTS); if (user.getIntroReviewed() == null) { user.setIntroReviewed(false); if (user.getAllDeviceTypesAvailable() == null) {
public UserVO convertTo() { UserVO result = new UserVO(); if (login != null) { result.setLogin(login); } if (data != null) { result.setData(data); } if (introReviewed != null) { result.setIntroReviewed(introReviewed); } if (allDeviceTypesAvailable != null) { result.setAllDeviceTypesAvailable(allDeviceTypesAvailable); } result.setStatus(getStatusEnum()); result.setRole(getRoleEnum()); return result; } }
private UserVO updateStatisticOnSuccessfulLogin(UserVO user, long loginTimeout) { boolean update = false; if (user.getLoginAttempts() != 0) { update = true; user.setLoginAttempts(0); } if (user.getLastLogin() == null || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout) { update = true; user.setLastLogin(timestampService.getDate()); } return update ? userDao.merge(user) : user; }
protected Optional<UserVO> checkPassword(UserVO user, String password) { boolean validPassword = passwordService.checkPassword(password, user.getPasswordSalt(), user.getPasswordHash()); long loginTimeout = configurationService.getLong(Constants.LAST_LOGIN_TIMEOUT, Constants.LAST_LOGIN_TIMEOUT_DEFAULT); boolean mustUpdateLoginStatistic = user.getLoginAttempts() != 0 || user.getLastLogin() == null || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout; if (validPassword && mustUpdateLoginStatistic) { UserVO user1 = updateStatisticOnSuccessfulLogin(user, loginTimeout); return of(user1); } else if (!validPassword) { user.setLoginAttempts(user.getLoginAttempts() + 1); if (user.getLoginAttempts() >= configurationService.getInt(Constants.MAX_LOGIN_ATTEMPTS, Constants.MAX_LOGIN_ATTEMPTS_DEFAULT)) { user.setStatus(UserStatus.LOCKED_OUT); logger.info("User with login {} has been locked out after {} login attempts.", user.getLogin(), user.getLoginAttempts()); user.setLoginAttempts(0); } userDao.merge(user); return empty(); } return of(user); }
public static UserVO convertToVo(User dc) { UserVO vo = null; if (dc != null) { vo = new UserVO(); vo.setData(dc.getData()); vo.setId(dc.getId()); vo.setLastLogin(dc.getLastLogin()); vo.setLogin(dc.getLogin()); vo.setLoginAttempts(dc.getLoginAttempts()); //TODO [rafa] ??? vo.setNetworks(dc.getN); vo.setPasswordHash(dc.getPasswordHash()); vo.setPasswordSalt(dc.getPasswordSalt()); vo.setRole(dc.getRole()); vo.setStatus(dc.getStatus()); vo.setIntroReviewed(dc.getIntroReviewed()); vo.setAllDeviceTypesAvailable(dc.getAllDeviceTypesAvailable()); } return vo; }
final boolean isClient = UserRole.CLIENT.equals(curUser.getRole()); if (isClient) { if (userToUpdate.getLogin().isPresent() || Optional<UserVO> withSuchLogin = userDao.findByName(newLogin); if (withSuchLogin.isPresent() && !withSuchLogin.get().getId().equals(id)) { throw new ActionNotAllowedException(Messages.DUPLICATE_LOGIN); existing.setLogin(newLogin); existing.setPasswordSalt(salt); existing.setPasswordHash(hash); existing.setRole(userToUpdate.getRoleEnum()); existing.setStatus(userToUpdate.getStatusEnum()); existing.setData(userToUpdate.getData().orElse(null)); existing.setIntroReviewed(userToUpdate.getIntroReviewed().get());
@Override public long hasAccessToDevice(UserVO user, String deviceId) { return createNamedQuery(Long.class, "User.hasAccessToDevice", empty()) .setParameter("user", user.getId()) .setParameter("deviceId", deviceId) .getSingleResult(); }
Long idForFiltering = user.isAdmin() ? null : user.getId(); if (user.getAllDeviceTypesAvailable()) { idForFiltering = null;
/** * {@inheritDoc} */ @Override public Response getUser(Long userId) { UserVO currentLoggedInUser = findCurrentUserFromAuthContext(); UserWithNetworkVO fetchedUser = null; if (currentLoggedInUser != null && currentLoggedInUser.getRole() == UserRole.ADMIN) { fetchedUser = userService.findUserWithNetworks(userId); } else if (currentLoggedInUser != null && currentLoggedInUser.getRole() == UserRole.CLIENT && Objects.equals(currentLoggedInUser.getId(), userId)) { fetchedUser = userService.findUserWithNetworks(currentLoggedInUser.getId()); } else { return ResponseFactory.response(FORBIDDEN, new ErrorResponse(NOT_FOUND.getStatusCode(), String.format(Messages.USER_NOT_FOUND, userId))); } if (fetchedUser == null) { logger.error("Can't get user with id {}: user not found", userId); return ResponseFactory.response(NOT_FOUND, new ErrorResponse(NOT_FOUND.getStatusCode(), String.format(Messages.USER_NOT_FOUND, userId))); } return ResponseFactory.response(OK, fetchedUser, JsonPolicyDef.Policy.USER_PUBLISHED); }
@Transactional(propagation = Propagation.SUPPORTS) public boolean hasAccessToDevice(UserVO user, String deviceId) { if (!user.isAdmin()) { long count = userDao.hasAccessToDevice(user, deviceId); return count > 0; } return true; }
public static Predicate[] deviceTypeListPredicates(CriteriaBuilder cb, Root<DeviceType> from, Optional<String> nameOpt, Optional<String> namePatternOpt, Optional<HivePrincipal> principalOpt) { List<Predicate> predicates = new LinkedList<>(); nameOpt.ifPresent(name -> predicates.add(cb.equal(from.get("name"), name))); namePatternOpt.ifPresent(pattern -> predicates.add(cb.like(from.get("name"), pattern))); principalOpt.flatMap(principal -> { UserVO user = principal.getUser(); return ofNullable(user); }).ifPresent(user -> { if (!user.isAdmin() && !user.getAllDeviceTypesAvailable()) { User usr = User.convertToEntity(user); predicates.add(from.join("users").in(usr)); } }); principalOpt.flatMap(principal -> { Set<Long> deviceTypes = principal.getDeviceTypeIds(); return ofNullable(deviceTypes); }).ifPresent(deviceTypes -> predicates.add(from.<Long>get("id").in(deviceTypes))); return predicates.toArray(new Predicate[predicates.size()]); }
if (userJwtPayload.getUserId() != null) { userVO = userService.findById(userJwtPayload.getUserId()); if (!UserStatus.ACTIVE.equals(userVO.getStatus())) { throw new BadCredentialsException("Unauthorized: user is not active"); if (!userVO.getAllDeviceTypesAvailable()) { principal.setAllDeviceTypesAvailable(false); if (deviceTypeIds.contains("*")) { principal.setAllDeviceTypesAvailable(true); } else if (userVO != null && userVO.getAllDeviceTypesAvailable()) { principal.setAllDeviceTypesAvailable(true); } else {
@Transactional(noRollbackFor = InvalidPrincipalException.class) public UserVO getActiveUser(String login, String password) { Optional<UserVO> userOpt = userDao.findByName(login); if (!userOpt.isPresent()) { logger.error("Can't find user with login {} and password {}", login, password); throw new InvalidPrincipalException(String.format(Messages.USER_LOGIN_NOT_FOUND, login)); } else if (userOpt.get().getStatus() != UserStatus.ACTIVE) { logger.error("User with login {} is not active", login); throw new InvalidPrincipalException(Messages.USER_NOT_ACTIVE); } return checkPassword(userOpt.get(), password) .orElseThrow(() -> new InvalidPrincipalException(String.format(Messages.INCORRECT_CREDENTIALS, login))); }
@Override public String getName() { if (user != null) { return user.getLogin(); } if (actions != null) { return actions.toString(); } if (networkIds != null) { return networkIds.toString(); } if (deviceTypeIds != null) { return deviceTypeIds.toString(); } return "anonymousPrincipal"; }
@Transactional(propagation = Propagation.SUPPORTS) public List<DeviceVO> getAllowedExistingDevices(Set<String> deviceIds, HivePrincipal principal) { List<DeviceVO> devices = findByIdWithPermissionsCheck(deviceIds, principal); Set<String> allowedIds = devices.stream() .map(DeviceVO::getDeviceId) .collect(Collectors.toSet()); Set<String> unresolvedIds = Sets.difference(deviceIds, allowedIds); if (unresolvedIds.isEmpty()) { return devices; } if (UserRole.ADMIN.equals(principal.getUser().getRole())) { throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, unresolvedIds), SC_NOT_FOUND); } else { throw new HiveException(Messages.ACCESS_DENIED, SC_FORBIDDEN); } }
/** * Allows user access to given device type * * @param userId id of user * @param deviceTypeId id of device type */ @Transactional(propagation = Propagation.REQUIRED) public void assignDeviceType(@NotNull long userId, @NotNull long deviceTypeId) { UserVO existingUser = userDao.find(userId); if (existingUser == null) { logger.error("Can't assign device type with id {}: user {} not found", deviceTypeId, userId); throw new HiveException(String.format(Messages.USER_NOT_FOUND, userId), NOT_FOUND.getStatusCode()); } if (existingUser.getAllDeviceTypesAvailable()) { throw new HiveException(String.format(Messages.DEVICE_TYPE_ASSIGNMENT_NOT_ALLOWED, userId), FORBIDDEN.getStatusCode()); } DeviceTypeWithUsersAndDevicesVO existingDeviceType = deviceTypeDao.findWithUsers(deviceTypeId).orElse(null); if (Objects.isNull(existingDeviceType)) { throw new HiveException(String.format(Messages.DEVICE_TYPE_NOT_FOUND, deviceTypeId), NOT_FOUND.getStatusCode()); } deviceTypeDao.assignToDeviceType(existingDeviceType, existingUser); }
@Override public long hasAccessToNetwork(UserVO user, NetworkVO network) { Network nw = reference(Network.class, network.getId()); return createNamedQuery(Long.class, "User.hasAccessToNetwork", empty()) .setParameter("user", user.getId()) .setParameter("network", nw) .getSingleResult(); }