Search in sources :

Example 1 with NotificationParamsBuilder

use of io.gravitee.management.service.notification.NotificationParamsBuilder 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 2 with NotificationParamsBuilder

use of io.gravitee.management.service.notification.NotificationParamsBuilder in project gravitee-management-rest-api by gravitee-io.

the class MembershipServiceImpl method buildEmailNotification.

private EmailNotification buildEmailNotification(UserEntity user, MembershipReferenceType referenceType, String referenceId) {
    String subject = null;
    EmailNotificationBuilder.EmailTemplate template = null;
    Map<String, Object> params = null;
    GroupEntity groupEntity;
    NotificationParamsBuilder paramsBuilder = new NotificationParamsBuilder();
    switch(referenceType) {
        case APPLICATION:
            ApplicationEntity applicationEntity = applicationService.findById(referenceId);
            subject = "Subscription to application " + applicationEntity.getName();
            template = EmailNotificationBuilder.EmailTemplate.APPLICATION_MEMBER_SUBSCRIPTION;
            params = paramsBuilder.application(applicationEntity).user(user).build();
            break;
        case API:
            ApiEntity apiEntity = apiService.findById(referenceId);
            subject = "Subscription to API " + apiEntity.getName();
            template = EmailNotificationBuilder.EmailTemplate.API_MEMBER_SUBSCRIPTION;
            params = paramsBuilder.api(apiEntity).user(user).build();
            break;
        case GROUP:
            groupEntity = groupService.findById(referenceId);
            subject = "Subscription to group " + groupEntity.getName();
            template = EmailNotificationBuilder.EmailTemplate.GROUP_MEMBER_SUBSCRIPTION;
            params = paramsBuilder.group(groupEntity).user(user).build();
            break;
    }
    if (template == null) {
        return null;
    }
    return new EmailNotificationBuilder().to(user.getEmail()).subject(subject).template(template).params(params).build();
}
Also used : EmailNotificationBuilder(io.gravitee.management.service.builder.EmailNotificationBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder)

Example 3 with NotificationParamsBuilder

use of io.gravitee.management.service.notification.NotificationParamsBuilder in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method create.

@Override
public SubscriptionEntity create(NewSubscriptionEntity newSubscriptionEntity) {
    String plan = newSubscriptionEntity.getPlan();
    String application = newSubscriptionEntity.getApplication();
    try {
        logger.debug("Create a new subscription for plan {} and application {}", plan, application);
        PlanEntity planEntity = planService.findById(plan);
        if (planEntity.getStatus() == PlanStatus.CLOSED) {
            throw new PlanAlreadyClosedException(plan);
        }
        if (planEntity.getStatus() == PlanStatus.STAGING) {
            throw new PlanNotYetPublishedException(plan);
        }
        if (planEntity.getSecurity() == PlanSecurityType.KEY_LESS) {
            throw new PlanNotSubscribableException("A key_less plan is not subscribable !");
        }
        ApplicationEntity applicationEntity = applicationService.findById(application);
        // Check existing subscriptions
        List<Subscription> subscriptions = subscriptionRepository.search(new SubscriptionCriteria.Builder().applications(Collections.singleton(application)).apis(planEntity.getApis()).build());
        if (!subscriptions.isEmpty()) {
            Predicate<Subscription> onlyValidSubs = subscription -> subscription.getStatus() != Subscription.Status.REJECTED && subscription.getStatus() != Subscription.Status.CLOSED;
            // First, check that there is no subscription to the same plan
            long subscriptionCount = subscriptions.stream().filter(onlyValidSubs).filter(subscription -> subscription.getPlan().equals(plan)).count();
            if (subscriptionCount > 0) {
                throw new PlanAlreadySubscribedException(plan);
            }
            // Check that there is no existing subscription based on an OAuth2 or JWT plan
            if (planEntity.getSecurity() == PlanSecurityType.OAUTH2 || planEntity.getSecurity() == PlanSecurityType.JWT) {
                long count = subscriptions.stream().filter(onlyValidSubs).map(Subscription::getPlan).distinct().map(plan1 -> planService.findById(plan1)).filter(subPlan -> subPlan.getSecurity() == PlanSecurityType.OAUTH2 || subPlan.getSecurity() == PlanSecurityType.JWT).count();
                if (count > 0) {
                    throw new PlanNotSubscribableException("An other OAuth2 or JWT plan is already subscribed by the same application.");
                }
            }
        }
        if (planEntity.getSecurity() == PlanSecurityType.OAUTH2 || planEntity.getSecurity() == PlanSecurityType.JWT) {
            // Check that the application contains a client_id
            if (applicationEntity.getClientId() == null || applicationEntity.getClientId().trim().isEmpty()) {
                throw new PlanNotSubscribableException("A client_id is required to subscribe to an OAuth2 or JWT plan.");
            }
        }
        Subscription subscription = new Subscription();
        subscription.setPlan(plan);
        subscription.setId(UUID.toString(UUID.random()));
        subscription.setApplication(application);
        subscription.setCreatedAt(new Date());
        subscription.setUpdatedAt(subscription.getCreatedAt());
        subscription.setStatus(Subscription.Status.PENDING);
        subscription.setRequest(newSubscriptionEntity.getRequest());
        subscription.setSubscribedBy(getAuthenticatedUser().getUsername());
        subscription.setClientId(applicationEntity.getClientId());
        String apiId = planEntity.getApis().iterator().next();
        subscription.setApi(apiId);
        subscription = subscriptionRepository.create(subscription);
        createAudit(apiId, application, SUBSCRIPTION_CREATED, subscription.getCreatedAt(), null, subscription);
        final ApiModelEntity api = apiService.findByIdForTemplates(apiId);
        final PrimaryOwnerEntity apiOwner = api.getPrimaryOwner();
        // final PrimaryOwnerEntity appOwner = applicationEntity.getPrimaryOwner();
        String portalUrl = environment.getProperty("portalURL");
        String subscriptionsUrl = "";
        if (portalUrl != null) {
            if (portalUrl.endsWith("/")) {
                portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
            }
            subscriptionsUrl = portalUrl + "/#!/management/apis/" + api.getId() + "/subscriptions/" + subscription.getId();
        }
        final Map<String, Object> params = new NotificationParamsBuilder().api(api).plan(planEntity).application(applicationEntity).owner(apiOwner).subscription(convert(subscription)).subscriptionsUrl(subscriptionsUrl).build();
        if (PlanValidationType.AUTO == planEntity.getValidation()) {
            ProcessSubscriptionEntity process = new ProcessSubscriptionEntity();
            process.setId(subscription.getId());
            process.setAccepted(true);
            process.setStartingAt(new Date());
            // Do process
            return process(process, SUBSCRIPTION_SYSTEM_VALIDATOR);
        } else {
            notifierService.trigger(ApiHook.SUBSCRIPTION_NEW, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_NEW, application, params);
            return convert(subscription);
        }
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to subscribe to the plan {}", plan, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to subscribe to the plan %s", plan), ex);
    }
}
Also used : SubscriptionQuery(io.gravitee.management.model.subscription.SubscriptionQuery) java.util(java.util) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Autowired(org.springframework.beans.factory.annotation.Autowired) Subscription(io.gravitee.repository.management.model.Subscription) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) io.gravitee.management.model(io.gravitee.management.model) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) AuditEvent(io.gravitee.repository.management.model.Subscription.AuditEvent) API(io.gravitee.repository.management.model.Audit.AuditProperties.API) APPLICATION(io.gravitee.repository.management.model.Audit.AuditProperties.APPLICATION) Logger(org.slf4j.Logger) Pageable(io.gravitee.management.model.common.Pageable) Metadata(io.gravitee.management.model.pagedresult.Metadata) ApiHook(io.gravitee.management.service.notification.ApiHook) SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) Predicate(java.util.function.Predicate) Audit(io.gravitee.repository.management.model.Audit) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) io.gravitee.management.service(io.gravitee.management.service) ApplicationHook(io.gravitee.management.service.notification.ApplicationHook) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Subscription(io.gravitee.repository.management.model.Subscription)

Example 4 with NotificationParamsBuilder

use of io.gravitee.management.service.notification.NotificationParamsBuilder 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 5 with NotificationParamsBuilder

use of io.gravitee.management.service.notification.NotificationParamsBuilder in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method register.

/**
 * Allows to pre-create a user and send an email notification to finalize its creation.
 */
@Override
public UserEntity register(final NewExternalUserEntity newExternalUserEntity) {
    checkUserRegistrationEnabled();
    newExternalUserEntity.setUsername(newExternalUserEntity.getEmail());
    newExternalUserEntity.setSource("gravitee");
    newExternalUserEntity.setSourceId(newExternalUserEntity.getUsername());
    final UserEntity userEntity = create(newExternalUserEntity, true);
    // generate a JWT to store user's information and for security purpose
    final Map<String, Object> claims = new HashMap<>();
    claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
    claims.put(Claims.SUBJECT, userEntity.getUsername());
    claims.put(Claims.EMAIL, userEntity.getEmail());
    claims.put(Claims.FIRSTNAME, userEntity.getFirstname());
    claims.put(Claims.LASTNAME, userEntity.getLastname());
    final JWTSigner.Options options = new JWTSigner.Options();
    options.setExpirySeconds(environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER));
    options.setIssuedAt(true);
    options.setJwtId(true);
    // send a confirm email with the token
    final String jwtSecret = environment.getProperty("jwt.secret");
    if (jwtSecret == null || jwtSecret.isEmpty()) {
        throw new IllegalStateException("JWT secret is mandatory");
    }
    final String token = new JWTSigner(jwtSecret).sign(claims, options);
    String portalUrl = environment.getProperty("portalURL");
    if (portalUrl.endsWith("/")) {
        portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
    }
    String registrationUrl = portalUrl + "/#!/registration/confirm/" + token;
    final Map<String, Object> params = new NotificationParamsBuilder().user(userEntity).token(token).registrationUrl(registrationUrl).build();
    notifierService.trigger(PortalHook.USER_REGISTERED, params);
    emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(userEntity.getEmail()).subject("User registration - " + userEntity.getUsername()).template(EmailNotificationBuilder.EmailTemplate.USER_REGISTRATION).params(params).build());
    return userEntity;
}
Also used : JWTSigner(com.auth0.jwt.JWTSigner) EmailNotificationBuilder(io.gravitee.management.service.builder.EmailNotificationBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder)

Aggregations

NotificationParamsBuilder (io.gravitee.management.service.notification.NotificationParamsBuilder)7 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 Subscription (io.gravitee.repository.management.model.Subscription)3 EmailNotificationBuilder (io.gravitee.management.service.builder.EmailNotificationBuilder)2 ApiKey (io.gravitee.repository.management.model.ApiKey)2 JWTSigner (com.auth0.jwt.JWTSigner)1 Page (io.gravitee.common.data.domain.Page)1 UUID (io.gravitee.common.utils.UUID)1 io.gravitee.management.model (io.gravitee.management.model)1 Pageable (io.gravitee.management.model.common.Pageable)1 Metadata (io.gravitee.management.model.pagedresult.Metadata)1 SubscriptionQuery (io.gravitee.management.model.subscription.SubscriptionQuery)1 io.gravitee.management.service (io.gravitee.management.service)1 io.gravitee.management.service.exceptions (io.gravitee.management.service.exceptions)1 ApiKeyNotFoundException (io.gravitee.management.service.exceptions.ApiKeyNotFoundException)1 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)1 ApiHook (io.gravitee.management.service.notification.ApiHook)1 ApplicationHook (io.gravitee.management.service.notification.ApplicationHook)1 SubscriptionRepository (io.gravitee.repository.management.api.SubscriptionRepository)1 SubscriptionCriteria (io.gravitee.repository.management.api.search.SubscriptionCriteria)1