Search in sources :

Example 6 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method process.

@Override
public SubscriptionEntity process(ProcessSubscriptionEntity processSubscription, String userId) {
    try {
        logger.debug("Subscription {} processed by {}", processSubscription.getId(), userId);
        Optional<Subscription> optSubscription = subscriptionRepository.findById(processSubscription.getId());
        if (!optSubscription.isPresent()) {
            throw new SubscriptionNotFoundException(processSubscription.getId());
        }
        Subscription subscription = optSubscription.get();
        Subscription previousSubscription = new Subscription(subscription);
        if (subscription.getStatus() != Subscription.Status.PENDING) {
            throw new SubscriptionAlreadyProcessedException(subscription.getId());
        }
        PlanEntity planEntity = planService.findById(subscription.getPlan());
        if (planEntity.getStatus() == PlanStatus.CLOSED) {
            throw new PlanAlreadyClosedException(planEntity.getId());
        }
        subscription.setProcessedBy(userId);
        subscription.setProcessedAt(new Date());
        if (processSubscription.isAccepted()) {
            subscription.setStatus(Subscription.Status.ACCEPTED);
            subscription.setStartingAt((processSubscription.getStartingAt() != null) ? processSubscription.getStartingAt() : new Date());
            subscription.setEndingAt(processSubscription.getEndingAt());
            subscription.setReason(processSubscription.getReason());
        } else {
            subscription.setStatus(Subscription.Status.REJECTED);
            subscription.setReason(processSubscription.getReason());
            subscription.setClosedAt(new Date());
        }
        subscription = subscriptionRepository.update(subscription);
        final ApplicationEntity application = applicationService.findById(subscription.getApplication());
        final PlanEntity plan = planService.findById(subscription.getPlan());
        final String apiId = plan.getApis().iterator().next();
        final ApiModelEntity api = apiService.findByIdForTemplates(apiId);
        final PrimaryOwnerEntity owner = application.getPrimaryOwner();
        createAudit(apiId, subscription.getApplication(), SUBSCRIPTION_UPDATED, subscription.getUpdatedAt(), previousSubscription, subscription);
        SubscriptionEntity subscriptionEntity = convert(subscription);
        final Map<String, Object> params = new NotificationParamsBuilder().owner(owner).application(application).api(api).plan(plan).subscription(subscriptionEntity).build();
        if (subscription.getStatus() == Subscription.Status.ACCEPTED) {
            notifierService.trigger(ApiHook.SUBSCRIPTION_ACCEPTED, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_ACCEPTED, application.getId(), params);
        } else {
            notifierService.trigger(ApiHook.SUBSCRIPTION_REJECTED, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_REJECTED, application.getId(), params);
        }
        if (plan.getSecurity() == PlanSecurityType.API_KEY && subscription.getStatus() == Subscription.Status.ACCEPTED) {
            apiKeyService.generate(subscription.getId());
        }
        return subscriptionEntity;
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to process subscription {} by {}", processSubscription.getId(), userId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to process subscription %s by %s", processSubscription.getId(), userId), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Subscription(io.gravitee.repository.management.model.Subscription)

Example 7 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method update.

@Override
public SubscriptionEntity update(UpdateSubscriptionEntity updateSubscription, String clientId) {
    try {
        logger.debug("Update subscription {}", updateSubscription.getId());
        Optional<Subscription> optSubscription = subscriptionRepository.findById(updateSubscription.getId());
        if (!optSubscription.isPresent()) {
            throw new SubscriptionNotFoundException(updateSubscription.getId());
        }
        Subscription subscription = optSubscription.get();
        if (subscription.getStatus() == Subscription.Status.ACCEPTED) {
            Subscription previousSubscription = new Subscription(subscription);
            subscription.setUpdatedAt(new Date());
            subscription.setStartingAt(updateSubscription.getStartingAt());
            subscription.setEndingAt(updateSubscription.getEndingAt());
            if (clientId != null) {
                subscription.setClientId(clientId);
            }
            subscription = subscriptionRepository.update(subscription);
            final PlanEntity plan = planService.findById(subscription.getPlan());
            createAudit(plan.getApis().iterator().next(), subscription.getApplication(), SUBSCRIPTION_UPDATED, subscription.getUpdatedAt(), previousSubscription, subscription);
            // Update the expiration date for not yet revoked api-keys relative to this subscription
            Date endingAt = subscription.getEndingAt();
            if (plan.getSecurity() == PlanSecurityType.API_KEY && endingAt != null) {
                Set<ApiKeyEntity> apiKeys = apiKeyService.findBySubscription(subscription.getId());
                Date now = new Date();
                for (ApiKeyEntity apiKey : apiKeys) {
                    Date expireAt = apiKey.getExpireAt();
                    if (!apiKey.isRevoked() && (expireAt == null || expireAt.equals(now) || expireAt.before(now))) {
                        apiKey.setExpireAt(endingAt);
                        apiKeyService.update(apiKey);
                    }
                }
            }
            return convert(subscription);
        }
        throw new SubscriptionNotUpdatableException(updateSubscription.getId());
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to update subscription {}", updateSubscription.getId(), ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to update subscription %s", updateSubscription.getId()), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Subscription(io.gravitee.repository.management.model.Subscription)

Example 8 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method delete.

@Override
public void delete(String subscriptionId) {
    try {
        logger.debug("Delete subscription {}", subscriptionId);
        Optional<Subscription> optSubscription = subscriptionRepository.findById(subscriptionId);
        if (!optSubscription.isPresent()) {
            throw new SubscriptionNotFoundException(subscriptionId);
        }
        Subscription subscription = optSubscription.get();
        // Delete API Keys
        apiKeyService.findBySubscription(subscriptionId).forEach(apiKey -> apiKeyService.delete(apiKey.getKey()));
        // Delete subscription
        subscriptionRepository.delete(subscriptionId);
        createAudit(planService.findById(subscription.getPlan()).getApis().iterator().next(), subscription.getApplication(), SUBSCRIPTION_DELETED, subscription.getUpdatedAt(), subscription, null);
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to delete subscription: {}", subscriptionId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to delete subscription: %s", subscriptionId), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Subscription(io.gravitee.repository.management.model.Subscription)

Example 9 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-gateway by gravitee-io.

the class CheckSubscriptionPolicyTest method shouldReturnUnauthorized_noClient.

@Test
public void shouldReturnUnauthorized_noClient() throws PolicyException, TechnicalException {
    CheckSubscriptionPolicy policy = new CheckSubscriptionPolicy();
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    when(response.headers()).thenReturn(mock(HttpHeaders.class));
    PolicyChain policyChain = mock(PolicyChain.class);
    ExecutionContext executionContext = mock(ExecutionContext.class);
    SubscriptionRepository subscriptionRepository = mock(SubscriptionRepository.class);
    when(executionContext.getComponent(SubscriptionRepository.class)).thenReturn(subscriptionRepository);
    Subscription subscription = mock(Subscription.class);
    when(subscription.getClientId()).thenReturn("my-bad-client-id");
    when(subscriptionRepository.search(any(SubscriptionCriteria.class))).thenReturn(Collections.singletonList(subscription));
    policy.onRequest(request, response, policyChain, executionContext);
    verify(policyChain, times(1)).failWith(argThat(statusCode(HttpStatusCode.UNAUTHORIZED_401)));
}
Also used : Response(io.gravitee.gateway.api.Response) HttpHeaders(io.gravitee.common.http.HttpHeaders) PolicyChain(io.gravitee.policy.api.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) Request(io.gravitee.gateway.api.Request) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Example 10 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-gateway by gravitee-io.

the class CheckSubscriptionPolicy method onRequest.

@Override
protected void onRequest(Request request, Response response, PolicyChain policyChain, ExecutionContext executionContext) throws PolicyException {
    SubscriptionRepository subscriptionRepository = executionContext.getComponent(SubscriptionRepository.class);
    // Get plan and client_id from execution context
    String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
    String clientId = (String) executionContext.getAttribute(CONTEXT_ATTRIBUTE_CLIENT_ID);
    try {
        List<Subscription> subscriptions = subscriptionRepository.search(new SubscriptionCriteria.Builder().plans(Collections.singleton(plan)).clientId(clientId).status(Subscription.Status.ACCEPTED).build());
        if (subscriptions != null && !subscriptions.isEmpty()) {
            Subscription subscription = subscriptions.get(0);
            if (subscription.getClientId().equals(clientId) && (subscription.getEndingAt() == null || subscription.getEndingAt().after(Date.from(request.timestamp())))) {
                executionContext.setAttribute(ExecutionContext.ATTR_APPLICATION, subscription.getApplication());
                executionContext.setAttribute(ExecutionContext.ATTR_USER_ID, subscription.getId());
                policyChain.doNext(request, response);
                return;
            }
        }
        // As per https://tools.ietf.org/html/rfc6749#section-4.1.2.1
        sendUnauthorized(policyChain, OAUTH2_ERROR_ACCESS_DENIED);
    } catch (TechnicalException te) {
        // As per https://tools.ietf.org/html/rfc6749#section-4.1.2.1
        sendUnauthorized(policyChain, OAUTH2_ERROR_SERVER_ERROR);
    }
}
Also used : SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Subscription(io.gravitee.repository.management.model.Subscription)

Aggregations

Subscription (io.gravitee.repository.management.model.Subscription)28 Test (org.junit.Test)19 SubscriptionCriteria (io.gravitee.repository.management.api.search.SubscriptionCriteria)10 SubscriptionRepository (io.gravitee.repository.management.api.SubscriptionRepository)8 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)7 ExecutionContext (io.gravitee.gateway.api.ExecutionContext)5 Request (io.gravitee.gateway.api.Request)5 Response (io.gravitee.gateway.api.Response)5 PolicyChain (io.gravitee.policy.api.PolicyChain)5 UserDetails (io.gravitee.management.idp.api.authentication.UserDetails)3 NotificationParamsBuilder (io.gravitee.management.service.notification.NotificationParamsBuilder)3 Authentication (org.springframework.security.core.Authentication)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SecurityContext (org.springframework.security.core.context.SecurityContext)3 Element (net.sf.ehcache.Element)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 Page (io.gravitee.common.data.domain.Page)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 UUID (io.gravitee.common.utils.UUID)1 io.gravitee.management.model (io.gravitee.management.model)1