diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag index e52746e9df..6777383200 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag @@ -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) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 1a163d76e4..74ba1290d4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag index d5f9bb2628..cfce1f0409 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index 6fa133523e..741bf1ed53 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -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); } } %> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag index 46b4595b66..99fa61a9f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -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")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag deleted file mode 100644 index 45210346bb..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag +++ /dev/null @@ -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); -%> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index cab3d3a32f..b8f495aa7c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -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); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json index 8c732e33cd..ad95aa01d6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json @@ -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" + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js deleted file mode 100644 index 02df5fb3a1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js +++ /dev/null @@ -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; -}(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js index 890a7e500e..f1ebedd948 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js @@ -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"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index 464093343d..cb640d4537 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js index 61bfe9f4b7..549d0d8787 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js @@ -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"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js deleted file mode 100644 index d191b1868d..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js +++ /dev/null @@ -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; -// } -// } -// -//}(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 429a6b9c1c..c383e1e817 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js new file mode 100644 index 0000000000..1ed0291e37 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js @@ -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 = "