@Override public long hasAccessToDevice(UserVO user, String deviceId) { return createNamedQuery(Long.class, "User.hasAccessToDevice", empty()) .setParameter("user", user.getId()) .setParameter("deviceId", deviceId) .getSingleResult(); }
@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(); }
private Long getCreatorId(String topic, UserVO user) { if (topic.equals("*")) { return user.isAdmin() ? user.getId() : null; } PluginVO pluginVO = pluginService.findByTopic(topic); return Optional.ofNullable(pluginVO) .map(plugin -> plugin.getUserId()) .orElse(null); }
@Override public void unassignDeviceType(@NotNull UserVO existingUser, @NotNull long deviceTypeId) { createNamedQuery(DeviceType.class, "DeviceType.findWithUsers", of(CacheConfig.refresh())) .setParameter("id", deviceTypeId) .getResultList() .stream().findFirst() .ifPresent(existingDeviceType -> { User usr = new User(); usr.setId(existingUser.getId()); existingDeviceType.getUsers().remove(usr); merge(existingDeviceType); }); }
@Override public Response getCurrent() { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Long id = principal.getUser().getId(); UserVO currentUser = userService.findUserWithNetworks(id); if (currentUser == null) { return ResponseFactory.response(CONFLICT, new ErrorResponse(CONFLICT.getStatusCode(), Messages.CAN_NOT_GET_CURRENT_USER)); } return ResponseFactory.response(OK, currentUser, JsonPolicyDef.Policy.USER_PUBLISHED); }
@Override public void unassignNetwork(@NotNull UserVO existingUser, @NotNull long networkId) { createNamedQuery(Network.class, "Network.findWithUsers", of(CacheConfig.refresh())) .setParameter("id", networkId) .getResultList() .stream().findFirst() .ifPresent(existingNetwork -> { User usr = new User(); usr.setId(existingUser.getId()); existingNetwork.getUsers().remove(usr); merge(existingNetwork); }); }
@Override public void count(String name, String namePattern, String topicName, Integer status, Long userId, AsyncResponse asyncResponse) { logger.debug("Plugin count requested"); HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserVO user = principal.getUser(); if (!user.isAdmin() && userId != null && !userId.equals(user.getId())) { logger.warn(Messages.NO_ACCESS_TO_PLUGIN); final Response response = ResponseFactory.response(FORBIDDEN, new ErrorResponse(FORBIDDEN.getStatusCode(), Messages.NO_ACCESS_TO_PLUGIN)); asyncResponse.resume(response); } else { pluginRegisterService.count(name, namePattern, topicName, status, userId, principal) .thenApply(count -> { logger.debug("Plugin count request proceed successfully"); return ResponseFactory.response(OK, count, JsonPolicyDef.Policy.PLUGINS_LISTED); }).thenAccept(asyncResponse::resume); } }
@HiveWebsocketAuth @PreAuthorize("isAuthenticated() and hasPermission(null, 'UPDATE_CURRENT_USER')") public void processUserUpdateCurrent(JsonObject request, WebSocketSession session) { UserUpdate user = gson.fromJson(request.get(USER), UserUpdate.class); if (user == null) { logger.error(Messages.USER_REQUIRED); throw new HiveException(Messages.USER_REQUIRED, BAD_REQUEST.getStatusCode()); } UserVO curUser = findCurrentUserFromAuthContext(); userService.updateUser(curUser.getId(), user, curUser); clientHandler.sendMessage(request, new WebSocketResponse(), session); }
@HiveWebsocketAuth @PreAuthorize("isAuthenticated() and hasPermission(null, 'MANAGE_USER')") public void processUserDelete(JsonObject request, WebSocketSession session) { Long userId = gson.fromJson(request.get(USER_ID), Long.class); if (userId == null) { logger.error(Messages.USER_ID_REQUIRED); throw new HiveException(Messages.USER_ID_REQUIRED, BAD_REQUEST.getStatusCode()); } HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserVO currentUser = null; if (principal.getUser() != null) { currentUser = principal.getUser(); } if (currentUser != null && currentUser.getId().equals(userId)) { logger.error("Rejected removing current user"); throw new HiveException(Messages.CANT_DELETE_CURRENT_USER_KEY, FORBIDDEN.getStatusCode()); } boolean isDeleted = userService.deleteUser(userId); if (!isDeleted) { logger.error(String.format(Messages.USER_NOT_FOUND, userId)); throw new HiveException(String.format(Messages.USER_NOT_FOUND, userId), NOT_FOUND.getStatusCode()); } clientHandler.sendMessage(request, new WebSocketResponse(), session); }
@Override public Response updateCurrentUser(UserUpdate user) { UserVO curUser = findCurrentUserFromAuthContext(); userService.updateUser(curUser.getId(), user, curUser); return ResponseFactory.response(NO_CONTENT); }
@Override public void register(PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization, @Suspended final AsyncResponse asyncResponse) { hiveValidator.validate(pluginUpdate); try { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); pluginRegisterService.register(principal.getUser().getId(), pluginReqisterQuery, pluginUpdate, authorization) .thenAccept(asyncResponse::resume); } catch (ServiceUnavailableException e) { logger.warn(HEALTH_CHECK_FAILED); asyncResponse.resume(ResponseFactory.response(BAD_REQUEST, new ErrorResponse(BAD_REQUEST.getStatusCode(), HEALTH_CHECK_FAILED))); } }
@Override public void assignToNetwork(NetworkVO network, UserVO user) { assert network != null && network.getId() != null; assert user != null && user.getId() != null; Network existing = find(Network.class, network.getId()); User userReference = reference(User.class, user.getId()); if (existing.getUsers() == null) { existing.setUsers(new HashSet<>()); } existing.getUsers().add(userReference); super.merge(existing); }
@Override public void assignToDeviceType(DeviceTypeVO deviceType, UserVO user) { assert deviceType != null && deviceType.getId() != null; assert user != null && user.getId() != null; DeviceType existing = find(DeviceType.class, deviceType.getId()); User userReference = reference(User.class, user.getId()); if (existing.getUsers() == null) { existing.setUsers(new HashSet<>()); } existing.getUsers().add(userReference); super.merge(existing); }
@HiveWebsocketAuth @PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_CURRENT_USER')") public void processUserGetCurrent(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Long id = principal.getUser().getId(); UserVO currentUser = userService.findUserWithNetworks(id); if (currentUser == null) { clientHandler.sendErrorResponse(request, CONFLICT.getStatusCode(), Messages.CAN_NOT_GET_CURRENT_USER, session); } else { WebSocketResponse response = new WebSocketResponse(); response.addValue(CURRENT_USER, currentUser, USER_PUBLISHED); clientHandler.sendMessage(request, response, session); } }
/** * {@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); }
@SuppressWarnings("unchecked") private static List<Predicate> deviceSpecificPrincipalPredicates(CriteriaBuilder cb, Root<Device> from, Optional<HivePrincipal> principal) { final List<Predicate> predicates = new LinkedList<>(); final Join<Device, Network> networkJoin = (Join) from.fetch("network", JoinType.LEFT); final Join<Device, DeviceType> deviceTypeJoin = (Join) from.fetch("deviceType", JoinType.LEFT); principal.ifPresent(p -> { UserVO user = p.getUser(); if (user != null && !user.isAdmin()) { // Joining after check to prevent duplicate objects final Join<Device, Network> usersJoin = (Join) networkJoin.fetch("users", JoinType.LEFT); predicates.add(cb.equal(usersJoin.<Long>get("id"), user.getId())); } if (p.getNetworkIds() != null) { predicates.add(networkJoin.<Long>get("id").in(p.getNetworkIds())); } if (p.getDeviceTypeIds() != null) { predicates.add(deviceTypeJoin.<Long>get("id").in(p.getDeviceTypeIds())); } }); return predicates; } }
private static List<Predicate> deviceCountPrincipalPredicates(CriteriaBuilder cb, Root<Device> from, Optional<HivePrincipal> principal) { final List<Predicate> predicates = new LinkedList<>(); final Join<Device, Network> networkJoin = from.join("network", JoinType.LEFT); final Join<Device, DeviceType> deviceTypeJoin = from.join("deviceType", JoinType.LEFT); principal.ifPresent(p -> { UserVO user = p.getUser(); if (user != null && !user.isAdmin()) { // Joining after check to prevent duplicate objects final Join<Device, Network> usersJoin = networkJoin.join("users", JoinType.LEFT); predicates.add(cb.equal(usersJoin.<Long>get("id"), user.getId())); } if (p.getNetworkIds() != null) { predicates.add(networkJoin.<Long>get("id").in(p.getNetworkIds())); } if (p.getDeviceTypeIds() != null) { predicates.add(deviceTypeJoin.<Long>get("id").in(p.getDeviceTypeIds())); } }); return predicates; }
public static UserWithNetworkVO fromUserVO(UserVO dc) { UserWithNetworkVO vo = null; if (dc != null) { vo = new UserWithNetworkVO(); vo.setData(dc.getData()); vo.setId(dc.getId()); vo.setData(dc.getData()); vo.setLastLogin(dc.getLastLogin()); vo.setLogin(dc.getLogin()); vo.setLoginAttempts(dc.getLoginAttempts()); vo.setNetworks(new HashSet<>()); 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; }
public static UserWithDeviceTypeVO fromUserVO(UserVO dc) { UserWithDeviceTypeVO vo = null; if (dc != null) { vo = new UserWithDeviceTypeVO(); vo.setData(dc.getData()); vo.setId(dc.getId()); vo.setData(dc.getData()); vo.setLastLogin(dc.getLastLogin()); vo.setLogin(dc.getLogin()); vo.setLoginAttempts(dc.getLoginAttempts()); vo.setDeviceTypes(new HashSet<>()); 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; }
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; }