Example #1
0
  @Override
  public void authenticate(AuthenticationFlowContext context) {
    if (!isConfigured(context.getSession(), context.getRealm(), context.getUser())) {
      if (context.getExecution().isOptional()) {
        context.attempted();
      } else if (context.getExecution().isRequired()) {
        context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
        Response challengeResponse =
            errorResponse(
                Response.Status.UNAUTHORIZED.getStatusCode(),
                "invalid_grant",
                "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
      }
      return;
    }
    String otp = retrieveOTP(context);
    if (otp == null) {
      if (context.getUser() != null) {
        context.getEvent().user(context.getUser());
      }
      context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
      Response challengeResponse =
          errorResponse(
              Response.Status.UNAUTHORIZED.getStatusCode(),
              "invalid_grant",
              "Invalid user credentials");
      context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
      return;
    }
    boolean valid =
        context
            .getSession()
            .userCredentialManager()
            .isValid(
                context.getRealm(),
                context.getUser(),
                UserCredentialModel.otp(context.getRealm().getOTPPolicy().getType(), otp));
    if (!valid) {
      context.getEvent().user(context.getUser());
      context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
      Response challengeResponse =
          errorResponse(
              Response.Status.UNAUTHORIZED.getStatusCode(),
              "invalid_grant",
              "Invalid user credentials");
      context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
      return;
    }

    context.success();
  }
Example #2
0
  public KeystoneAccess createToken(KeystoneAuthCredentials credentials)
      throws KeystoneServerException, KeystoneConnectionException, KeystoneUnauthorizedException {

    Client client = Client.create(clientConfig);
    WebResource resource = client.resource(getTokensUrl());

    try {
      return resource
          .type(MediaType.APPLICATION_JSON)
          .accept(MediaType.APPLICATION_JSON)
          .post(KeystoneAccess.class, credentials);
    } catch (UniformInterfaceException e) {
      if (e.getResponse().getStatus() == Response.Status.BAD_REQUEST.getStatusCode()) {
        String err = "Keystone v2 login credentials invalid " + credentials.toString();
        log.warn(err);
        throw new KeystoneUnauthorizedException(err, e);
      } else if (e.getResponse().getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {
        String err = "Keystone v2 login credentials not found " + credentials.toString();
        log.warn(err, credentials);
        throw new KeystoneUnauthorizedException(err, e);
      } else {
        throw new KeystoneServerException("Keystone server error", e, e.getResponse().getStatus());
      }
    } catch (ClientHandlerException e) {
      throw new KeystoneConnectionException(
          "Could not connect to Keystone server. Uri=" + resource.getURI(), e);
    }
  }
 @PUT
 @Path("device/{deviceId}/policy")
 public Response updatePolicy(
     @PathParam("deviceId") String deviceId,
     @QueryParam("protocol") String protocol,
     @FormParam("policy") String policy) {
   String protocolString = protocol.toUpperCase();
   if (log.isDebugEnabled()) {
     log.debug(
         "Sending request to update-policy of device [" + deviceId + "] via " + protocolString);
   }
   try {
     if (!APIUtil.getDeviceAccessAuthorizationService()
         .isUserAuthorized(
             new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
             DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS)) {
       return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
     }
     PrivateKey serverPrivateKey = VirtualFirealarmSecurityManager.getServerPrivateKey();
     String actualMessage = VirtualFireAlarmConstants.POLICY_CONTEXT + ":" + policy;
     String encryptedMsg =
         VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, serverPrivateKey);
     Map<String, String> dynamicProperties = new HashMap<>();
     switch (protocolString) {
       case XMPP_PROTOCOL:
         dynamicProperties.put(
             VirtualFireAlarmConstants.JID_PROPERTY_KEY,
             deviceId + "@" + XmppConfig.getInstance().getServerName());
         dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "POLICTY-REQUEST");
         dynamicProperties.put(
             VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
             VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
         APIUtil.getOutputEventAdapterService()
             .publish(
                 VirtualFireAlarmConstants.XMPP_ADAPTER_NAME, dynamicProperties, encryptedMsg);
         break;
       default:
         String publishTopic =
             APIUtil.getTenantDomainOftheUser()
                 + "/"
                 + VirtualFireAlarmConstants.DEVICE_TYPE
                 + "/"
                 + deviceId;
         dynamicProperties.put(VirtualFireAlarmConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
         APIUtil.getOutputEventAdapterService()
             .publish(
                 VirtualFireAlarmConstants.MQTT_ADAPTER_NAME, dynamicProperties, encryptedMsg);
         break;
     }
     return Response.ok().build();
   } catch (DeviceAccessAuthorizationException e) {
     log.error(e.getErrorMessage(), e);
     return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
   } catch (VirtualFireAlarmException e) {
     log.error(e);
     return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
   }
 }
 @Test
 public void testErrorChangeUserInfo() {
   final JSONObject jsonObject = new JSONObject();
   jsonObject.put("login", faker.name().firstName());
   jsonObject.put("password", faker.name().lastName());
   jsonObject.put("email", faker.internet().emailAddress());
   jsonObject.put("imgData", "");
   final Response json =
       target("user")
           .path("1")
           .request(MediaType.APPLICATION_JSON)
           .post(Entity.json(jsonObject.toString()));
   assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), json.getStatus());
 }
Example #5
0
  /**
   * Authenticates a user session.
   *
   * @param req The HTTP request.
   * @param creds The credentials with which to authenticate.
   * @return The authenticated user or null if authentication fails.
   * @throws WebApplicationException If the user is not authenticated.
   */
  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @Description("Authenticates a user session.")
  @Path("/login")
  public PrincipalUserDto login(@Context HttpServletRequest req, final CredentialsDto creds) {
    try {
      PrincipalUserDto result = null;
      PrincipalUser user = authService.getUser(creds.getUsername(), creds.getPassword());

      if (user != null) {
        result = PrincipalUserDto.transformToDto(user);
      } else {
        throw new WebApplicationException(
            Response.Status.UNAUTHORIZED.getReasonPhrase(), Response.Status.UNAUTHORIZED);
      }
      req.getSession(true).setAttribute(AuthFilter.USER_ATTRIBUTE_NAME, result);
      return result;
    } catch (Exception ex) {
      throw new WebApplicationException(
          Response.Status.UNAUTHORIZED.getReasonPhrase(), Response.Status.UNAUTHORIZED);
    }
  }
 @Path("device/stats/{deviceId}")
 @GET
 @Consumes("application/json")
 @Produces("application/json")
 public Response getVirtualFirealarmStats(
     @PathParam("deviceId") String deviceId,
     @QueryParam("from") long from,
     @QueryParam("to") long to) {
   String fromDate = String.valueOf(from);
   String toDate = String.valueOf(to);
   String query =
       "deviceId:"
           + deviceId
           + " AND deviceType:"
           + VirtualFireAlarmConstants.DEVICE_TYPE
           + " AND time : ["
           + fromDate
           + " TO "
           + toDate
           + "]";
   String sensorTableName = VirtualFireAlarmConstants.TEMPERATURE_EVENT_TABLE;
   try {
     if (!APIUtil.getDeviceAccessAuthorizationService()
         .isUserAuthorized(
             new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
             DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
       return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
     }
     List<SortByField> sortByFields = new ArrayList<>();
     SortByField sortByField = new SortByField("time", SORT.ASC, false);
     sortByFields.add(sortByField);
     List<SensorRecord> sensorRecords =
         APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
     return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
   } catch (AnalyticsException e) {
     String errorMsg =
         "Error on retrieving stats on table " + sensorTableName + " with query " + query;
     log.error(errorMsg);
     return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
         .entity(errorMsg)
         .build();
   } catch (DeviceAccessAuthorizationException e) {
     log.error(e.getErrorMessage(), e);
     return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
   }
 }
Example #7
0
  @SuppressWarnings("unchecked")
  @Test
  public void testGetAllHidden() {
    // invalid request
    Response response = service.getAllHidden(null);
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // invalid request
    response = service.getAllHidden(new RequestBean<Object>(null, null));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // invalid request
    response = service.getAllHidden(new RequestBean<Object>(new CredentialsBean(), null));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // valid request but unauthorized
    response =
        service.getAllHidden(
            new RequestBean<Object>(new CredentialsBean("admin", "password"), null));
    assertNotNull(response);
    assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), response.getStatus());

    // valid request
    response =
        service.getAllHidden(
            new RequestBean<Object>(new CredentialsBean("manager", "password"), null));
    assertNotNull(response);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    List<MenuItemBean> menuItems = (ArrayList<MenuItemBean>) response.getEntity();
    assertNotNull(menuItems);
    assertEquals(1, menuItems.size());
  }
 @Test
 public void testErrorCheckAuth() {
   final Response json = target("session").request(MediaType.APPLICATION_JSON).get();
   assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), json.getStatus());
 }
 @Test
 public void testErrorGetUserById() {
   final Response json = target("user").path("1000").request(MediaType.APPLICATION_JSON).get();
   assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), json.getStatus());
 }
Example #10
0
    public String requestString(
        int timeout, String url, String method, Object body, Pair<String, ?>... parameters)
        throws IOException, ServerException, ForbiddenException, NotFoundException,
            UnauthorizedException, ConflictException {
      final String authToken = getAuthenticationToken();
      if ((parameters != null && parameters.length > 0) || authToken != null) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        // remove sensitive information from url.
        ub.replaceQueryParam("token", null);

        if (parameters != null && parameters.length > 0) {
          for (Pair<String, ?> parameter : parameters) {
            String name = URLEncoder.encode(parameter.first, "UTF-8");
            String value =
                parameter.second == null
                    ? null
                    : URLEncoder.encode(String.valueOf(parameter.second), "UTF-8");
            ub.replaceQueryParam(name, value);
          }
        }
        url = ub.build().toString();
      }
      final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
      conn.setReadTimeout(timeout > 0 ? timeout : 60000);
      try {
        conn.setRequestMethod(method);
        // drop a hint for server side that we want to receive application/json
        conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (authToken != null) {
          conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
        }
        if (body != null) {
          conn.addRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
          conn.setDoOutput(true);

          if (HttpMethod.DELETE.equals(
              method)) { // to avoid jdk bug described here
                         // http://bugs.java.com/view_bug.do?bug_id=7157360
            conn.setRequestMethod(HttpMethod.POST);
            conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
          }

          try (OutputStream output = conn.getOutputStream()) {
            output.write(DtoFactory.getInstance().toJson(body).getBytes());
          }
        }

        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
          InputStream in = conn.getErrorStream();
          if (in == null) {
            in = conn.getInputStream();
          }
          final String str;
          try (Reader reader = new InputStreamReader(in)) {
            str = CharStreams.toString(reader);
          }
          final String contentType = conn.getContentType();
          if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
            final ServiceError serviceError =
                DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
            if (serviceError.getMessage() != null) {
              if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                throw new ForbiddenException(serviceError);
              } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                throw new NotFoundException(serviceError);
              } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                throw new UnauthorizedException(serviceError);
              } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
                throw new ConflictException(serviceError);
              } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                throw new ServerException(serviceError);
              }
              throw new ServerException(serviceError);
            }
          }
          // Can't parse content as json or content has format other we expect for error.
          throw new IOException(
              String.format(
                  "Failed access: %s, method: %s, response code: %d, message: %s",
                  UriBuilder.fromUri(url).replaceQuery("token").build(),
                  method,
                  responseCode,
                  str));
        }
        final String contentType = conn.getContentType();
        if (!(contentType == null || contentType.startsWith(MediaType.APPLICATION_JSON))) {
          throw new IOException(conn.getResponseMessage());
        }

        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
          return CharStreams.toString(reader);
        }
      } finally {
        conn.disconnect();
      }
    }
  @POST
  @Path("device/{deviceId}/buzz")
  public Response switchBuzzer(
      @PathParam("deviceId") String deviceId, @FormParam("state") String state) {
    if (state == null || state.isEmpty()) {
      log.error("State is not defined for the buzzer operation");
      return Response.status(Response.Status.BAD_REQUEST).build();
    }
    String switchToState = state.toUpperCase();
    if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON)
        && !switchToState.equals(VirtualFireAlarmConstants.STATE_OFF)) {
      log.error("The requested state change shoud be either - 'ON' or 'OFF'");
      return Response.status(Response.Status.BAD_REQUEST).build();
    }
    try {
      if (!APIUtil.getDeviceAccessAuthorizationService()
          .isUserAuthorized(
              new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
              DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
        return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
      }
      String resource = VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", "");
      PrivateKey serverPrivateKey = VirtualFirealarmSecurityManager.getServerPrivateKey();
      String actualMessage = resource + ":" + switchToState;
      String encryptedMsg =
          VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, serverPrivateKey);
      String publishTopic =
          APIUtil.getTenantDomainOftheUser()
              + "/"
              + VirtualFireAlarmConstants.DEVICE_TYPE
              + "/"
              + deviceId;

      Operation commandOp = new CommandOperation();
      commandOp.setCode("buzz");
      commandOp.setType(Operation.Type.COMMAND);
      commandOp.setEnabled(true);
      commandOp.setPayLoad(encryptedMsg);

      Properties props = new Properties();
      props.setProperty(VirtualFireAlarmConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
      props.setProperty(
          VirtualFireAlarmConstants.CLIENT_JID_PROPERTY_KEY,
          deviceId + "@" + XmppConfig.getInstance().getServerName());
      props.setProperty(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "CONTROL-REQUEST");
      props.setProperty(
          VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
          VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
      commandOp.setProperties(props);

      List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
      deviceIdentifiers.add(new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE));
      APIUtil.getDeviceManagementService()
          .addOperation(VirtualFireAlarmConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
      return Response.ok().build();
    } catch (DeviceAccessAuthorizationException e) {
      log.error(e.getErrorMessage(), e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (VirtualFireAlarmException e) {
      String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "]";
      log.error(errorMsg);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (OperationManagementException e) {
      String msg = "Error occurred while executing command operation upon ringing the buzzer";
      log.error(msg, e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
  }