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);
}
}
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);
}
}
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);
}
}
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)));
}
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);
}
}
Aggregations