Merge branch 'master' of https://github.com/wso2/carbon-device-mgt into scope-impl

merge-requests/7/head
mharindu 8 years ago
commit ccdcea0109

@ -23,7 +23,7 @@ var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
function appendQueryParam (url, queryParam , value) {
if (url.indexOf("?") > 0) {

@ -26,7 +26,7 @@ var deviceModule = require("/app/modules/device.js").deviceModule;
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var userModule = require("/app/modules/user.js").userModule;
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var user = session.get(constants.USER_SESSION_KEY);
var result;

@ -24,7 +24,7 @@ var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var user = session.get(constants.USER_SESSION_KEY);
var result;

@ -24,7 +24,7 @@ var uriMatcher = new URIMatcher(String(uri));
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
if (uriMatcher.match("/{context}/api/invoker/execute/")) {
var restAPIRequestDetails = request.getContent();
@ -97,8 +97,8 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) {
break;
}
} catch (e) {
log.error("Exception occurred while trying to access backend " +
"REST API services from Jaggery API invoker layer", e);
throw new Error("Exception occurred while trying to access " +
"backend REST API services from Jaggery API invoker layer", e);
}
}
%>

@ -22,7 +22,7 @@ var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/operation-api.jag");
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/operation/paginate")) {

@ -1,27 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
@Deprecated - new
*/
// var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"];
// var tokenCookie = apiWrapperUtil.refreshToken();
// print(tokenCookie);
%>

@ -27,8 +27,8 @@ var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var userModule = require("/app/modules/user.js").userModule;
var deviceModule = require("/app/modules/device.js").deviceModule;
var utility = require("/app/modules/utility.js").utility;
var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"];
var util = require("/app/modules/util.js").util;
var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
var util = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var responseProcessor = require('utils').response;
@ -46,10 +46,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) {
if (log.isDebugEnabled()) {
log.debug("User Logged In : " + user);
}
apiWrapperUtil.setupAccessTokenPair("password", {
"username": username,
"password": password
});
apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password);
}, function () {
response = responseProcessor.buildSuccessResponse(response, 200, {'sessionId': session.getId()});
});
@ -68,7 +65,8 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) {
if (log.isDebugEnabled()) {
log.debug("User Logged In : " + user);
}
apiWrapperUtil.setupAccessTokenPair("password", {"username": username, "password": password});
apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password);
var permissions = userModule.getUIPermissions();
if (permissions.VIEW_DASHBOARD) {
response.sendRedirect(constants.WEB_APP_CONTEXT);

@ -1,68 +1,89 @@
{
"appContext" : "/devicemgt/",
"webAgentContext" : "/devicemgt-web-agent/",
"apiContext" : "api",
"httpsURL" : "https://localhost:8243",
"httpURL" : "%http.ip%",
"httpsWebURL" : "%https.ip%",
"wssURL" : "%https.ip%",
"wsURL" : "%http.ip%",
"dashboardserverURL" : "%https.ip%",
"enrollmentDir": "/emm-web-agent/enrollment",
"iOSConfigRoot" : "%https.ip%/ios-enrollment/",
"iOSAPIRoot" : "%https.ip%/ios/",
"dynamicClientRegistrationEndPoint" : "https://localhost:8243/dynamic-client-web/register/",
"adminService":"%https.ip%",
"idPServer":"https://localhost:8243",
"callBackUrl":"%https.ip%/devicemgt_admin",
"adminUser":"admin@carbon.super",
"adminRole":"admin",
"usernameLength":30,
"ssoConfiguration" : {
"enabled" : false,
"issuer" : "devicemgt",
"appName" : "devicemgt",
"identityProviderURL" : "%https.ip%/sso/samlsso.jag",
"responseSigningEnabled" : "true",
"keyStorePassword" : "wso2carbon",
"identityAlias" : "wso2carbon",
"keyStoreName" : "/repository/resources/security/wso2carbon.jks"
},
"userValidationConfig" : {
"usernameJSRegEx" : "^[\\S]{3,30}$",
"usernameRegExViolationErrorMsg" : "Provided username is invalid.",
"usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.",
"firstnameJSRegEx" : "^[\\S]{3,30}$",
"firstnameRegExViolationErrorMsg" : "Provided first name is invalid.",
"lastnameJSRegEx" : "^[\\S]{3,30}$",
"lastnameRegExViolationErrorMsg" : "Provided last name is invalid.",
"emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/",
"emailRegExViolationErrorMsg" : "Provided email is invalid."
},
"groupValidationConfig": {
"groupNameJSRegEx": "^[\\S]{3,30}$",
"groupNameRegExViolationErrorMsg": "Provided group name is invalid.",
"groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces."
},
"roleValidationConfig" : {
"rolenameJSRegEx" : "^[\\S]{3,30}$",
"rolenameRegExViolationErrorMsg" : "Provided role name is invalid.",
"rolenameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces."
},
"generalConfig" : {
"host" : "https://localhost:9443",
"companyName" : "WSO2 Carbon Device Manager",
"browserTitle" : "WSO2 Device Manager",
"copyrightPrefix" : "\u00A9 %date-year%, ",
"copyrightOwner" : "WSO2 Inc.",
"copyrightOwnersSite" : "http://www.wso2.org",
"copyrightSuffix" : " All Rights Reserved."
},
"scopes" : ["license-add", "license-view", "device-view", "device-info", "device-list", "device-view-own",
"device-modify", "device-search", "operation-install", "operation-view", "operation-modify", "operation-uninstall",
"group-add", "group-share", "group-modify", "group-view", "group-remove", "certificate-modify", "certificate-view",
"configuration-view", "configuration-modify", "policy-view", "policy-modify", "device-notification-view",
"device-notification-modify", "feature-view", "arduino_device", "arduino_user", " android_sense_user",
"virtual_firealarm_user", "raspberrypi_user", "roles-view", "roles-modify", "roles-remove", "roles-add",
"user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"]
"appContext": "/emm/",
"webAgentContext" : "/emm-web-agent/",
"apiContext": "api",
"httpsURL" : "%https.ip%",
"httpURL" : "%http.ip%",
"httpsWebURL" : "%https.ip%",
"wssURL" : "%https.ip%",
"wsURL" : "%http.ip%",
"dashboardServerURL" : "%https.ip%",
"enrollmentDir": "/emm-web-agent/enrollment",
"iOSConfigRoot" : "%https.ip%/ios-enrollment/",
"iOSAPIRoot" : "%https.ip%/ios/",
"adminService": "%https.ip%",
"oauthProvider": {
"appRegistration": {
"appType": "webapp",
"clientName": "emm",
"owner": "admin@carbon.super",
"dynamicClientAppRegistrationServiceURL": "%https.ip%/dynamic-client-web/register",
"apiManagerClientAppRegistrationServiceURL": "%https.ip%/api-application-registration/register/tenants",
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer",
"tokenScope": "admin",
"callbackUrl": "%https.ip%/api/device-mgt/v1.0"
},
"tokenServiceURL": "%https.ip%/oauth2/token"
},
"adminUser":"admin@carbon.super",
"adminRole":"admin",
"usernameLength":30,
"pageSize":10,
"ssoConfiguration" : {
"enabled" : false,
"issuer" : "devicemgt",
"appName" : "devicemgt",
"identityProviderURL" : "%https.ip%/sso/samlsso.jag",
"responseSigningEnabled" : "true",
"keyStorePassword" : "wso2carbon",
"identityAlias" : "wso2carbon",
"keyStoreName" : "/repository/resources/security/wso2carbon.jks"
},
"userValidationConfig" : {
"usernameJSRegEx" : "^[\\S]{3,30}$",
"usernameRegExViolationErrorMsg" : "Provided username is invalid.",
"usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.",
"firstnameJSRegEx" : "^[\\S]{3,30}$",
"firstnameRegExViolationErrorMsg" : "Provided first name is invalid.",
"lastnameJSRegEx" : "^[\\S]{3,30}$",
"lastnameRegExViolationErrorMsg" : "Provided last name is invalid.",
"emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/",
"emailRegExViolationErrorMsg" : "Provided email is invalid."
},
"groupValidationConfig": {
"groupNameJSRegEx": "^[\\S]{3,30}$",
"groupNameRegExViolationErrorMsg": "Provided group name is invalid.",
"groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces."
},
"roleValidationConfig" : {
"roleNameJSRegEx" : "^[\\S]{3,30}$",
"roleNameRegExViolationErrorMsg" : "Provided role name is invalid.",
"roleNameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces."
},
"generalConfig" : {
"host" : "https://localhost:9443",
"companyName" : "WSO2 Carbon Device Manager",
"browserTitle" : "WSO2 Device Manager",
"copyrightPrefix" : "\u00A9 %date-year%, ",
"copyrightOwner" : "WSO2 Inc.",
"copyrightOwnersSite" : "http://www.wso2.org",
"copyrightSuffix" : " All Rights Reserved."
},
"scopes" : [
"license-add", "license-view", "device-view",
"device-info", "device-list", "device-view-own", "device-modify", "device-search",
"operation-install", "operation-view", "operation-modify", "operation-uninstall",
"group-add", "group-share", "group-modify", "group-view", "group-remove",
"certificate-modify", "certificate-view",
"configuration-view", "configuration-modify",
"policy-view", "policy-modify",
"device-notification-view", "device-notification-modify",
"feature-view",
"roles-view", "roles-modify", "roles-remove", "roles-add",
"user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"
],
"isOAuthEnabled" : true,
"backendRestEndpoints" : {
"deviceMgt" : "/api/device-mgt/v1.0"
}
}

@ -1,155 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* ----------------------------------------------------------------------------
* Following module includes invokers
* at Jaggery Layer for calling Backend Services, protected by OAuth Tokens.
* These Services include both REST and SOAP Services.
* ----------------------------------------------------------------------------
*/
var handlers = function () {
var log = new Log("/app/modules/token-handlers.js");
var tokenUtil = require("/app/modules/util.js")["util"];
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var privateMethods = {};
var publicMethods = {};
privateMethods.setUpEncodedTenantBasedClientCredentials = function (username) {
if (!username) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context. No username is found as " +
"input - setUpEncodedTenantBasedClientCredentials(x)");
} else {
var dynamicClientCredentials = tokenUtil.getDynamicClientCredentials();
if (!dynamicClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)");
} else {
var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials);
if (!jwtToken) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"a jwt token - setUpEncodedTenantBasedClientCredentials(x)");
} else {
var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(username, jwtToken);
if (!tenantBasedClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " +
"to obtain such credentials - setUpEncodedTenantBasedClientCredentials(x)");
} else {
var encodedTenantBasedClientCredentials =
tokenUtil.encode(tenantBasedClientCredentials["clientId"] + ":" +
tenantBasedClientCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials);
}
}
}
}
};
publicMethods.setupAccessTokenPairByPasswordGrantType = function (username, password) {
if (!username || !password) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " +
"password grant type. Either username, password or both are missing as " +
"input - setupAccessTokenPairByPasswordGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientCredentials(username);
var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]);
if (!encodedClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " +
"password grant type. Encoded client credentials are " +
"missing - setupAccessTokenPairByPasswordGrantType(x, y)");
} else {
var accessTokenPair;
// accessTokenPair will include current access token as well as current refresh token
var arrayOfScopes = devicemgtProps["scopes"];
var stringOfScopes = "";
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
accessTokenPair = tokenUtil.
getTokenWithPasswordGrantType(username,
encodeURIComponent(password), encodedClientCredentials, stringOfScopes);
if (!accessTokenPair) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access " +
"token pair by password grant type. Error in token " +
"retrieval - setupAccessTokenPairByPasswordGrantType(x, y)");
} else {
// setting up access token pair into session context as a string
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair));
}
}
}
};
publicMethods.setupAccessTokenPairBySamlGrantType = function (username, samlToken) {
if (!username || !samlToken) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " +
"saml grant type. Either username, samlToken or both are missing as " +
"input - setupAccessTokenPairByPasswordGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientCredentials(username);
var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]);
if (!encodedClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair " +
"by saml grant type. Encoded client credentials are " +
"missing - setupAccessTokenPairByPasswordGrantType(x, y)");
} else {
var accessTokenPair;
// accessTokenPair will include current access token as well as current refresh token
accessTokenPair = tokenUtil.
getTokenWithSAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION");
if (!accessTokenPair) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access token " +
"pair by password grant type. Error in token " +
"retrieval - setupAccessTokenPairByPasswordGrantType(x, y)");
} else {
// setting up access token pair into session context as a string
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair));
}
}
}
};
publicMethods.refreshToken = function () {
var accessTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]));
// accessTokenPair includes current access token as well as current refresh token
var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]);
if (!accessTokenPair || !encodedClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Error in refreshing tokens. Either the access " +
"token pair, encoded client credentials or both input are not found under " +
"session context - refreshToken()");
} else {
var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials);
if (!newAccessTokenPair) {
log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " +
"session context with new access token pair - refreshToken()");
} else {
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newAccessTokenPair));
}
}
};
return publicMethods;
}();

@ -59,8 +59,8 @@ var USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT =
var SOAP_VERSION = 1.2;
var WEB_SERVICE_ADDRESSING_VERSION = 1.0;
var ACCESS_TOKEN_PAIR_IDENTIFIER = "accessTokenPair";
var ENCODED_CLIENT_KEYS_IDENTIFIER = "encodedClientKey";
var TOKEN_PAIR = "tokenPair";
var ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS = "encodedTenantBasedClientAppCredentials";
var CONTENT_TYPE_IDENTIFIER = "Content-Type";
var CONTENT_DISPOSITION_IDENTIFIER = "Content-Disposition";
var APPLICATION_JSON = "application/json";

@ -23,20 +23,20 @@ deviceModule = function () {
var utility = require('/app/modules/utility.js').utility;
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var ArrayList = Packages.java.util.ArrayList;
var Properties = Packages.java.util.Properties;
var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
// var ArrayList = Packages.java.util.ArrayList;
// var Properties = Packages.java.util.Properties;
// var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
// var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
// var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
// var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
// var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
var publicMethods = {};
var privateMethods = {};
var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";
// var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";
privateMethods.validateAndReturn = function (value) {
return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
@ -45,57 +45,57 @@ deviceModule = function () {
/*
@Deprecated
*/
publicMethods.listDevices = function () {
var carbonUser = session.get(constants.USER_SESSION_KEY);
var utility = require('/app/modules/utility.js').utility;
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
try {
utility.startTenantFlow(carbonUser);
var deviceManagementService = utility.getDeviceManagementService();
var devices = deviceManagementService.getAllDevices();
var deviceList = [];
var i, device, propertiesList, deviceObject;
for (i = 0; i < devices.size(); i++) {
device = devices.get(i);
propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
deviceObject = {};
deviceObject[constants.DEVICE_IDENTIFIER] =
privateMethods.validateAndReturn(device.getDeviceIdentifier());
deviceObject[constants.DEVICE_NAME] =
privateMethods.validateAndReturn(device.getName());
deviceObject[constants.DEVICE_OWNERSHIP] =
privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
deviceObject[constants.DEVICE_OWNER] =
privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
deviceObject[constants.DEVICE_TYPE] =
privateMethods.validateAndReturn(device.getType());
deviceObject[constants.DEVICE_PROPERTIES] = {};
if (device.getType() == constants.PLATFORM_IOS) {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
} else {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
}
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
deviceList.push(deviceObject);
}
return deviceList;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
// publicMethods.listDevices = function () {
// var carbonUser = session.get(constants.USER_SESSION_KEY);
// var utility = require('/app/modules/utility.js').utility;
// if (!carbonUser) {
// log.error("User object was not found in the session");
// throw constants.ERRORS.USER_NOT_FOUND;
// }
// try {
// utility.startTenantFlow(carbonUser);
// var deviceManagementService = utility.getDeviceManagementService();
// var devices = deviceManagementService.getAllDevices();
// var deviceList = [];
// var i, device, propertiesList, deviceObject;
// for (i = 0; i < devices.size(); i++) {
// device = devices.get(i);
// propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
//
// deviceObject = {};
// deviceObject[constants.DEVICE_IDENTIFIER] =
// privateMethods.validateAndReturn(device.getDeviceIdentifier());
// deviceObject[constants.DEVICE_NAME] =
// privateMethods.validateAndReturn(device.getName());
// deviceObject[constants.DEVICE_OWNERSHIP] =
// privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
// deviceObject[constants.DEVICE_OWNER] =
// privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
// deviceObject[constants.DEVICE_TYPE] =
// privateMethods.validateAndReturn(device.getType());
// deviceObject[constants.DEVICE_PROPERTIES] = {};
// if (device.getType() == constants.PLATFORM_IOS) {
// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
// } else {
// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
// }
// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
//
// deviceList.push(deviceObject);
// }
// return deviceList;
// } catch (e) {
// throw e;
// } finally {
// utility.endTenantFlow();
// }
// };
/*
@Deprecated
@ -103,105 +103,105 @@ deviceModule = function () {
/*
Get the supported features by the device type
*/
publicMethods.getFeatures = function (deviceType) {
var carbonUser = session.get(constants.USER_SESSION_KEY);
var utility = require('/app/modules/utility.js').utility;
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
try {
utility.startTenantFlow(carbonUser);
var deviceManagementService = utility.getDeviceManagementService();
var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
var featuresConverted = {};
if (features) {
var i, feature, featureObject;
for (i = 0; i < features.size(); i++) {
feature = features.get(i);
featureObject = {};
featureObject[constants.FEATURE_NAME] = feature.getName();
featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
featuresConverted[feature.getName()] = featureObject;
}
}
return featuresConverted;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
// publicMethods.getFeatures = function (deviceType) {
// var carbonUser = session.get(constants.USER_SESSION_KEY);
// var utility = require('/app/modules/utility.js').utility;
// if (!carbonUser) {
// log.error("User object was not found in the session");
// throw constants.ERRORS.USER_NOT_FOUND;
// }
// try {
// utility.startTenantFlow(carbonUser);
// var deviceManagementService = utility.getDeviceManagementService();
// var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
// var featuresConverted = {};
// if (features) {
// var i, feature, featureObject;
// for (i = 0; i < features.size(); i++) {
// feature = features.get(i);
// featureObject = {};
// featureObject[constants.FEATURE_NAME] = feature.getName();
// featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
// featuresConverted[feature.getName()] = featureObject;
// }
// }
// return featuresConverted;
// } catch (e) {
// throw e;
// } finally {
// utility.endTenantFlow();
// }
// };
/*
@Deprecated
*/
publicMethods.performOperation = function (devices, operation) {
var carbonUser = session.get(constants.USER_SESSION_KEY);
var utility = require('/app/modules/utility.js').utility;
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
try {
utility.startTenantFlow(carbonUser);
var deviceManagementService = utility.getDeviceManagementService();
var operationInstance;
if (operation.type == "COMMAND") {
operationInstance = new CommandOperation();
} else if (operation.type == "CONFIG") {
operationInstance = new ConfigOperation();
} else {
operationInstance = new SimpleOperation();
}
operationInstance.setCode(operation.featureName);
var props = new Properties();
var i, object;
for (i = 0; i < operation.properties.length; i++) {
object = properties[i];
props.setProperty(object.key, object.value);
}
operationInstance.setProperties(props);
var deviceList = new ArrayList();
var j, device, deviceIdentifier;
for (j = 0; j < devices.length; i++) {
device = devices[j];
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.id);
deviceIdentifier.setType(device.type);
deviceList.add(deviceIdentifier);
}
deviceManagementService.addOperation(operationInstance, deviceList);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
// publicMethods.performOperation = function (devices, operation) {
// var carbonUser = session.get(constants.USER_SESSION_KEY);
// var utility = require('/app/modules/utility.js').utility;
// if (!carbonUser) {
// log.error("User object was not found in the session");
// throw constants.ERRORS.USER_NOT_FOUND;
// }
// try {
// utility.startTenantFlow(carbonUser);
// var deviceManagementService = utility.getDeviceManagementService();
// var operationInstance;
// if (operation.type == "COMMAND") {
// operationInstance = new CommandOperation();
// } else if (operation.type == "CONFIG") {
// operationInstance = new ConfigOperation();
// } else {
// operationInstance = new SimpleOperation();
// }
// operationInstance.setCode(operation.featureName);
// var props = new Properties();
// var i, object;
// for (i = 0; i < operation.properties.length; i++) {
// object = properties[i];
// props.setProperty(object.key, object.value);
// }
// operationInstance.setProperties(props);
// var deviceList = new ArrayList();
// var j, device, deviceIdentifier;
// for (j = 0; j < devices.length; i++) {
// device = devices[j];
// deviceIdentifier = new DeviceIdentifier();
// deviceIdentifier.setId(device.id);
// deviceIdentifier.setType(device.type);
// deviceList.add(deviceIdentifier);
// }
// deviceManagementService.addOperation(operationInstance, deviceList);
// } catch (e) {
// throw e;
// } finally {
// utility.endTenantFlow();
// }
// };
/*
@Deprecated
*/
privateMethods.getDevice = function (type, deviceId) {
var carbonUser = session.get(constants.USER_SESSION_KEY);
var utility = require('/app/modules/utility.js').utility;
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
try {
utility.startTenantFlow(carbonUser);
var deviceManagementService = utility.getDeviceManagementService();
var deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(type);
deviceIdentifier.setId(deviceId);
return deviceManagementService.getDevice(deviceIdentifier);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
// privateMethods.getDevice = function (type, deviceId) {
// var carbonUser = session.get(constants.USER_SESSION_KEY);
// var utility = require('/app/modules/utility.js').utility;
// if (!carbonUser) {
// log.error("User object was not found in the session");
// throw constants.ERRORS.USER_NOT_FOUND;
// }
// try {
// utility.startTenantFlow(carbonUser);
// var deviceManagementService = utility.getDeviceManagementService();
// var deviceIdentifier = new DeviceIdentifier();
// deviceIdentifier.setType(type);
// deviceIdentifier.setId(deviceId);
// return deviceManagementService.getDevice(deviceIdentifier);
// } catch (e) {
// throw e;
// } finally {
// utility.endTenantFlow();
// }
// };
/*
@Updated
@ -218,37 +218,37 @@ deviceModule = function () {
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId;
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
var device = responsePayload.responseContent;
if (device) {
var propertiesList = device["properties"];
var properties = {};
if (propertiesList){
for (var i = 0; i < propertiesList.length; i++) {
properties[propertiesList[i]["name"]] = propertiesList[i]["value"];
}
}
var deviceObject = {};
deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
deviceObject[constants["DEVICE_NAME"]] = device["name"];
deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
deviceObject[constants["DEVICE_TYPE"]] = device["type"];
if (device["type"] == constants["PLATFORM_IOS"]) {
properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
delete properties[constants["DEVICE_PRODUCT"]];
properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
url, function (responsePayload) {
var device = responsePayload.responseContent;
if (device) {
var propertiesList = device["properties"];
var properties = {};
if (propertiesList){
for (var i = 0; i < propertiesList.length; i++) {
properties[propertiesList[i]["name"]] = propertiesList[i]["value"];
}
deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
return deviceObject;
}
},
function (responsePayload) {
var response = {};
response["status"] = "error";
return response;
var deviceObject = {};
deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
deviceObject[constants["DEVICE_NAME"]] = device["name"];
deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
deviceObject[constants["DEVICE_TYPE"]] = device["type"];
if (device["type"] == constants["PLATFORM_IOS"]) {
properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
delete properties[constants["DEVICE_PRODUCT"]];
properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
}
deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
return deviceObject;
}
},
function (responsePayload) {
var response = {};
response["status"] = "error";
return response;
}
);
} catch (e) {
throw e;
@ -268,19 +268,19 @@ deviceModule = function () {
url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count";
} else if (uiPermissions.LIST_OWN_DEVICES) {
url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username
+ "/count";
+ "/count";
} else {
log.error("Access denied for user: " + carbonUser.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
} else {
log.error("User object was not found in the session");
@ -291,13 +291,13 @@ deviceModule = function () {
publicMethods.getDeviceTypes = function () {
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types";
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
@ -328,16 +328,16 @@ deviceModule = function () {
publicMethods.getDevices = function (userName) {
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName;
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
for (var i = 0; i < responsePayload.length; i++) {
responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type);
}
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
url, function (responsePayload) {
for (var i = 0; i < responsePayload.length; i++) {
responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type);
}
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
return publicMethods;

@ -24,7 +24,7 @@ var groupModule = {};
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var utility = require("/app/modules/utility.js").utility;
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups";

@ -1,98 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
@Deprecated - new
*/
/**
* This invokerRequestWrapper contains the wrappers for invoker util requests.
*/
//var invokerRequestWrapper = function () {
//
// var constants = require("/modules/constants.js");
// var serviceInvokers = require("/modules/backend-service-invoker.js").backendServiceInvoker;
//
// var publicWrappers = [];
//
// publicWrappers.initiate = function (method, url, payload) {
// switch (method) {
// case constants.HTTP_GET:
// var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
// var response = {};
// response.content = responsePayload["responseContent"];
// response.status = "success";
// return response;
// },
// function (responsePayload) {
// var response = {};
// response.content = responsePayload;
// response.status = "error";
// return response;
// });
// return response;
// break;
// case constants.HTTP_POST:
// var response = serviceInvokers.XMLHttp.post(url, payload, function (responsePayload) {
// var response = {};
// response.content = responsePayload["responseContent"];
// response.status = "success";
// return response;
// },
// function (responsePayload) {
// var response = {};
// response.content = responsePayload;
// response.status = "error";
// return response;
// });
// return response;
// break;
// case constants.HTTP_PUT:
// var response = serviceInvokers.XMLHttp.put(url, payload, function (responsePayload) {
// var response = {};
// response.content = responsePayload["responseContent"];
// response.status = "success";
// return response;
// },
// function (responsePayload) {
// var response = {};
// response.content = responsePayload;
// response.status = "error";
// return response;
// });
// return response;
// break;
// case constants.HTTP_DELETE:
// var response = serviceInvokers.XMLHttp.delete(url, function (responsePayload) {
// var response = {};
// response.content = responsePayload["responseContent"];
// response.status = "success";
// return response;
// },
// function (responsePayload) {
// var response = {};
// response.content = responsePayload;
// response.status = "error";
// return response;
// });
// return response;
// break;
// }
// }
//
//}();

@ -24,11 +24,11 @@ var onFail;
var constants = require("/app/modules/constants.js");
onSuccess = function (context) {
var utility = require("/app/modules/utility.js").utility;
var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"];
var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
if (context.input.samlToken) {
apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken);
apiWrapperUtil.setupTokenPairBySamlGrantType(context.input.username, context.input.samlToken);
} else {
apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(context.input.username, context.input.password);
apiWrapperUtil.setupTokenPairByPasswordGrantType(context.input.username, context.input.password);
}
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var carbonServer = require("carbon").server;

@ -0,0 +1,286 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var utils = function () {
var log = new Log("/app/modules/oauth/token-handler-utils.js");
var deviceMgtProps = require("/app/conf/reader/main.js")["conf"];
var constants = require("/app/modules/constants.js");
var carbon = require("carbon");
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
var String = Packages.java.lang.String;
var publicMethods = {};
var privateMethods = {};
publicMethods.encode = function (payload) {
return new String(Base64.encodeBase64(new String(payload).getBytes()));
};
publicMethods.decode = function (payload) {
return new String(Base64.decodeBase64(new String(payload).getBytes()));
};
publicMethods.getDynamicClientAppCredentials = function () {
// setting up dynamic client application properties
var dcAppProperties = {
"applicationType": deviceMgtProps["oauthProvider"]["appRegistration"]["appType"],
"clientName": deviceMgtProps["oauthProvider"]["appRegistration"]["clientName"],
"owner": deviceMgtProps["oauthProvider"]["appRegistration"]["owner"],
"tokenScope": deviceMgtProps["oauthProvider"]["appRegistration"]["tokenScope"],
"grantType": deviceMgtProps["oauthProvider"]["appRegistration"]["grantType"],
"callbackUrl": deviceMgtProps["oauthProvider"]["appRegistration"]["callbackUrl"],
"saasApp" : true
};
// calling dynamic client app registration service endpoint
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
["dynamicClientAppRegistrationServiceURL"];
var requestPayload = dcAppProperties;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(stringify(requestPayload));
var dynamicClientAppCredentials = {};
if (xhr["status"] == 201 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
dynamicClientAppCredentials["clientId"] = responsePayload["client_id"];
dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"];
} else if (xhr["status"] == 400) {
log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Bad request. Invalid data provided as dynamic client application properties.");
dynamicClientAppCredentials = null;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Error in retrieving dynamic client credentials.");
dynamicClientAppCredentials = null;
}
// returning dynamic client credentials
return dynamicClientAppCredentials;
};
publicMethods.getTokenPairByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) {
if (!username || !password || !encodedClientAppCredentials || !scopes) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " +
"grant type. No username, password, encoded client app credentials or scopes are " +
"found - getTokenPairByPasswordGrantType(a, b, c, d)");
return null;
} else {
// calling oauth provider token service endpoint
var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=password&username=" +
username + "&password=" + password + "&scope=" + scopes;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenPair = {};
tokenPair["accessToken"] = responsePayload["access_token"];
tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairByPasswordGrantType(a, b, c, d)");
return null;
}
}
};
publicMethods.getTokenPairBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) {
if (!assertion || !encodedClientAppCredentials || !scopes) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " +
"grant type. No assertion, encoded client app credentials or scopes are " +
"found - getTokenPairBySAMLGrantType(x, y, z)");
return null;
} else {
var assertionXML = publicMethods.decode(assertion);
/*
TODO: make assertion extraction with proper parsing. Since Jaggery XML parser seem
to add formatting which causes signature verification to fail.
*/
var assertionStartMarker = "<saml2:Assertion";
var assertionEndMarker = "<\/saml2:Assertion>";
var assertionStartIndex = assertionXML.indexOf(assertionStartMarker);
var assertionEndIndex = assertionXML.indexOf(assertionEndMarker);
var extractedAssertion;
if (assertionStartIndex == -1 || assertionEndIndex == -1) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access " +
"token by saml grant type. Issue in assertion format - getTokenPairBySAMLGrantType(x, y, z)");
return null;
} else {
extractedAssertion = assertionXML.
substring(assertionStartIndex, assertionEndIndex) + assertionEndMarker;
var encodedAssertion = publicMethods.encode(extractedAssertion);
// calling oauth provider token service endpoint
var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&" +
"assertion=" + encodeURIComponent(encodedAssertion) + "&scope=" + scopes;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenPair = {};
tokenPair["accessToken"] = responsePayload["access_token"];
tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairBySAMLGrantType(x, y, z)");
return null;
}
}
}
};
publicMethods.getNewTokenPairByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) {
if (!refreshToken || !encodedClientAppCredentials) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " +
"by current refresh token. No refresh token or encoded client app credentials are " +
"found - getNewTokenPairByRefreshToken(x, y, z)");
return null;
} else {
var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=refresh_token&refresh_token=" + refreshToken;
if (scopes) {
requestPayload = requestPayload + "&scope=" + scopes;
}
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenPair = {};
tokenPair["accessToken"] = responsePayload["access_token"];
tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token by " +
"current refresh token - getNewTokenPairByRefreshToken(x, y, z)");
return null;
}
}
};
publicMethods.getAccessTokenByJWTGrantType = function (clientAppCredentials) {
if (!clientAppCredentials) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " +
"by current refresh token. No client app credentials are found " +
"as input - getAccessTokenByJWTGrantType(x)");
return null;
} else {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
return jwtClient.getAccessToken(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"],
deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], null)["accessToken"];
}
};
publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) {
if (!username || !jwtToken) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username or jwt token is found " +
"as input - getTenantBasedClientAppCredentials(x, y)");
return null;
} else {
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials. Unable to obtain a valid tenant domain for provided " +
"username - getTenantBasedClientAppCredentials(x, y)");
return null;
} else {
var cachedTenantBasedClientAppCredentials = privateMethods.
getCachedTenantBasedClientAppCredentials(tenantDomain);
if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials;
} else {
// register a tenant based client app at API Manager
var applicationName = "webapp_" + tenantDomain;
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
["apiManagerClientAppRegistrationServiceURL"] +
"?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + jwtToken);
xhr.send();
if (xhr["status"] == 201 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tenantBasedClientAppCredentials = {};
tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"];
tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"];
privateMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials);
return tenantBasedClientAppCredentials;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials from API " +
"Manager - getTenantBasedClientAppCredentials(x, y)");
return null;
}
}
}
}
};
privateMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientAppCredentials) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (!cachedTenantBasedClientAppCredentialsMap) {
cachedTenantBasedClientAppCredentialsMap = {};
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap);
} else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
}
};
privateMethods.getCachedTenantBasedClientAppCredentials = function (tenantDomain) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (!cachedTenantBasedClientAppCredentialsMap ||
!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
return null;
} else {
return cachedTenantBasedClientAppCredentialsMap[tenantDomain];
}
};
return publicMethods;
}();

@ -0,0 +1,157 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* -----------------------------------------------------
* Following module includes handlers
* at Jaggery Layer for handling OAuth tokens.
* -----------------------------------------------------
*/
var handlers = function () {
var log = new Log("/app/modules/oauth/token-handlers.js");
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var publicMethods = {};
var privateMethods = {};
publicMethods.setupTokenPairByPasswordGrantType = function (username, password) {
if (!username || !password) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"password grant type. Either username of logged in user, password or both are missing " +
"as input - setupTokenPairByPasswordGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"password grant type. Encoded client credentials are " +
"missing - setupTokenPairByPasswordGrantType(x, y)");
} else {
var tokenPair;
// tokenPair will include current access token as well as current refresh token
var arrayOfScopes = devicemgtProps["scopes"];
var stringOfScopes = "";
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
tokenPair = tokenUtil.
getTokenPairByPasswordGrantType(username,
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
if (!tokenPair) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up " +
"token pair by password grant type. Error in token " +
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
} else {
// setting up access token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
}
}
}
};
publicMethods.setupTokenPairBySamlGrantType = function (username, samlToken) {
if (!username || !samlToken) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
"saml grant type. Either username of logged in user, samlToken or both are missing " +
"as input - setupTokenPairByPasswordGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " +
"by saml grant type. Encoded client credentials are " +
"missing - setupTokenPairByPasswordGrantType(x, y)");
} else {
var tokenPair;
// accessTokenPair will include current access token as well as current refresh token
tokenPair = tokenUtil.
getTokenPairBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION");
if (!tokenPair) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " +
"pair by password grant type. Error in token " +
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
} else {
// setting up access token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
}
}
}
};
publicMethods.refreshTokenPair = function () {
var currentTokenPair = parse(session.get(constants["TOKEN_PAIR"]));
// currentTokenPair includes current access token as well as current refresh token
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
if (!currentTokenPair || !encodedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Error in refreshing tokens. Either the " +
"token pair, encoded client app credentials or both input are not found under " +
"session context - refreshTokenPair()");
} else {
var newTokenPair = tokenUtil.
getNewTokenPairByRefreshToken(currentTokenPair["refreshToken"], encodedClientAppCredentials);
if (!newTokenPair) {
log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing token pair. " +
"Unable to update session context with new access token pair - refreshTokenPair()");
} else {
session.put(constants["TOKEN_PAIR"], stringify(newTokenPair));
}
}
};
privateMethods.setUpEncodedTenantBasedClientAppCredentials = function (username) {
if (!username) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context. No username of logged in user is found as " +
"input - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials();
if (!dynamicClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientAppCredentials);
if (!jwtToken) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
var tenantBasedClientAppCredentials = tokenUtil.
getTenantBasedClientAppCredentials(username, jwtToken);
if (!tenantBasedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " +
"to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
var encodedTenantBasedClientAppCredentials =
tokenUtil.encode(tenantBasedClientAppCredentials["clientId"] + ":" +
tenantBasedClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"],
encodedTenantBasedClientAppCredentials);
}
}
}
}
};
return publicMethods;
}();

@ -24,7 +24,7 @@
* ----------------------------------------------------------------------------
*/
var invokers = function () {
var log = new Log("/app/modules/backend-service-invoker.js");
var log = new Log("/app/modules/oauth/token-protected-service-invokers.js");
var publicXMLHTTPInvokers = {};
var publicHTTPClientInvokers = {};
@ -38,14 +38,14 @@ var invokers = function () {
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var constants = require("/app/modules/constants.js");
var userModule = require("/app/modules/user.js")["userModule"];
var tokenUtil = require("/app/modules/api-wrapper-util.js")["handlers"];
var tokenUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
/**
* This method reads the token pair from the session and return the access token.
* If the token pair s not set in the session this will send a redirect to the login page.
* If the token pair is not set in the session, this will return null.
*/
privateMethods.getAccessToken = function () {
var tokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]));
var tokenPair = parse(session.get(constants["TOKEN_PAIR"]));
if (tokenPair) {
return tokenPair["accessToken"];
} else {
@ -103,7 +103,7 @@ var invokers = function () {
if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED ||
xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) {
tokenUtil.refreshToken();
tokenUtil.refreshTokenPair();
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count);
} else {
return responseCallback(xmlHttpRequest);
@ -122,7 +122,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateXMLHttpRequest for get calls
* This method invokes return initiateXMLHttpRequest for get calls.
* @param endpoint Backend REST API url.
* @param responseCallback a function to be called with response retrieved.
*/
@ -132,7 +132,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateXMLHttpRequest for post calls
* This method invokes return initiateXMLHttpRequest for post calls.
* @param endpoint Backend REST API url.
* @param requestPayload payload/data if exists which is needed to be send.
* @param responseCallback a function to be called with response retrieved.
@ -142,7 +142,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateXMLHttpRequest for put calls
* This method invokes return initiateXMLHttpRequest for put calls.
* @param endpoint Backend REST API url.
* @param requestPayload payload/data if exists which is needed to be send.
* @param responseCallback a function to be called with response retrieved.
@ -152,7 +152,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateXMLHttpRequest for delete calls
* This method invokes return initiateXMLHttpRequest for delete calls.
* @param endpoint Backend REST API url.
* @param responseCallback a function to be called with response retrieved.
*/
@ -214,7 +214,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateWSRequest for soap calls
* This method invokes return initiateWSRequest for soap calls.
* @param action describes particular soap action.
* @param requestPayload SOAP request payload which is needed to be send.
* @param endpoint service end point to be triggered.
@ -303,7 +303,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateHTTPClientRequest for get calls
* This method invokes return initiateHTTPClientRequest for get calls.
* @param url target url.
* @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved.
@ -315,7 +315,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateHTTPClientRequest for post calls
* This method invokes return initiateHTTPClientRequest for post calls.
* @param url target url.
* @param payload payload/data which need to be send.
* @param successCallback a function to be called if the respond if successful.
@ -327,7 +327,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateHTTPClientRequest for put calls
* This method invokes return initiateHTTPClientRequest for put calls.
* @param url target url.
* @param payload payload/data which need to be send.
* @param successCallback a function to be called if the respond if successful.
@ -339,7 +339,7 @@ var invokers = function () {
};
/**
* This method invokes return initiateHTTPClientRequest for delete calls
* This method invokes return initiateHTTPClientRequest for delete calls.
* @param url target url.
* @param successCallback a function to be called if the respond if successful.
* @param errorCallback a function to be called if en error is reserved.

@ -21,7 +21,7 @@ var operationModule = function () {
var utility = require('/app/modules/utility.js').utility;
var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];;
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var publicMethods = {};
var privateMethods = {};

@ -26,7 +26,7 @@ policyModule = function () {
var constants = require('/app/modules/constants.js');
var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var publicMethods = {};
var privateMethods = {};

@ -1,74 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
@Deprecated - new
*/
//var serverAddress = function () {
// var log = new Log("serverAddress.js");
// var process = require("process"),
// host = process.getProperty('server.host'),
// ip = process.getProperty('carbon.local.ip');
// var publicMethods = {};
// publicMethods.getHTTPSAddress = function () {
// var port = process.getProperty('mgt.transport.https.proxyPort');
// if (!port) {
// port = process.getProperty('mgt.transport.https.port');
// }
// if (host === "localhost") {
// return "https://" + ip + ":" + port;
// } else {
// return "https://" + host + ":" + port;
// }
// };
// publicMethods.getHPPTAddress = function () {
// var port = process.getProperty('mgt.transport.http.proxyPort');
// if (!port) {
// port = process.getProperty('mgt.transport.http.port');
// }
// if (host === "localhost") {
// return "http://" + ip + ":" + port;
// } else {
// return "http://" + host + ":" + port;
// }
// };
// publicMethods.getWSSAddress = function () {
// var port = process.getProperty('mgt.transport.https.proxyPort');
// if (!port) {
// port = process.getProperty('mgt.transport.https.port');
// }
// if (host === "localhost") {
// return "wss://" + ip + ":" + port;
// } else {
// return "wss://" + host + ":" + port;
// }
// };
// publicMethods.getWSAddress = function () {
// var port = process.getProperty('mgt.transport.http.proxyPort');
// if (!port) {
// port = process.getProperty('mgt.transport.http.port');
// }
// if (host === "localhost") {
// return "ws://" + ip + ":" + port;
// } else {
// return "ws://" + host + ":" + port;
// }
// };
// return publicMethods;
//}();

@ -25,7 +25,7 @@ var userModule = function () {
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
/* Initializing user manager */
var carbon = require("carbon");

@ -1,226 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var util = function () {
var log = new Log("/app/modules/util.js");
var module = {};
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
var String = Packages.java.lang.String;
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var carbon = require('carbon');
var constants = require("/app/modules/constants.js");
var adminUser = devicemgtProps["adminUser"];
var clientName = devicemgtProps["clientName"];
module.getDynamicClientCredentials = function () {
var payload = {
"callbackUrl": devicemgtProps.callBackUrl,
"clientName": clientName,
"tokenScope": "admin",
"owner": adminUser,
"applicationType": "webapp",
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer",
"saasApp" :true
};
var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.dynamicClientRegistrationEndPoint;
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(payload);
var clientData = {};
if (xhr.status == 201) {
var data = parse(xhr.responseText);
clientData.clientId = data.client_id;
clientData.clientSecret = data.client_secret;
} else if (xhr.status == 400) {
throw "Invalid client meta data";
} else {
throw "Error in obtaining client id and secret";
}
return clientData;
};
/**
* Encode the payload in Base64
* @param payload
* @returns {Packages.java.lang.String}
*/
module.encode = function (payload) {
return new String(Base64.encodeBase64(new String(payload).getBytes()));
}
module.decode = function (payload) {
return new String(Base64.decodeBase64(new String(payload).getBytes()));
}
/**
* Get an AccessToken pair based on username and password
* @param username
* @param password
* @param clientId
* @param clientSecret
* @param scope
* @returns {{accessToken: "", refreshToken: ""}}
*/
module.getTokenWithPasswordGrantType = function (username, password, encodedClientKeys, scope) {
var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys);
xhr.send("grant_type=password&username=" + username + "&password=" + password + "&scope=" + scope);
delete password, delete clientSecret, delete encodedClientKeys;
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 403) {
log.error("Error in obtaining token with Password grant type");
return null;
} else {
log.error("Error in obtaining token with Password grant type");
return null;
}
return tokenPair;
};
module.getTokenWithSAMLGrantType = function (assertion, clientKeys, scope) {
var assertionXML = module.decode(assertion) ;
var encodedExtractedAssertion;
var extractedAssertion;
//TODO: make assertion extraction with proper parsing. Since Jaggery XML parser seem to add formatting
//which causes signature verification to fail.
var assertionStartMarker = "<saml2:Assertion";
var assertionEndMarker = "<\/saml2:Assertion>";
var assertionStartIndex = assertionXML.indexOf(assertionStartMarker);
var assertionEndIndex = assertionXML.indexOf(assertionEndMarker);
if (assertionStartIndex != -1 && assertionEndIndex != -1) {
extractedAssertion = assertionXML.substring(assertionStartIndex, assertionEndIndex) + assertionEndMarker;
} else {
throw "Invalid SAML response. SAML response has no valid assertion string";
}
encodedExtractedAssertion = this.encode(extractedAssertion);
var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + clientKeys);
xhr.send("grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=" +
encodeURIComponent(encodedExtractedAssertion) + "&scope=" + "PRODUCTION");
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 403) {
throw "Error in obtaining token with SAML extension grant type";
} else {
throw "Error in obtaining token with SAML extension grant type";
}
return tokenPair;
};
module.refreshToken = function (tokenPair, clientData, scope) {
var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + clientData);
var url = "grant_type=refresh_token&refresh_token=" + tokenPair.refreshToken;
if (scope) {
url = url + "&scope=" + scope
}
xhr.send(url);
delete clientData;
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 400) {
tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
} else if (xhr.status == 403) {
throw "Error in obtaining token with Refresh Token Grant Type";
} else {
throw "Error in obtaining token with Refresh Token Type";
}
return tokenPair;
};
module.getTokenWithJWTGrantType = function (clientData) {
var jwtService = carbon.server.osgiService('org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
var jwtClient = jwtService.getJWTClient();
var jwtToken = jwtClient.getAccessToken(clientData.clientId, clientData.clientSecret, adminUser, null);
return jwtToken;
};
module.getTenantBasedAppCredentials = function (uname, token) {
var tenantDomain = carbonModule.server.tenantDomain({
username: uname
});
var clientData = this.getCachedCredentials(tenantDomain);
if (!clientData) {
var applicationName = "webapp_" + tenantDomain;
var xhr = new XMLHttpRequest();
var endpoint = devicemgtProps["adminService"] + "/api-application-registration/register/tenants?tenantDomain=" +
tenantDomain + "&applicationName=" + applicationName;
xhr.open("POST", endpoint, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + token.accessToken);
xhr.send();
if (xhr.status == 201) {
var data = parse(xhr.responseText);
clientData = {};
clientData.clientId = data.client_id;
clientData.clientSecret = data.client_secret;
this.setTenantBasedAppCredentials(tenantDomain, clientData);
} else if (xhr.status == 400) {
throw "Invalid client meta data";
} else {
throw "Error in obtaining client id and secret from APIM";
}
}
return clientData;
};
module.setTenantBasedAppCredentials = function (tenantDomain, clientData) {
var cachedMap = application.get(constants.CACHED_CREDENTIALS);
if (!cachedMap) {
cachedMap = new Object();
cachedMap[tenantDomain] = clientData;
application.put(constants.CACHED_CREDENTIALS, cachedMap);
} else {
cachedMap[tenantDomain] = clientData;
}
};
module.getCachedCredentials = function(tenantDomain) {
var cachedMap = application.get(constants.CACHED_CREDENTIALS);
if (cachedMap) {
return cachedMap[tenantDomain];
}
return null;
};
return module;
}();

@ -116,10 +116,18 @@ public class JWTClientUtil {
throws RegistryException, IOException, JWTClientConfigurationException {
File configFile = new File(SUPERTENANT_JWT_CONFIG_LOCATION);
if (configFile.exists()) {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
jwtClientManagerService.setDefaultJWTClient(properties);
InputStream propertyStream = null;
try {
propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
jwtClientManagerService.setDefaultJWTClient(properties);
} finally {
if (propertyStream != null) {
propertyStream.close();
}
}
}
}

Loading…
Cancel
Save