@Override
  public Promise<ResourceResponse, ResourceException> createInstance(
      Context context, CreateRequest request) {
    TokenGenerationServiceInvocationState invocationState;
    try {
      invocationState = TokenGenerationServiceInvocationState.fromJson(request.getContent());
    } catch (Exception e) {
      logger.error(
          "Exception caught marshalling json into TokenGenerationServiceInvocationState instance: "
              + e);
      return new BadRequestException(e.getMessage(), e).asPromise();
    }
    SSOToken subjectToken;
    try {
      subjectToken = validateAssertionSubjectSession(invocationState);
    } catch (ForbiddenException e) {
      return e.asPromise();
    }

    STSInstanceState stsInstanceState;
    try {
      stsInstanceState = getSTSInstanceState(invocationState);
    } catch (ResourceException e) {
      return e.asPromise();
    }

    if (TokenType.SAML2.equals(invocationState.getTokenType())) {
      try {
        final String assertion =
            saml2TokenGeneration.generate(subjectToken, stsInstanceState, invocationState);
        return newResultPromise(issuedTokenResource(assertion));
      } catch (TokenCreationException e) {
        logger.error("Exception caught generating saml2 token: " + e, e);
        return e.asPromise();
      } catch (Exception e) {
        logger.error("Exception caught generating saml2 token: " + e, e);
        return new InternalServerErrorException(e.toString(), e).asPromise();
      }
    } else if (TokenType.OPENIDCONNECT.equals(invocationState.getTokenType())) {
      try {
        final String assertion =
            openIdConnectTokenGeneration.generate(subjectToken, stsInstanceState, invocationState);
        return newResultPromise(issuedTokenResource(assertion));
      } catch (TokenCreationException e) {
        logger.error("Exception caught generating OpenIdConnect token: " + e, e);
        return e.asPromise();
      } catch (Exception e) {
        logger.error("Exception caught generating OpenIdConnect token: " + e, e);
        return new InternalServerErrorException(e.toString(), e).asPromise();
      }
    } else {
      String message = "Bad request: unexpected token type:" + invocationState.getTokenType();
      logger.error(message);
      return new BadRequestException(message).asPromise();
    }
  }
Пример #2
0
  /** {@inheritDoc} */
  @Override
  public void createInstance(
      final ServerContext context,
      final CreateRequest request,
      final ResultHandler<Resource> handler) {

    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();

    Resource resource;
    String parentRealm;
    String childRealm;
    String realm = null;

    try {
      hasPermission(context);
      final JsonValue jVal = request.getContent();
      // get the realm
      realm = jVal.get("realm").asString();
      realm = checkForTopLevelRealm(realm);
      if (realm == null || realm.isEmpty()) {
        throw new BadRequestException("No realm name provided.");
      } else if (!realm.startsWith("/")) {
        realm = "/" + realm;
      }
      if (!realmPath.equalsIgnoreCase("/")) {
        // build realm to comply with format if not top level
        realm = realmPath + realm;
      }

      parentRealm = RealmUtils.getParentRealm(realm);
      childRealm = RealmUtils.getChildRealm(realm);

      OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), parentRealm);

      Map defaultValues = createServicesMap(jVal);
      ocm.createSubOrganization(childRealm, defaultValues);
      String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
      debug.message(
          "RealmResource.createInstance :: CREATE of realm "
              + childRealm
              + " in realm "
              + parentRealm
              + " performed by "
              + principalName);

      // create a resource for handler to return
      OrganizationConfigManager realmCreated = new OrganizationConfigManager(getSSOToken(), realm);
      resource =
          new Resource(
              childRealm,
              String.valueOf(System.currentTimeMillis()),
              createJsonMessage("realmCreated", realmCreated.getOrganizationName()));
      handler.handleResult(resource);

    } catch (SMSException smse) {

      debug.error("RealmResource.createInstance() : Cannot find " + realm, smse);

      try {
        configureErrorMessage(smse);
      } catch (NotFoundException nf) {
        debug.error("RealmResource.createInstance() : Cannot find " + realm, nf);
        handler.handleError(nf);
      } catch (ForbiddenException fe) {
        // User does not have authorization
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
        handler.handleError(fe);
      } catch (PermanentException pe) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
        // Cannot recover from this exception
        handler.handleError(pe);
      } catch (ConflictException ce) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, ce);
        handler.handleError(ce);
      } catch (BadRequestException be) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
        handler.handleError(be);
      } catch (Exception e) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, e);
        handler.handleError(new BadRequestException(e.getMessage(), e));
      }
    } catch (SSOException sso) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, sso);
      handler.handleError(new PermanentException(401, "Access Denied", null));
    } catch (ForbiddenException fe) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
      handler.handleError(fe);
    } catch (BadRequestException be) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
      handler.handleError(be);
    } catch (PermanentException pe) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
      // Cannot recover from this exception
      handler.handleError(pe);
    } catch (Exception e) {
      debug.error("RealmResource.createInstance()" + realm + ":" + e);
      handler.handleError(new BadRequestException(e.getMessage(), e));
    }
  }
  /**
   * Creates a new object in the object set.
   *
   * <p>This method sets the {@code _id} property to the assigned identifier for the object, and the
   * {@code _rev} property to the revised object version (For optimistic concurrency)
   *
   * @param request the contents of the object to create in the object set.
   * @throws NotFoundException if the specified id could not be resolved.
   * @throws ForbiddenException if access to the object or object set is forbidden.
   * @throws ConflictException if an object with the same ID already exists.
   */
  @Override
  public ResourceResponse create(CreateRequest request) throws ResourceException {
    if (request.getResourcePathObject().isEmpty()) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type: "
              + request.getResourcePath());
    }

    final String type = request.getResourcePath();
    // TODO: should CREST support server side generation of ID itself?
    final String localId =
        (request.getNewResourceId() == null || "".equals(request.getNewResourceId()))
            ? UUID.randomUUID().toString() // Generate ID server side.
            : request.getNewResourceId();

    // Used currently for logging
    String fullId = request.getResourcePathObject().child(localId).toString();

    String orientClassName = typeToOrientClassName(type);
    JsonValue obj = request.getContent();

    obj.put(DocumentUtil.TAG_ID, localId);

    ODatabaseDocumentTx db = getConnection();
    try {
      // Rather than using MVCC for insert, rely on primary key uniqueness constraints to detect
      // duplicate create
      ODocument newDoc = DocumentUtil.toDocument(obj, null, db, orientClassName);
      logger.trace("Created doc for id: {} to save {}", fullId, newDoc);
      newDoc.save();

      obj.put(DocumentUtil.TAG_REV, Integer.toString(newDoc.getVersion()));
      logger.debug("Completed create for id: {} revision: {}", fullId, newDoc.getVersion());
      logger.trace("Create payload for id: {} doc: {}", fullId, newDoc);
      return newResourceResponse(
          obj.get(DocumentUtil.TAG_ID).asString(), obj.get(DocumentUtil.TAG_REV).asString(), obj);
    } catch (ORecordDuplicatedException ex) {
      // Because the OpenIDM ID is defined as unique, duplicate inserts must fail
      throw new PreconditionFailedException(
          "Create rejected as Object with same ID already exists. " + ex.getMessage(), ex);
    } catch (OIndexException ex) {
      // Because the OpenIDM ID is defined as unique, duplicate inserts must fail
      throw new PreconditionFailedException(
          "Create rejected as Object with same ID already exists. " + ex.getMessage(), ex);
    } catch (ODatabaseException ex) {
      // Because the OpenIDM ID is defined as unique, duplicate inserts must fail.
      // OrientDB may wrap the IndexException root cause.
      if (isCauseIndexException(ex, 10) || isCauseRecordDuplicatedException(ex, 10)) {
        throw new PreconditionFailedException(
            "Create rejected as Object with same ID already exists and was detected. "
                + ex.getMessage(),
            ex);
      } else {
        throw ex;
      }
    } catch (RuntimeException e) {
      throw e;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }