Search in sources :

Example 1 with ApiKey

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

the class ApiKeyServiceImpl method generateForSubscription.

/**
 * Generate an {@link ApiKey} from a subscription.
 *
 * @param subscription
 * @return An Api Key
 */
private ApiKey generateForSubscription(String subscription) {
    SubscriptionEntity subscriptionEntity = subscriptionService.findById(subscription);
    Date now = new Date();
    if (subscriptionEntity.getEndingAt() != null && subscriptionEntity.getEndingAt().before(now)) {
        throw new SubscriptionClosedException(subscription);
    }
    ApiKey apiKey = new ApiKey();
    apiKey.setSubscription(subscription);
    apiKey.setApplication(subscriptionEntity.getApplication());
    apiKey.setPlan(subscriptionEntity.getPlan());
    apiKey.setCreatedAt(new Date());
    apiKey.setUpdatedAt(apiKey.getCreatedAt());
    apiKey.setKey(apiKeyGenerator.generate());
    // By default, the API Key will expire when subscription is closed
    apiKey.setExpireAt(subscriptionEntity.getEndingAt());
    return apiKey;
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) SubscriptionClosedException(io.gravitee.management.service.exceptions.SubscriptionClosedException)

Example 2 with ApiKey

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

the class ApiKeyServiceImpl method revoke.

@Override
public void revoke(String apiKey, boolean notify) {
    try {
        LOGGER.debug("Revoke API Key {}", apiKey);
        Optional<ApiKey> optKey = apiKeyRepository.findById(apiKey);
        if (!optKey.isPresent()) {
            throw new ApiKeyNotFoundException();
        }
        ApiKey key = optKey.get();
        if (!key.isRevoked()) {
            ApiKey previousApiKey = new ApiKey(key);
            key.setRevoked(true);
            key.setUpdatedAt(new Date());
            key.setRevokedAt(key.getUpdatedAt());
            apiKeyRepository.update(key);
            final PlanEntity plan = planService.findById(key.getPlan());
            // Audit
            auditService.createApiAuditLog(plan.getApis().iterator().next(), Collections.singletonMap(API_KEY, key.getKey()), APIKEY_REVOKED, key.getUpdatedAt(), previousApiKey, key);
            // notify
            if (notify) {
                final ApplicationEntity application = applicationService.findById(key.getApplication());
                final ApiModelEntity api = apiService.findByIdForTemplates(plan.getApis().iterator().next());
                final PrimaryOwnerEntity owner = application.getPrimaryOwner();
                final Map<String, Object> params = new NotificationParamsBuilder().application(application).plan(plan).api(api).owner(owner).apikey(key).build();
                notifierService.trigger(ApiHook.APIKEY_REVOKED, api.getId(), params);
            }
        } else {
            LOGGER.info("API Key {} already revoked. Skipping...", apiKey);
        }
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to revoke a key {}", apiKey, ex);
        throw new TechnicalManagementException("An error occurs while trying to revoke a key " + apiKey, ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ApiKeyNotFoundException(io.gravitee.management.service.exceptions.ApiKeyNotFoundException) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 3 with ApiKey

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

the class ApiKeyServiceImpl method generate.

@Override
public ApiKeyEntity generate(String subscription) {
    try {
        LOGGER.debug("Generate an API Key for subscription {}", subscription);
        ApiKey apiKey = generateForSubscription(subscription);
        apiKey = apiKeyRepository.create(apiKey);
        // TODO: Send a notification to the application owner
        // Audit
        final PlanEntity plan = planService.findById(apiKey.getPlan());
        auditService.createApiAuditLog(plan.getApis().iterator().next(), Collections.singletonMap(API_KEY, apiKey.getKey()), APIKEY_CREATED, apiKey.getCreatedAt(), null, apiKey);
        return convert(apiKey);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to generate an API Key for {} - {}", subscription, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to generate an API Key for %s", subscription), ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 4 with ApiKey

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

the class ApiKeyServiceTest method shouldRenew.

@Test
public void shouldRenew() throws TechnicalException {
    // Prepare data
    // apiKey object is not a mock since its state is updated by the call to apiKeyService.renew()
    apiKey = new ApiKey();
    apiKey.setKey("123-456-789");
    apiKey.setSubscription(SUBSCRIPTION_ID);
    apiKey.setCreatedAt(new Date());
    apiKey.setPlan(PLAN_ID);
    apiKey.setApplication(APPLICATION_ID);
    final ApiModelEntity api = mock(ApiModelEntity.class);
    when(api.getId()).thenReturn("123");
    when(subscription.getId()).thenReturn(SUBSCRIPTION_ID);
    when(subscription.getEndingAt()).thenReturn(Date.from(new Date().toInstant().plus(1, ChronoUnit.DAYS)));
    when(subscription.getApplication()).thenReturn(APPLICATION_ID);
    when(subscription.getPlan()).thenReturn(PLAN_ID);
    when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
    // Stub
    when(apiKeyGenerator.generate()).thenReturn(API_KEY);
    when(apiKeyRepository.findById(API_KEY)).thenReturn(Optional.of(apiKey));
    when(subscriptionService.findById(subscription.getId())).thenReturn(subscription);
    when(apiKeyRepository.create(any())).thenAnswer(returnsFirstArg());
    when(apiKeyRepository.findBySubscription(SUBSCRIPTION_ID)).thenReturn(Collections.singleton(apiKey));
    when(applicationService.findById(subscription.getApplication())).thenReturn(application);
    when(planService.findById(subscription.getPlan())).thenReturn(plan);
    when(apiService.findByIdForTemplates(any())).thenReturn(api);
    // Run
    final ApiKeyEntity apiKeyEntity = apiKeyService.renew(SUBSCRIPTION_ID);
    // Verify
    // A new API Key has been created
    verify(apiKeyRepository, times(1)).create(any());
    assertEquals(API_KEY, apiKeyEntity.getKey());
    // Old API Key has been revoked
    verify(apiKeyRepository, times(1)).update(apiKey);
    assertFalse(apiKey.isRevoked());
    assertNotNull(apiKey.getExpireAt());
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) Date(java.util.Date) Test(org.junit.Test)

Example 5 with ApiKey

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

the class ApiKeyServiceImpl method findBySubscription.

@Override
public Set<ApiKeyEntity> findBySubscription(String subscription) {
    try {
        LOGGER.debug("Find API Keys for subscription {}", subscription);
        SubscriptionEntity subscriptionEntity = subscriptionService.findById(subscription);
        Set<ApiKey> keys = apiKeyRepository.findBySubscription(subscriptionEntity.getId());
        return keys.stream().map(ApiKeyServiceImpl::convert).collect(Collectors.toSet());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while finding API keys for subscription {}", subscription, ex);
        throw new TechnicalManagementException(String.format("An error occurs while finding API keys for subscription %s", subscription), ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Aggregations

ApiKey (io.gravitee.repository.management.model.ApiKey)14 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)6 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)6 Test (org.junit.Test)6 ApiKeyNotFoundException (io.gravitee.management.service.exceptions.ApiKeyNotFoundException)3 ApiKeyCriteria (io.gravitee.repository.management.api.search.ApiKeyCriteria)3 Element (net.sf.ehcache.Element)3 Plan (io.gravitee.gateway.handlers.api.definition.Plan)2 NotificationParamsBuilder (io.gravitee.management.service.notification.NotificationParamsBuilder)2 Date (java.util.Date)2 SubscriptionClosedException (io.gravitee.management.service.exceptions.SubscriptionClosedException)1 Instant (java.time.Instant)1