@Transactional
 public AccessKey updateAccessKeyFromOAuthGrant(OAuthGrant grant, User user, Date now) {
   AccessKey existing = find(grant.getAccessKey().getId(), user.getId());
   deleteAccessKeyPermissions(existing);
   if (grant.getAccessType().equals(AccessType.ONLINE)) {
     Date expirationDate = new Date(now.getTime() + 600000); // the key is valid for 10 minutes
     existing.setExpirationDate(expirationDate);
   } else {
     existing.setExpirationDate(null);
   }
   existing.setLabel(
       String.format(
           Messages.OAUTH_GRANT_TOKEN_LABEL,
           grant.getClient().getName(),
           System.currentTimeMillis()));
   Set<AccessKeyPermission> permissions = new HashSet<>();
   AccessKeyPermission permission = new AccessKeyPermission();
   permission.setDomainArray(grant.getClient().getDomain());
   permission.setActionsArray(StringUtils.split(grant.getScope(), ' '));
   permission.setSubnetsArray(grant.getClient().getSubnet());
   permission.setNetworkIds(grant.getNetworkIds());
   permissions.add(permission);
   existing.setPermissions(permissions);
   AccessKeyProcessor keyProcessor = new AccessKeyProcessor();
   String key = keyProcessor.generateKey();
   existing.setKey(key);
   for (AccessKeyPermission current : permissions) {
     current.setAccessKey(existing);
     genericDAO.persist(current);
   }
   return existing;
 }
 @Transactional
 public AccessKey createAccessKeyFromOAuthGrant(OAuthGrant grant, User user, Date now) {
   AccessKey newKey = new AccessKey();
   newKey.setType(AccessKeyType.OAUTH);
   if (grant.getAccessType().equals(AccessType.ONLINE)) {
     Date expirationDate = new Date(now.getTime() + 600000); // the key is valid for 10 minutes
     newKey.setExpirationDate(expirationDate);
   }
   newKey.setUser(user);
   newKey.setLabel(
       String.format(
           Messages.OAUTH_GRANT_TOKEN_LABEL,
           grant.getClient().getName(),
           System.currentTimeMillis()));
   Set<AccessKeyPermission> permissions = new HashSet<>();
   AccessKeyPermission permission = new AccessKeyPermission();
   permission.setDomainArray(grant.getClient().getDomain());
   permission.setActionsArray(StringUtils.split(grant.getScope(), ' '));
   permission.setSubnetsArray(grant.getClient().getSubnet());
   permission.setNetworkIds(grant.getNetworkIds());
   permissions.add(permission);
   newKey.setPermissions(permissions);
   create(user, newKey);
   return newKey;
 }
  @Transactional(propagation = Propagation.REQUIRED)
  public AccessKey authenticate(@NotNull User user) {
    userService.refreshUserLoginData(user);

    AccessKey accessKey = authenticationUtils.prepareAccessKey(user);

    Set<AccessKeyPermission> permissions = new HashSet<>();
    final AccessKeyPermission permission = authenticationUtils.preparePermission(user.getRole());
    permissions.add(permission);
    accessKey.setPermissions(permissions);
    genericDAO.persist(accessKey);

    permission.setAccessKey(accessKey);
    genericDAO.persist(permission);
    return accessKey;
  }
 @Transactional(propagation = Propagation.SUPPORTS)
 public boolean hasAccessToNetwork(AccessKey accessKey, Network targetNetwork) {
   Set<AccessKeyPermission> permissions = accessKey.getPermissions();
   User user = accessKey.getUser();
   boolean hasNullPermission =
       permissions.stream().anyMatch(perm -> perm.getNetworkIdsAsSet() == null);
   if (hasNullPermission) {
     return userService.hasAccessToNetwork(user, targetNetwork);
   } else {
     Set<Long> allowedNetworks =
         permissions
             .stream()
             .map(AccessKeyPermission::getNetworkIdsAsSet)
             .flatMap(Collection::stream)
             .collect(Collectors.toSet());
     user = userService.findUserWithNetworks(user.getId());
     return allowedNetworks.contains(targetNetwork.getId())
         && (user.isAdmin() || user.getNetworks().contains(targetNetwork));
   }
 }
  @Transactional(propagation = Propagation.SUPPORTS)
  public boolean hasAccessToDevice(AccessKey accessKey, String deviceGuid) {
    Set<AccessKeyPermission> permissions = accessKey.getPermissions();
    Set<String> allowedDevices = new HashSet<>();
    Set<Long> allowedNetworks = new HashSet<>();

    User accessKeyUser = userService.findUserWithNetworks(accessKey.getUser().getId());
    Set<AccessKeyPermission> toRemove = new HashSet<>();

    Device device =
        genericDAO
            .createNamedQuery(Device.class, "Device.findByUUID", of(CacheConfig.refresh()))
            .setParameter("guid", deviceGuid)
            .getSingleResult();

    for (AccessKeyPermission currentPermission : permissions) {
      if (currentPermission.getDeviceGuidsAsSet() == null) {
        allowedDevices.add(null);
      } else {
        if (!currentPermission.getDeviceGuidsAsSet().contains(deviceGuid)) {
          toRemove.add(currentPermission);
        } else {
          allowedDevices.addAll(currentPermission.getDeviceGuidsAsSet());
        }
      }
      if (currentPermission.getNetworkIdsAsSet() == null) {
        allowedNetworks.add(null);
      } else {
        if (device.getNetwork() != null) {
          if (!currentPermission.getNetworkIdsAsSet().contains(device.getNetwork().getId())) {
            toRemove.add(currentPermission);
          } else {
            allowedNetworks.addAll(currentPermission.getNetworkIdsAsSet());
          }
        }
      }
    }
    permissions.removeAll(toRemove);
    boolean hasAccess;
    hasAccess =
        allowedDevices.contains(null)
            ? userService.hasAccessToDevice(accessKeyUser, device.getGuid())
            : allowedDevices.contains(device.getGuid())
                && userService.hasAccessToDevice(accessKeyUser, device.getGuid());

    hasAccess =
        hasAccess && allowedNetworks.contains(null)
            ? accessKeyUser.isAdmin() || accessKeyUser.getNetworks().contains(device.getNetwork())
            : (accessKeyUser.isAdmin() || accessKeyUser.getNetworks().contains(device.getNetwork()))
                && allowedNetworks.contains(device.getNetwork().getId());

    return hasAccess;
  }