use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.
the class ApplicationServiceImpl method renewClientSecret.
@Override
public ApplicationEntity renewClientSecret(String applicationId) {
try {
LOGGER.debug("Renew client secret for application {}", applicationId);
Optional<Application> optApplicationToUpdate = applicationRepository.findById(applicationId);
if (!optApplicationToUpdate.isPresent()) {
throw new ApplicationNotFoundException(applicationId);
}
if (ApplicationStatus.ARCHIVED.equals(optApplicationToUpdate.get().getStatus())) {
throw new ApplicationArchivedException(optApplicationToUpdate.get().getName());
}
// Check that client registration is enabled
checkClientRegistrationEnabled();
Application application = optApplicationToUpdate.get();
ApplicationEntity applicationEntity = findById(applicationId);
// Check that the application can be updated with a new client secret
if (applicationEntity.getSettings().getoAuthClient() != null && applicationEntity.getSettings().getoAuthClient().isRenewClientSecretSupported()) {
ClientRegistrationResponse registrationResponse = clientRegistrationService.renewClientSecret(application.getMetadata().get("registration_payload"));
// Update application metadata
Map<String, String> metadata = new HashMap<>();
try {
metadata.put("client_id", registrationResponse.getClientId());
metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
application.setUpdatedAt(new Date());
metadata.forEach((key, value) -> application.getMetadata().put(key, value));
Application updatedApplication = applicationRepository.update(application);
// Audit
auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_UPDATED, updatedApplication.getUpdatedAt(), optApplicationToUpdate.get(), updatedApplication);
return convert(Collections.singleton(updatedApplication)).iterator().next();
}
throw new ApplicationRenewClientSecretException(application.getName());
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to renew client secret {}", applicationId, ex);
throw new TechnicalManagementException(String.format("An error occurs while trying to renew client secret %s", applicationId), ex);
}
}
use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.
the class ApplicationServiceImpl method getSettings.
private ApplicationSettings getSettings(Application application) {
final ApplicationSettings settings = new ApplicationSettings();
if (application.getType() == ApplicationType.SIMPLE) {
SimpleApplicationSettings simpleSettings = new SimpleApplicationSettings();
if (application.getMetadata() != null) {
if (application.getMetadata().get("client_id") != null) {
simpleSettings.setClientId(application.getMetadata().get("client_id"));
}
if (application.getMetadata().get("type") != null) {
simpleSettings.setType(application.getMetadata().get("type"));
}
}
settings.setApp(simpleSettings);
} else {
OAuthClientSettings clientSettings = new OAuthClientSettings();
if (application.getMetadata() != null) {
try {
final String registrationPayload = application.getMetadata().get("registration_payload");
if (registrationPayload != null) {
final ClientRegistrationResponse registrationResponse = mapper.readValue(registrationPayload, ClientRegistrationResponse.class);
clientSettings.setClientId(registrationResponse.getClientId());
clientSettings.setClientSecret(registrationResponse.getClientSecret());
clientSettings.setClientUri(registrationResponse.getClientUri());
clientSettings.setApplicationType(registrationResponse.getApplicationType());
clientSettings.setLogoUri(registrationResponse.getLogoUri());
clientSettings.setResponseTypes(registrationResponse.getResponseTypes());
clientSettings.setRedirectUris(registrationResponse.getRedirectUris());
clientSettings.setGrantTypes(registrationResponse.getGrantTypes());
}
Iterator<ClientRegistrationProviderEntity> clientRegistrationProviderIte = clientRegistrationService.findAll().iterator();
if (clientRegistrationProviderIte.hasNext()) {
clientSettings.setRenewClientSecretSupported(clientRegistrationProviderIte.next().isRenewClientSecretSupport());
}
} catch (IOException e) {
e.printStackTrace();
}
}
settings.setoAuthClient(clientSettings);
}
return settings;
}
use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.
the class ApplicationServiceImpl method create.
@Override
public ApplicationEntity create(NewApplicationEntity newApplicationEntity, String userId, String environmentId) {
LOGGER.debug("Create {} for user {}", newApplicationEntity, userId);
// Check that only one settings is defined
if (newApplicationEntity.getSettings().getApp() != null && newApplicationEntity.getSettings().getoAuthClient() != null) {
throw new InvalidApplicationTypeException();
}
// Check that a type is defined
if (newApplicationEntity.getSettings().getApp() == null && newApplicationEntity.getSettings().getoAuthClient() == null) {
throw new InvalidApplicationTypeException();
}
// Create application metadata
Map<String, String> metadata = new HashMap<>();
// Create a simple "internal" application
if (newApplicationEntity.getSettings().getApp() != null) {
// If client registration is enabled, check that the simple type is allowed
if (isClientRegistrationEnabled(environmentId) && !isApplicationTypeAllowed("simple", environmentId)) {
throw new IllegalStateException("Application type 'simple' is not allowed");
}
// If clientId is set, check for uniqueness
String clientId = newApplicationEntity.getSettings().getApp().getClientId();
if (clientId != null && !clientId.trim().isEmpty()) {
LOGGER.debug("Check that client_id is unique among all applications");
try {
final Set<Application> applications = applicationRepository.findAllByEnvironment(environmentId, ApplicationStatus.ACTIVE);
final boolean alreadyExistingApp = applications.stream().anyMatch(app -> app.getMetadata() != null && clientId.equals(app.getMetadata().get("client_id")));
if (alreadyExistingApp) {
LOGGER.error("An application already exists with the same client_id");
throw new ClientIdAlreadyExistsException(clientId);
}
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to create {} for user {}", newApplicationEntity, userId, ex);
throw new TechnicalManagementException("An error occurs while trying create " + newApplicationEntity + " for user " + userId, ex);
}
}
} else {
// Check that client registration is enabled
checkClientRegistrationEnabled(environmentId);
String appType = newApplicationEntity.getSettings().getoAuthClient().getApplicationType();
// Check that the application_type is allowed
if (!isApplicationTypeAllowed(appType, environmentId)) {
throw new IllegalStateException("Application type '" + appType + "' is not allowed");
}
checkClientSettings(newApplicationEntity.getSettings().getoAuthClient());
// Create an OAuth client
ClientRegistrationResponse registrationResponse = clientRegistrationService.register(newApplicationEntity);
try {
metadata.put("client_id", registrationResponse.getClientId());
metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
if (newApplicationEntity.getGroups() != null && !newApplicationEntity.getGroups().isEmpty()) {
// throw a NotFoundException if the group doesn't exist
groupService.findByIds(newApplicationEntity.getGroups());
}
Application application = convert(newApplicationEntity);
application.setId(UuidString.generateRandom());
application.setStatus(ApplicationStatus.ACTIVE);
metadata.forEach((key, value) -> application.getMetadata().put(key, value));
// Add Default groups
Set<String> defaultGroups = groupService.findByEvent(GroupEvent.APPLICATION_CREATE).stream().map(GroupEntity::getId).collect(toSet());
if (!defaultGroups.isEmpty() && application.getGroups() == null) {
application.setGroups(defaultGroups);
} else if (!defaultGroups.isEmpty()) {
application.getGroups().addAll(defaultGroups);
}
// Set date fields
application.setCreatedAt(new Date());
application.setUpdatedAt(application.getCreatedAt());
return createApplicationForEnvironment(userId, application, environmentId);
}
use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.
the class ApplicationServiceImpl method update.
@Override
public ApplicationEntity update(String applicationId, UpdateApplicationEntity updateApplicationEntity) {
try {
LOGGER.debug("Update application {}", applicationId);
if (updateApplicationEntity.getGroups() != null && !updateApplicationEntity.getGroups().isEmpty()) {
// throw a NotFoundException if the group doesn't exist
groupService.findByIds(updateApplicationEntity.getGroups());
}
Optional<Application> optApplicationToUpdate = applicationRepository.findById(applicationId);
if (!optApplicationToUpdate.isPresent()) {
throw new ApplicationNotFoundException(applicationId);
}
if (ApplicationStatus.ARCHIVED.equals(optApplicationToUpdate.get().getStatus())) {
throw new ApplicationArchivedException(optApplicationToUpdate.get().getName());
}
// Check that only one settings is defined
if (updateApplicationEntity.getSettings().getApp() != null && updateApplicationEntity.getSettings().getoAuthClient() != null) {
throw new InvalidApplicationTypeException();
}
// Check that a type is defined
if (updateApplicationEntity.getSettings().getApp() == null && updateApplicationEntity.getSettings().getoAuthClient() == null) {
throw new InvalidApplicationTypeException();
}
// Update application metadata
Map<String, String> metadata = new HashMap<>();
// Update a simple application
if (optApplicationToUpdate.get().getType() == ApplicationType.SIMPLE && updateApplicationEntity.getSettings().getApp() != null) {
// If clientId is set, check for uniqueness
String clientId = updateApplicationEntity.getSettings().getApp().getClientId();
if (clientId != null && !clientId.trim().isEmpty()) {
LOGGER.debug("Check that client_id is unique among all applications");
final Set<Application> applications = applicationRepository.findAllByEnvironment(GraviteeContext.getCurrentEnvironment(), ApplicationStatus.ACTIVE);
final Optional<Application> byClientId = applications.stream().filter(app -> app.getMetadata() != null && clientId.equals(app.getMetadata().get("client_id"))).findAny();
if (byClientId.isPresent() && !byClientId.get().getId().equals(optApplicationToUpdate.get().getId())) {
LOGGER.error("An application already exists with the same client_id");
throw new ClientIdAlreadyExistsException(clientId);
}
}
} else {
// Check that client registration is enabled
checkClientRegistrationEnabled();
checkClientSettings(updateApplicationEntity.getSettings().getoAuthClient());
// Update an OAuth client
final String registrationPayload = optApplicationToUpdate.get().getMetadata().get("registration_payload");
if (registrationPayload != null) {
ClientRegistrationResponse registrationResponse = clientRegistrationService.update(registrationPayload, updateApplicationEntity);
if (registrationResponse != null) {
try {
metadata.put("client_id", registrationResponse.getClientId());
metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
}
Application application = convert(updateApplicationEntity);
application.setId(applicationId);
application.setEnvironmentId(optApplicationToUpdate.get().getEnvironmentId());
application.setStatus(ApplicationStatus.ACTIVE);
application.setType(optApplicationToUpdate.get().getType());
application.setCreatedAt(optApplicationToUpdate.get().getCreatedAt());
application.setUpdatedAt(new Date());
metadata.forEach((key, value) -> application.getMetadata().put(key, value));
Application updatedApplication = applicationRepository.update(application);
// Audit
auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_UPDATED, updatedApplication.getUpdatedAt(), optApplicationToUpdate.get(), updatedApplication);
// Set correct client_id for all subscriptions
SubscriptionQuery subQuery = new SubscriptionQuery();
subQuery.setApplication(applicationId);
subQuery.setStatuses(Collections.singleton(SubscriptionStatus.ACCEPTED));
subscriptionService.search(subQuery).forEach(new Consumer<SubscriptionEntity>() {
@Override
public void accept(SubscriptionEntity subscriptionEntity) {
UpdateSubscriptionEntity updateSubscriptionEntity = new UpdateSubscriptionEntity();
updateSubscriptionEntity.setId(subscriptionEntity.getId());
updateSubscriptionEntity.setStartingAt(subscriptionEntity.getStartingAt());
updateSubscriptionEntity.setEndingAt(subscriptionEntity.getEndingAt());
subscriptionService.update(updateSubscriptionEntity, application.getMetadata().get("client_id"));
}
});
return convert(Collections.singleton(updatedApplication)).iterator().next();
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to update application {}", applicationId, ex);
throw new TechnicalManagementException(String.format("An error occurs while trying to update application %s", applicationId), ex);
}
}
use of io.gravitee.rest.api.service.impl.configuration.application.registration.client.register.ClientRegistrationResponse in project gravitee-management-rest-api by gravitee-io.
the class ClientRegistrationServiceImpl method update.
@Override
public ClientRegistrationResponse update(String previousRegistrationResponse, UpdateApplicationEntity application) {
try {
ClientRegistrationResponse registrationResponse = mapper.readValue(previousRegistrationResponse, ClientRegistrationResponse.class);
if (registrationResponse.getRegistrationAccessToken() == null || registrationResponse.getRegistrationAccessToken().isEmpty() || registrationResponse.getRegistrationClientUri() == null || registrationResponse.getRegistrationClientUri().isEmpty()) {
throw new RegisteredClientNotUpdatableException();
}
// Update an OAuth client
Set<ClientRegistrationProviderEntity> providers = findAll();
if (providers == null || providers.isEmpty()) {
throw new MissingDynamicClientRegistrationProviderException();
}
// For now, took the first provider
ClientRegistrationProviderEntity provider = providers.iterator().next();
// Get provider client
DynamicClientRegistrationProviderClient registrationProviderClient = getDCRClient(false, provider);
ClientRegistrationRequest registrationRequest = mapper.readValue(previousRegistrationResponse, ClientRegistrationRequest.class);
registrationRequest.setSoftwareId(provider.getSoftwareId());
return registrationProviderClient.update(registrationResponse.getRegistrationAccessToken(), registrationResponse.getRegistrationClientUri(), convert(registrationRequest, application), application.getSettings().getoAuthClient().getClientId());
} catch (Exception ex) {
LOGGER.error("Unexpected error while updating a client", ex);
return null;
}
}
Aggregations