/**
   * Validates the request by checking for the presence of a pre-configured attribute in the
   * ServletRequest.
   *
   * @param messageInfo {@inheritDoc}
   * @param clientSubject {@inheritDoc}
   * @param serviceSubject {@inheritDoc}
   * @return {@inheritDoc}
   */
  @Override
  public Promise<AuthStatus, AuthenticationException> validateRequest(
      MessageInfoContext messageInfo, Subject clientSubject, Subject serviceSubject) {

    SecurityContextMapper securityContextMapper =
        SecurityContextMapper.fromMessageInfo(messageInfo);
    final JsonValue attributes =
        json(messageInfo.asContext(AttributesContext.class).getAttributes());

    if (attributes.isDefined(authenticationIdAttribute)
        && attributes.get(authenticationIdAttribute).isString()) {
      final String authenticationId = attributes.get(authenticationIdAttribute).asString();
      securityContextMapper.setAuthenticationId(authenticationId);
      clientSubject
          .getPrincipals()
          .add(
              new Principal() {
                public String getName() {
                  return authenticationId;
                }
              });
      return newResultPromise(SUCCESS);
    } else {
      return newResultPromise(SEND_FAILURE);
    }
  }
Example #2
0
 /**
  * Helper function to retrieve a field from the provided request's JSON POST data. This exists for
  * the new-style interfaces, and takes the parameter name as an argument also.
  *
  * @param input JsonValue containing the key "goto" and a paired URL.
  * @param paramName The key whose value to attempt to read.
  * @return The String representation fo the "goto" key's value, or null.
  */
 public String getValueFromJson(JsonValue input, String paramName) {
   if (input == null || !input.isDefined(paramName)) {
     return null;
   } else {
     return input.get(paramName).asString();
   }
 }
  @Override
  protected Map<String, String> getContextsForAccessAttempt(Request request) {
    try {
      String jsonString = request.getEntity().getString();
      if (isNotEmpty(jsonString)) {
        JsonValue jsonValue = toJsonValue(jsonString);
        if (jsonValue.isDefined(AUTH_ID)) {
          populateContextFromAuthId(jsonValue.get(AUTH_ID).asString());
        }
      }
    } catch (IOException e) {
      // Do nothing
    }

    return super.getContextsForAccessAttempt(request);
  }
 @Override
 public Promise<Response, NeverThrowsException> filter(
     Context context, Request request, Handler next) {
   try {
     AttributesContext attributesContext = context.asContext(AttributesContext.class);
     final Issuer issuer = (Issuer) attributesContext.getAttributes().get(ISSUER_KEY);
     if (issuer != null) {
       ClientRegistration cr = heap.get(issuer.getName() + suffix, ClientRegistration.class);
       if (cr == null) {
         if (!config.isDefined("redirect_uris")) {
           throw new RegistrationException(
               "Cannot perform dynamic registration: 'redirect_uris' should be defined");
         }
         if (issuer.getRegistrationEndpoint() == null) {
           throw new RegistrationException(
               format("Registration is not supported by the issuer '%s'", issuer));
         }
         final JsonValue registeredClientConfiguration =
             performDynamicClientRegistration(context, config, issuer.getRegistrationEndpoint());
         cr =
             heap.resolve(
                 createClientRegistrationDeclaration(
                     registeredClientConfiguration, issuer.getName()),
                 ClientRegistration.class);
       }
       attributesContext.getAttributes().put(CLIENT_REG_KEY, cr);
     } else {
       throw new RegistrationException("Cannot retrieve issuer from the context");
     }
   } catch (RegistrationException e) {
     return newResultPromise(newInternalServerError(e));
   } catch (HeapException e) {
     return newResultPromise(
         newInternalServerError(
             "Cannot inject inlined Client Registration declaration to heap", e));
   }
   return next.handle(context, request);
 }
  /**
   * TODO Implement this method
   *
   * <p>{@inheritDoc}
   */
  public Promise<QueryResponse, ResourceException> handleQuery(
      final Context context, final QueryRequest request, final QueryResourceHandler handler) {
    EventEntry measure =
        Publisher.start(
            Name.get(
                "openidm/internal/script/" + this.getScriptEntry().getName().getName() + "/query"),
            null,
            null);
    try {
      final ScriptEntry _scriptEntry = getScriptEntry();
      if (!_scriptEntry.isActive()) {
        throw new ServiceUnavailableException("Inactive script: " + _scriptEntry.getName());
      }
      final Script script = _scriptEntry.getScript(context);
      script.setBindings(script.createBindings());
      customizer.handleQuery(context, request, script.getBindings());

      final Function<Void> queryCallback =
          new Function<Void>() {
            @Override
            public Void call(Parameter scope, Function<?> callback, Object... arguments)
                throws ResourceException, NoSuchMethodException {
              if (arguments.length == 3 && null != arguments[2]) {
                if (arguments[2] instanceof Map) {}

                if (arguments[2] instanceof JsonValue) {

                } else {
                  throw new NoSuchMethodException(
                      FunctionFactory.getNoSuchMethodMessage("callback", arguments));
                }
              } else if (arguments.length >= 2 && null != arguments[1]) {
                if (arguments[1] instanceof Map) {}

                if (arguments[1] instanceof JsonValue) {

                } else {
                  throw new NoSuchMethodException(
                      FunctionFactory.getNoSuchMethodMessage("callback", arguments));
                }
              } else if (arguments.length >= 1 && null != arguments[0]) {
                if (arguments[0] instanceof Map) {}

                if (arguments[0] instanceof JsonValue) {

                } else {
                  throw new NoSuchMethodException(
                      FunctionFactory.getNoSuchMethodMessage("callback", arguments));
                }
              } else {
                throw new NoSuchMethodException(
                    FunctionFactory.getNoSuchMethodMessage("callback", arguments));
              }
              return null;
            }
          };
      script.putSafe("callback", queryCallback);
      Object rawResult = script.eval();
      JsonValue result = null;
      if (rawResult instanceof JsonValue) {
        result = (JsonValue) rawResult;
      } else {
        result = new JsonValue(rawResult);
      }
      QueryResponse queryResponse = newQueryResponse();
      // Script can either
      // - return null and instead use callback hook to call
      //   handleResource, handleResult, handleError
      //   careful! script MUST call handleResult or handleError itself
      // or
      // - return a result list of resources
      // or
      // - return a full query result structure
      if (!result.isNull()) {
        if (result.isList()) {
          // Script may return just the result elements as a list
          handleQueryResultList(result, handler);
        } else {
          // Or script may return a full query response structure,
          // with meta-data and results field
          if (result.isDefined(QueryResponse.FIELD_RESULT)) {
            handleQueryResultList(result.get(QueryResponse.FIELD_RESULT), handler);
            queryResponse =
                newQueryResponse(
                    result.get(QueryResponse.FIELD_PAGED_RESULTS_COOKIE).asString(),
                    result
                        .get(QueryResponse.FIELD_TOTAL_PAGED_RESULTS_POLICY)
                        .asEnum(CountPolicy.class),
                    result.get(QueryResponse.FIELD_TOTAL_PAGED_RESULTS).asInteger());
          } else {
            logger.debug("Script returned unexpected query result structure: ", result.getObject());
            return new InternalServerErrorException(
                    "Script returned unexpected query result structure of type "
                        + result.getObject().getClass())
                .asPromise();
          }
        }
      }
      return queryResponse.asPromise();
    } catch (ScriptException e) {
      return convertScriptException(e).asPromise();
    } catch (ResourceException e) {
      return e.asPromise();
    } catch (Exception e) {
      return new InternalServerErrorException(e.getMessage(), e).asPromise();
    } finally {
      measure.end();
    }
  }