use of org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO in project carbon-apimgt by wso2.
the class ApiMgtDAO method createApplicationRegistrationEntry.
/**
* Persist the details of the token generation request (allowed domains & validity period) to be used back
* when approval has been granted.
*
* @param dto DTO related to Application Registration.
* @param onlyKeyMappingEntry When this flag is enabled, only AM_APPLICATION_KEY_MAPPING will get affected.
* @throws APIManagementException if failed to create entries in AM_APPLICATION_REGISTRATION and
* AM_APPLICATION_KEY_MAPPING tables.
*/
public void createApplicationRegistrationEntry(ApplicationRegistrationWorkflowDTO dto, boolean onlyKeyMappingEntry) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement queryPs = null;
PreparedStatement appRegPs = null;
ResultSet resultSet = null;
Application application = dto.getApplication();
Subscriber subscriber = application.getSubscriber();
String jsonString = dto.getAppInfoDTO().getOAuthApplicationInfo().getJsonString();
String registrationQuery = SQLConstants.GET_APPLICATION_REGISTRATION_SQL;
String registrationEntry = SQLConstants.ADD_APPLICATION_REGISTRATION_SQL;
String keyMappingEntry = SQLConstants.ADD_APPLICATION_KEY_MAPPING_SQL;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
queryPs = conn.prepareStatement(registrationQuery);
queryPs.setInt(1, subscriber.getId());
queryPs.setInt(2, application.getId());
queryPs.setString(3, dto.getKeyType());
queryPs.setString(4, dto.getKeyManager());
resultSet = queryPs.executeQuery();
if (resultSet.next()) {
throw new APIManagementException("Application '" + application.getName() + "' is already registered.", ExceptionCodes.APPLICATION_ALREADY_REGISTERED);
}
if (!onlyKeyMappingEntry) {
appRegPs = conn.prepareStatement(registrationEntry);
appRegPs.setInt(1, subscriber.getId());
appRegPs.setString(2, dto.getWorkflowReference());
appRegPs.setInt(3, application.getId());
appRegPs.setString(4, dto.getKeyType());
appRegPs.setString(5, dto.getDomainList());
appRegPs.setLong(6, dto.getValidityTime());
appRegPs.setString(7, (String) dto.getAppInfoDTO().getOAuthApplicationInfo().getParameter("tokenScope"));
appRegPs.setString(8, jsonString);
appRegPs.setString(9, dto.getKeyManager());
appRegPs.execute();
}
ps = conn.prepareStatement(keyMappingEntry);
ps.setInt(1, application.getId());
ps.setString(2, dto.getKeyType());
ps.setString(3, dto.getStatus().toString());
ps.setString(4, dto.getKeyManager());
ps.setString(5, UUID.randomUUID().toString());
ps.setString(6, APIConstants.OAuthAppMode.CREATED.name());
ps.execute();
conn.commit();
} catch (SQLException e) {
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
handleException("Error occurred while Rolling back changes done on Application Registration", e1);
}
handleException("Error occurred while creating an " + "Application Registration Entry for Application : " + application.getName(), e);
} finally {
APIMgtDBUtil.closeStatement(queryPs);
APIMgtDBUtil.closeStatement(appRegPs);
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
}
}
use of org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO in project carbon-apimgt by wso2.
the class AbstractApplicationRegistrationWorkflowExecutor method complete.
public WorkflowResponse complete(WorkflowDTO workFlowDTO) throws WorkflowException {
if (log.isDebugEnabled()) {
log.debug("Completing AbstractApplicationRegistrationWorkflowExecutor...");
}
super.complete(workFlowDTO);
ApiMgtDAO dao = ApiMgtDAO.getInstance();
try {
String status = null;
if ("CREATED".equals(workFlowDTO.getStatus().toString())) {
status = APIConstants.AppRegistrationStatus.REGISTRATION_CREATED;
} else if ("REJECTED".equals(workFlowDTO.getStatus().toString())) {
status = APIConstants.AppRegistrationStatus.REGISTRATION_REJECTED;
} else if ("APPROVED".equals(workFlowDTO.getStatus().toString())) {
status = APIConstants.AppRegistrationStatus.REGISTRATION_APPROVED;
}
ApplicationRegistrationWorkflowDTO regWorkFlowDTO;
if (workFlowDTO instanceof ApplicationRegistrationWorkflowDTO) {
regWorkFlowDTO = (ApplicationRegistrationWorkflowDTO) workFlowDTO;
} else {
String message = "Invalid workflow type found";
log.error(message);
throw new WorkflowException(message);
}
dao.populateAppRegistrationWorkflowDTO(regWorkFlowDTO);
dao.updateApplicationRegistration(status, regWorkFlowDTO.getKeyType(), regWorkFlowDTO.getApplication().getId(), regWorkFlowDTO.getKeyManager());
} catch (APIManagementException e) {
log.error("Error while completing Application Registration entry.", e);
throw new WorkflowException("Error while completing Application Registration entry.", e);
}
return new GeneralWorkflowResponse();
}
use of org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO in project carbon-apimgt by wso2.
the class AbstractApplicationRegistrationWorkflowExecutor method dogenerateKeysForApplication.
public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO) throws APIManagementException {
log.debug("Registering Application and creating an Access Token... ");
Application application = workflowDTO.getApplication();
Subscriber subscriber = application.getSubscriber();
ApiMgtDAO dao = ApiMgtDAO.getInstance();
if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
dao.populateAppRegistrationWorkflowDTO(workflowDTO);
}
try {
// get new key manager
// Here the default flow is set expecting an ID as the keymanager as this flow only involves new applications
String keyManagerId = workflowDTO.getKeyManager();
KeyManagerConfigurationDTO km = dao.getKeyManagerConfigurationByUUID(keyManagerId);
String tenantDomain = km.getOrganization();
String keyManagerName = km.getName();
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
if (keyManager == null) {
throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
}
workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().setClientName(application.getName());
// set applications attributes to the oAuthApplicationInfo
workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
// createApplication on oAuthorization server.
OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());
// update associateApplication
ApplicationUtils.updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerId);
// change create application status in to completed.
dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED, workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerId);
workflowDTO.setApplicationInfo(oAuthApplication);
AccessTokenInfo tokenInfo;
Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
} else {
tokenInfo = new AccessTokenInfo();
tokenInfo.setAccessToken("");
tokenInfo.setValidityPeriod(0L);
String[] noScopes = new String[] { "N/A" };
tokenInfo.setScope(noScopes);
oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
}
workflowDTO.setAccessTokenInfo(tokenInfo);
} catch (Exception e) {
APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
}
}
use of org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO in project carbon-apimgt by wso2.
the class ApplicationRegistrationSimpleWorkflowExecutor method complete.
/**
* Complete the external process status
* Based on the workflow status we will update the status column of the
* Application table
*
* @param workFlowDTO - WorkflowDTO
*/
public WorkflowResponse complete(WorkflowDTO workFlowDTO) throws WorkflowException {
if (log.isDebugEnabled()) {
log.info("Complete Application Registration Workflow..");
}
ApplicationRegistrationWorkflowDTO regWFDTO = (ApplicationRegistrationWorkflowDTO) workFlowDTO;
ApiMgtDAO dao = ApiMgtDAO.getInstance();
try {
dao.createApplicationRegistrationEntry((ApplicationRegistrationWorkflowDTO) workFlowDTO, false);
generateKeysForApplication(regWFDTO);
} catch (APIManagementException e) {
String msg = "Error occurred when updating the status of the Application creation process";
log.error(msg, e);
throw new WorkflowException(e.getMessage(), e);
}
return new GeneralWorkflowResponse();
}
use of org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO in project carbon-apimgt by wso2.
the class APIConsumerImpl method requestApprovalForApplicationRegistration.
/**
* This method specifically implemented for REST API by removing application and data access logic
* from host object layer. So as per new implementation we need to pass requested scopes to this method
* as tokenScope. So we will do scope related other logic here in this method.
* So host object should only pass required 9 parameters.
*/
@Override
public Map<String, Object> requestApprovalForApplicationRegistration(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String jsonString, String keyManagerName, String tenantDomain, boolean isImportMode) throws APIManagementException {
boolean isTenantFlowStarted = false;
if (StringUtils.isEmpty(tenantDomain)) {
tenantDomain = MultitenantUtils.getTenantDomain(userId);
} else {
int tenantId = APIUtil.getInternalOrganizationId(tenantDomain);
// To handle choreo scenario.
if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
}
String keyManagerId = null;
if (keyManagerName != null) {
KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
if (keyManagerConfiguration == null) {
keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
if (keyManagerConfiguration != null) {
keyManagerId = keyManagerName;
keyManagerName = keyManagerConfiguration.getName();
}
} else {
keyManagerId = keyManagerConfiguration.getUuid();
}
if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
}
if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
}
Object enableOauthAppCreation = keyManagerConfiguration.getProperty(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION);
if (enableOauthAppCreation != null && !(Boolean) enableOauthAppCreation) {
if (isImportMode) {
log.debug("Importing application when KM OAuth App creation is disabled. Trying to map keys");
// in the `jsonString` and ApplicationUtils#createOauthAppRequest logic handles it.
return mapExistingOAuthClient(jsonString, userId, null, application.getName(), tokenType, APIConstants.DEFAULT_TOKEN_TYPE, keyManagerName, tenantDomain);
} else {
throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
}
}
}
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
}
// check if there are any existing key mappings set for the application and the key manager.
if (apiMgtDAO.isKeyMappingExistsForApplication(application.getId(), keyManagerName, keyManagerId, tokenType)) {
throw new APIManagementException("Key Mappings already exists for application " + application.getName(), ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
}
// initiate WorkflowExecutor
WorkflowExecutor appRegistrationWorkflow = null;
// initiate ApplicationRegistrationWorkflowDTO
ApplicationRegistrationWorkflowDTO appRegWFDto = null;
ApplicationKeysDTO appKeysDto = new ApplicationKeysDTO();
boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
boolean isUserAppOwner;
if (isCaseInsensitiveComparisons) {
isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(userId);
} else {
isUserAppOwner = application.getSubscriber().getName().equals(userId);
}
if (!isUserAppOwner) {
throw new APIManagementException("user: " + application.getSubscriber().getName() + ", " + "attempted to generate tokens for application owned by: " + userId);
}
// if its a PRODUCTION application.
if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
// initiate workflow type. By default simple work flow will be
// executed.
appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
} else // if it is a sandBox application.
if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
// if its a SANDBOX application.
appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
} else {
throw new APIManagementException("Invalid Token Type '" + tokenType + "' requested.");
}
// check whether callback url is empty and set null
if (StringUtils.isBlank(callbackUrl)) {
callbackUrl = null;
}
String applicationTokenType = application.getTokenType();
if (StringUtils.isEmpty(application.getTokenType())) {
applicationTokenType = APIConstants.DEFAULT_TOKEN_TYPE;
}
// Build key manager instance and create oAuthAppRequest by jsonString.
OAuthAppRequest request = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, applicationTokenType, tenantDomain, keyManagerName);
request.getOAuthApplicationInfo().addParameter(ApplicationConstants.VALIDITY_PERIOD, validityTime);
request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_CALLBACK_URL, callbackUrl);
request.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
// Setting request values in WorkflowDTO - In future we should keep
// Application/OAuthApplication related
// information in the respective entities not in the workflowDTO.
appRegWFDto.setStatus(WorkflowStatus.CREATED);
appRegWFDto.setCreatedTime(System.currentTimeMillis());
appRegWFDto.setTenantDomain(tenantDomain);
appRegWFDto.setTenantId(tenantId);
appRegWFDto.setExternalWorkflowReference(appRegistrationWorkflow.generateUUID());
appRegWFDto.setWorkflowReference(appRegWFDto.getExternalWorkflowReference());
appRegWFDto.setApplication(application);
appRegWFDto.setKeyManager(keyManagerId);
request.setMappingId(appRegWFDto.getWorkflowReference());
if (!application.getSubscriber().getName().equals(userId)) {
appRegWFDto.setUserName(application.getSubscriber().getName());
} else {
appRegWFDto.setUserName(userId);
}
appRegWFDto.setCallbackUrl(appRegistrationWorkflow.getCallbackURL());
appRegWFDto.setAppInfoDTO(request);
appRegWFDto.setDomainList(allowedDomains);
appRegWFDto.setKeyDetails(appKeysDto);
appRegistrationWorkflow.execute(appRegWFDto);
Map<String, Object> keyDetails = new HashMap<String, Object>();
keyDetails.put(APIConstants.FrontEndParameterNames.KEY_STATE, appRegWFDto.getStatus().toString());
OAuthApplicationInfo applicationInfo = appRegWFDto.getApplicationInfo();
String keyMappingId = apiMgtDAO.getKeyMappingIdFromApplicationIdKeyTypeAndKeyManager(application.getId(), tokenType, keyManagerId);
keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
if (applicationInfo != null) {
keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, applicationInfo.getClientId());
keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, applicationInfo.getClientSecret());
keyDetails.put(ApplicationConstants.OAUTH_APP_DETAILS, applicationInfo.getJsonString());
keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.CREATED.name());
}
// There can be instances where generating the Application Token is
// not required. In those cases,
// token info will have nothing.
AccessTokenInfo tokenInfo = appRegWFDto.getAccessTokenInfo();
if (tokenInfo != null) {
keyDetails.put("accessToken", tokenInfo.getAccessToken());
keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
keyDetails.put("tokenDetails", tokenInfo.getJSONString());
keyDetails.put("tokenScope", tokenInfo.getScopes());
}
JSONObject appLogObject = new JSONObject();
appLogObject.put("Generated keys for application", application.getName());
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
// if its a PRODUCTION application.
if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
// get the workflow state once the executor is executed.
WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
// wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
if (wfDTO != null) {
if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
}
} else {
ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
}
} else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
// get the workflow state once the executor is executed.
WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
// wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
if (wfDTO != null) {
if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
}
} else {
ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
}
}
return keyDetails;
} catch (WorkflowException e) {
log.error("Could not execute Workflow", e);
throw new APIManagementException(e);
} finally {
if (isTenantFlowStarted) {
endTenantFlow();
}
}
}
Aggregations