forked from community/device-mgt-plugins
Merge branch 'master' of https://github.com/wso2/carbon-device-mgt-plugins
commit
578bda6e3b
@ -1,104 +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 log = new Log("api/invoker-api.jag");
|
||||
|
||||
var uri = request.getRequestURI();
|
||||
var uriMatcher = new URIMatcher(String(uri));
|
||||
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
|
||||
|
||||
if (uriMatcher.match("/{context}/api/invoker/execute/")) {
|
||||
var restAPIRequestDetails = request.getContent();
|
||||
|
||||
var requestMethod = restAPIRequestDetails["requestMethod"];
|
||||
var requestURL = restAPIRequestDetails["requestURL"];
|
||||
var requestPayload = restAPIRequestDetails["requestPayload"];
|
||||
|
||||
if (!requestMethod) {
|
||||
requestMethod = parse(restAPIRequestDetails)["requestMethod"];
|
||||
}
|
||||
|
||||
if (!requestURL) {
|
||||
requestURL = parse(restAPIRequestDetails)["requestURL"];
|
||||
}
|
||||
|
||||
if (!requestPayload) {
|
||||
requestPayload = parse(restAPIRequestDetails)["requestPayload"];
|
||||
}
|
||||
|
||||
var restAPIEndpoint = devicemgtProps["httpsURL"] + requestURL;
|
||||
|
||||
try {
|
||||
switch (requestMethod) {
|
||||
case constants["HTTP_GET"]:
|
||||
serviceInvokers.XMLHttp.get(
|
||||
restAPIEndpoint,
|
||||
function (restAPIResponse) {
|
||||
response["status"] = restAPIResponse["status"];
|
||||
if (restAPIResponse["responseText"]) {
|
||||
response["content"] = restAPIResponse["responseText"];
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case constants["HTTP_POST"]:
|
||||
serviceInvokers.XMLHttp.post(
|
||||
restAPIEndpoint,
|
||||
requestPayload,
|
||||
function (restAPIResponse) {
|
||||
response["status"] = restAPIResponse["status"];
|
||||
if (restAPIResponse["responseText"]) {
|
||||
response["content"] = restAPIResponse["responseText"];
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case constants["HTTP_PUT"]:
|
||||
serviceInvokers.XMLHttp.put(
|
||||
restAPIEndpoint,
|
||||
requestPayload,
|
||||
function (restAPIResponse) {
|
||||
response["status"] = restAPIResponse["status"];
|
||||
if (restAPIResponse["responseText"]) {
|
||||
response["content"] = restAPIResponse["responseText"];
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
case constants["HTTP_DELETE"]:
|
||||
serviceInvokers.XMLHttp.delete(
|
||||
restAPIEndpoint,
|
||||
function (restAPIResponse) {
|
||||
response["status"] = restAPIResponse["status"];
|
||||
if (restAPIResponse["responseText"]) {
|
||||
response["content"] = restAPIResponse["responseText"];
|
||||
}
|
||||
}
|
||||
);
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error("Exception occurred while trying to access " +
|
||||
"backend REST API services from Jaggery API invoker layer", e);
|
||||
}
|
||||
}
|
||||
%>
|
@ -1,185 +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 uri = request.getRequestURI();
|
||||
var uriMatcher = new URIMatcher(String(uri));
|
||||
|
||||
var log = new Log("api/user-api.jag");
|
||||
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
|
||||
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
|
||||
var utility = require("/app/modules/utility.js").utility;
|
||||
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;
|
||||
|
||||
var result;
|
||||
|
||||
if (uriMatcher.match("/{context}/api/user/authenticate")) {
|
||||
var username = request.getParameter("username");
|
||||
var password = request.getParameter("password");
|
||||
//Check if a username and password is provided
|
||||
if ((!username) || (!password)) {
|
||||
response = responseProcessor.buildErrorResponse(response, 400, 'Username and Password must be provided');
|
||||
} else {
|
||||
try {
|
||||
userModule.login(username, password, function (user) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User Logged In : " + user);
|
||||
}
|
||||
apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password);
|
||||
}, function () {
|
||||
response = responseProcessor.buildSuccessResponse(response, 200, {'sessionId': session.getId()});
|
||||
});
|
||||
} catch (e) {
|
||||
log.error("Exception occurred while a user tried to login to MDM", e);
|
||||
response = responseProcessor.buildErrorResponse(response, 401, 'username/password is incorrect');
|
||||
}
|
||||
}
|
||||
} else if (uriMatcher.match("/{context}/api/user/login/")) {
|
||||
username = request.getParameter("username");
|
||||
password = request.getParameter("password");
|
||||
username = util.decode(username);
|
||||
password = util.decode(password);
|
||||
try {
|
||||
userModule.login(username, password, function (user) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User Logged In : " + user);
|
||||
}
|
||||
|
||||
apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password);
|
||||
var permissions = userModule.getUIPermissions();
|
||||
if (permissions.VIEW_DASHBOARD) {
|
||||
response.sendRedirect(constants.WEB_APP_CONTEXT);
|
||||
} else {
|
||||
response.sendRedirect(constants.WEB_APP_CONTEXT + "/devices");
|
||||
}
|
||||
}, function () {
|
||||
response.sendRedirect(devicemgtProps.appContext + "login?#auth-failed");
|
||||
});
|
||||
} catch (e) {
|
||||
log.error("Exception occurred while a user tried to login to MDM", e);
|
||||
response.sendRedirect(devicemgtProps.appContext + "login?#error");
|
||||
}
|
||||
} else if (uriMatcher.match("/{context}/api/user/logout/")) {
|
||||
userModule.logout(function () {
|
||||
response.sendRedirect(devicemgtProps.appContext + "login");
|
||||
});
|
||||
} else if (uriMatcher.match("/{context}/api/user/devices/")) {
|
||||
/*
|
||||
@Deprecated
|
||||
*/
|
||||
if (userModule.isAuthorized("/permission/admin/device-mgt/user/devices/list")) {
|
||||
carbonUser = session.get(constants.USER_SESSION_KEY);
|
||||
result = deviceModule.listDevicesForUser(carbonUser.username);
|
||||
} else {
|
||||
response.sendError(403);
|
||||
}
|
||||
} else if (uriMatcher.match("/{context}/api/user/{username}/invite")) {
|
||||
/*
|
||||
@Deprecated
|
||||
*/
|
||||
if (userModule.isAuthorized("/permission/admin/device-mgt/admin/user/invite")) {
|
||||
elements = uriMatcher.elements();
|
||||
username = elements.username;
|
||||
userModule.inviteUser(username);
|
||||
} else {
|
||||
response.sendError(403);
|
||||
}
|
||||
} else if (uriMatcher.match("/{context}/api/user/add")) {
|
||||
/*
|
||||
@Deprecated
|
||||
*/
|
||||
if (userModule.isAuthorized("/permission/admin/device-mgt/admin/user/add")) {
|
||||
addUserFormData = request.getContent();
|
||||
username = addUserFormData.username;
|
||||
firstname = addUserFormData.firstname;
|
||||
lastname = addUserFormData.lastname;
|
||||
emailAddress = addUserFormData.emailAddress;
|
||||
|
||||
if (!addUserFormData.userRoles) {
|
||||
userRoles = null;
|
||||
} else {
|
||||
userRoles = String(addUserFormData.userRoles).split(",");
|
||||
}
|
||||
if (username.length < devicemgtProps.userValidationConfig.usernameLength) {
|
||||
log.error("Username Must be between 1 and " + devicemgtProps.userValidationConfig.usernameLength + " characters long");
|
||||
result = "Username Must be between 1 and " + devicemgtProps.userValidationConfig.usernameLength + " characters long";
|
||||
} else {
|
||||
try {
|
||||
result = userModule.addUser(username, firstname, lastname, emailAddress, userRoles);
|
||||
} catch (e) {
|
||||
log.error("Exception occurred while trying to add a user to MDM User Store", e);
|
||||
// http status code 400 refers to - Bad request.
|
||||
result = 400;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// http status code 403 refers to - forbidden.
|
||||
result = 403;
|
||||
}
|
||||
} else if (uriMatcher.match("/{context}/api/user/register")) {
|
||||
|
||||
addUserFormData = request.getContent();
|
||||
username = addUserFormData.username;
|
||||
firstname = addUserFormData.firstname;
|
||||
lastname = addUserFormData.lastname;
|
||||
emailAddress = addUserFormData.emailAddress;
|
||||
password = addUserFormData.password;
|
||||
userRoles = ["internal/devicemgt-user"];
|
||||
|
||||
try {
|
||||
result = userModule.registerUser(username, firstname, lastname, emailAddress, password,
|
||||
userRoles);
|
||||
} catch (e) {
|
||||
log.error("Exception occurred while trying to registering a new user to DC User Store", e);
|
||||
// http status code 400 refers to - Bad request.
|
||||
result = 400;
|
||||
}
|
||||
|
||||
} else if (uriMatcher.match("/{context}/api/user/{username}/remove")) {
|
||||
/*
|
||||
@Deprecated
|
||||
*/
|
||||
if (userModule.isAuthorized("/permission/admin/device-mgt/admin/user/remove")) {
|
||||
elements = uriMatcher.elements();
|
||||
username = elements.username;
|
||||
try {
|
||||
result = userModule.removeUser(username);
|
||||
} catch (e) {
|
||||
log.error("Exception occurred while trying to remove a user from MDM User Store", e);
|
||||
// http status code 400 refers to - Bad request.
|
||||
result = 400;
|
||||
}
|
||||
} else {
|
||||
// http status code 403 refers to - forbidden.
|
||||
result = 403;
|
||||
}
|
||||
} else if (uriMatcher.match("/{context}/api/user/all")) {
|
||||
result = userModule.getUsers();
|
||||
}
|
||||
|
||||
// returning the result.
|
||||
if (result) {
|
||||
print(result);
|
||||
}
|
||||
%>
|
@ -1,52 +0,0 @@
|
||||
{
|
||||
"appName": "WSO2 IoT Server",
|
||||
"cachingEnabled": true,
|
||||
"debuggingEnabled": false,
|
||||
"permissionRoot": "/",
|
||||
"loginPage": "cdmf.page.sign-in",
|
||||
"adminServicesUrl": "https://${server.ip}:${server.https_port}/admin/services/",
|
||||
"authModule": {
|
||||
"enabled": true,
|
||||
"login": {
|
||||
"onSuccess": {
|
||||
"script": "/app/modules/login.js",
|
||||
"page": "mdm.page.dashboard"
|
||||
},
|
||||
"onFail": {
|
||||
"script": "/app/modules/login.js",
|
||||
"page": "cdmf.page.sign-in"
|
||||
}
|
||||
},
|
||||
"logout": {
|
||||
"onSuccess": {
|
||||
"page": "cdmf.page.sign-in"
|
||||
},
|
||||
"onFail": {
|
||||
"page": "mdm.page.dashboard"
|
||||
}
|
||||
},
|
||||
"sso": {
|
||||
"enabled": false,
|
||||
"issuer" : "devicemgt",
|
||||
"appName" : "devicemgt",
|
||||
"identityProviderUrl" : "https://localhost:9443/samlsso",
|
||||
"acs": "https://localhost:9443/devicemgt/uuf/sso/acs",
|
||||
"identityAlias": "wso2carbon",
|
||||
"responseSigningEnabled" : "true",
|
||||
"useTenantKey": false
|
||||
}
|
||||
},
|
||||
"generalConfig" : {
|
||||
"host" : "https://localhost:9443",
|
||||
"companyName" : "WSO2 IoT Server",
|
||||
"browserTitle" : "WSO2 IoT Server",
|
||||
"copyrightPrefix" : "\u00A9 %date-year%, ",
|
||||
"copyrightOwner" : "WSO2 Inc.",
|
||||
"copyrightOwnersSite" : "http://www.wso2.org",
|
||||
"copyrightSuffix" : ""
|
||||
},
|
||||
"errorPages": {
|
||||
"404": "mdm.page.error",
|
||||
"default": "uuf.page.error"
|
||||
}
|
||||
}
|
@ -1,88 +0,0 @@
|
||||
{
|
||||
"appContext" : "/android-web-agent/",
|
||||
"httpsURL" : "%https.ip%",
|
||||
"httpURL" : "%http.ip%",
|
||||
"managerHTTPSURL": "https://%iot.manager.host%:%iot.manager.https.port%",
|
||||
"enrollmentDir": "/android-web-agent/enrollment",
|
||||
"adminService":"%https.ip%",
|
||||
"callBackUrl":"%https.ip%/mdm-admin",
|
||||
"oauthProvider": {
|
||||
"appRegistration": {
|
||||
"appType": "webapp",
|
||||
"clientName": "android-web-agent",
|
||||
"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",
|
||||
"samlGrantTypeName": "urn:ietf:params:oauth:grant-type:saml2-bearer"
|
||||
},
|
||||
"tokenServiceURL": "%https.ip%/oauth2/token"
|
||||
},
|
||||
"userValidationConfig" : {
|
||||
"usernameLength":30
|
||||
},
|
||||
"androidAgentApp" : "android-agent.apk",
|
||||
"windowsConfigRoot" : "%http.ip%/api/device-mgt/windows/v1.0/services/federated/bst/authentication",
|
||||
"generalConfig" : {
|
||||
"host" : "%http.ip%",
|
||||
"companyName" : "WSO2 IoT Server",
|
||||
"browserTitle" : "WSO2 IoT Server",
|
||||
"copyrightText" : "\u00A9 %date-year%, WSO2 Inc. (http://www.wso2.org) All Rights Reserved."
|
||||
},
|
||||
"isOAuthEnabled" : true,
|
||||
"scopes" : ["activity:view",
|
||||
"application:install",
|
||||
"application:uninstall",
|
||||
"device:view",
|
||||
"user:modify",
|
||||
"configuration:view",
|
||||
"configuration:modify",
|
||||
"device:list",
|
||||
"device:search",
|
||||
"notification:view",
|
||||
"policy:list",
|
||||
"policy:add",
|
||||
"polciy:modify",
|
||||
"policy:view",
|
||||
"role:list",
|
||||
"role:add",
|
||||
"role:view",
|
||||
"role:modify",
|
||||
"user:list",
|
||||
"user:add",
|
||||
"user:view",
|
||||
"certificate:view",
|
||||
"certificate:add",
|
||||
"certificate:modify",
|
||||
"device:android:get-applications",
|
||||
"device:android:blacklist-applications",
|
||||
"device:android:change-lock-code",
|
||||
"device:android:clear-password",
|
||||
"device:android:vpn",
|
||||
"device:android:wifi",
|
||||
"device:android:camera",
|
||||
"device:android:encrypt",
|
||||
"device:android:enterprise-wipe",
|
||||
"device:android:info",
|
||||
"device:android:install-application",
|
||||
"device:android:location",
|
||||
"device:android:lock",
|
||||
"device:android:mute",
|
||||
"device:android:reboot",
|
||||
"device:android:ring",
|
||||
"device:android:send-notification",
|
||||
"device:android:set-password-policy",
|
||||
"device:android:webclip",
|
||||
"device:android:uninstall-application",
|
||||
"device:android:unlock",
|
||||
"device:android:update-application",
|
||||
"device:android:upgrade-firmware",
|
||||
"device:android:wipe",
|
||||
"device:configuration:view",
|
||||
"device:android:configuration:modify",
|
||||
"device:android:enroll",
|
||||
"device:android:event:publish",
|
||||
"device:android:event:view"]
|
||||
}
|
@ -1,76 +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. --}}
|
||||
|
||||
{{!-- 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. --}}
|
||||
{{~defineZone "accessControl"~}}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
{{defineZone "favicon"}}
|
||||
<title>
|
||||
{{defineZone "title"}}
|
||||
</title>
|
||||
{{defineZone "topCss"}}
|
||||
{{defineZone "topJs"}}
|
||||
</head>
|
||||
<body>
|
||||
<header class="header header-default">
|
||||
<div class="container-fluid ">
|
||||
<div class="col-sm-8 app-logo">
|
||||
{{defineZone "brand"}}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="page-content-wrapper">
|
||||
<div class="container-fluid ">
|
||||
<div class="body-wrapper">
|
||||
<div class="wr-head">
|
||||
<h2>{{defineZone "headerTitle" }}</h2>
|
||||
<hr>
|
||||
</div>
|
||||
<!-- start: zone-content-->
|
||||
{{defineZone "content"}}
|
||||
<!-- end: zone-content-->
|
||||
{{!-- {{ defineZone "footer"}} --}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="footer">
|
||||
<div class="container-fluid">
|
||||
{{defineZone "footer"}}
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
{{defineZone "bottomJs" }}
|
||||
</body>
|
||||
</html>
|
@ -1,348 +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 deviceModule;
|
||||
deviceModule = function () {
|
||||
var log = new Log("/app/modules/business-controllers/device.js");
|
||||
|
||||
var utility = require('/app/modules/utility.js').utility;
|
||||
var constants = require('/app/modules/constants.js');
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
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 publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
// var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";
|
||||
|
||||
privateMethods.validateAndReturn = function (value) {
|
||||
return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
|
||||
};
|
||||
|
||||
/*
|
||||
@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();
|
||||
// }
|
||||
// };
|
||||
|
||||
/*
|
||||
@Deprecated
|
||||
*/
|
||||
/*
|
||||
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();
|
||||
// }
|
||||
// };
|
||||
|
||||
/*
|
||||
@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();
|
||||
// }
|
||||
// };
|
||||
|
||||
/*
|
||||
@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();
|
||||
// }
|
||||
// };
|
||||
|
||||
/*
|
||||
@Updated
|
||||
*/
|
||||
publicMethods.viewDevice = function (deviceType, deviceId) {
|
||||
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
|
||||
if (!carbonUser) {
|
||||
log.error("User object was not found in the session");
|
||||
throw constants["ERRORS"]["USER_NOT_FOUND"];
|
||||
}
|
||||
var utility = require('/app/modules/utility.js')["utility"];
|
||||
try {
|
||||
utility.startTenantFlow(carbonUser);
|
||||
|
||||
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"];
|
||||
}
|
||||
deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
|
||||
return deviceObject;
|
||||
}
|
||||
},
|
||||
function (responsePayload) {
|
||||
var response = {};
|
||||
response["status"] = "error";
|
||||
return response;
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
// Refactored methods
|
||||
publicMethods.getDevicesCount = function () {
|
||||
var carbonUser = session.get(constants.USER_SESSION_KEY);
|
||||
if (carbonUser) {
|
||||
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
|
||||
var uiPermissions = userModule.getUIPermissions();
|
||||
var url;
|
||||
if (uiPermissions.LIST_DEVICES) {
|
||||
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";
|
||||
} 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;
|
||||
}
|
||||
);
|
||||
} else {
|
||||
log.error("User object was not found in the session");
|
||||
throw constants["ERRORS"]["USER_NOT_FOUND"];
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
//Old methods
|
||||
//TODO: make sure these methods are updated
|
||||
/*
|
||||
@Updated
|
||||
*/
|
||||
publicMethods.getLicense = function (deviceType) {
|
||||
var url;
|
||||
var license;
|
||||
if (deviceType == "windows") {
|
||||
url = devicemgtProps["httpURL"] + "/mdm-windows-agent/services/device/license";
|
||||
} else if (deviceType == "ios") {
|
||||
url = devicemgtProps["httpsURL"] + "/ios-enrollment/license/";
|
||||
}
|
||||
if (url != null && url != undefined) {
|
||||
return serviceInvokers.XMLHttp.get(
|
||||
url, function (responsePayload) {
|
||||
return "" + parse(responsePayload.responseText).text;
|
||||
},
|
||||
function (responsePayload) {
|
||||
return null;
|
||||
}
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
);
|
||||
};
|
||||
return publicMethods;
|
||||
}();
|
@ -1,82 +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 groupModule = {};
|
||||
(function (groupModule) {
|
||||
var log = new Log("/app/modules/business-controllers/group.js");
|
||||
|
||||
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
|
||||
var constants = require('/app/modules/constants.js');
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var utility = require("/app/modules/utility.js").utility;
|
||||
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
|
||||
|
||||
var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups";
|
||||
|
||||
var user = session.get(constants.USER_SESSION_KEY);
|
||||
|
||||
var endPoint;
|
||||
|
||||
groupModule.getGroupCount = function () {
|
||||
var permissions = userModule.getUIPermissions();
|
||||
if (permissions.LIST_ALL_GROUPS) {
|
||||
endPoint = groupServiceEndpoint + "/count";
|
||||
} else if (permissions.LIST_GROUPS) {
|
||||
endPoint = groupServiceEndpoint + "/user/" + user.username + "/count";
|
||||
} else {
|
||||
log.error("Access denied for user: " + carbonUser.username);
|
||||
return -1;
|
||||
}
|
||||
return serviceInvokers.XMLHttp.get(
|
||||
endPoint, function (responsePayload) {
|
||||
return responsePayload;
|
||||
},
|
||||
function (responsePayload) {
|
||||
log.error(responsePayload);
|
||||
return -1;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
groupModule.getGroupDeviceCount = function (groupName, owner) {
|
||||
endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count";
|
||||
return serviceInvokers.XMLHttp.get(
|
||||
endPoint, function (responsePayload) {
|
||||
return responsePayload;
|
||||
},
|
||||
function (responsePayload) {
|
||||
log.error(responsePayload);
|
||||
return -1;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
groupModule.getGroupDevices = function (groupName, owner) {
|
||||
endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices";
|
||||
return serviceInvokers.XMLHttp.get(
|
||||
endPoint, function (responsePayload) {
|
||||
return responsePayload;
|
||||
},
|
||||
function (responsePayload) {
|
||||
log.error(responsePayload);
|
||||
return responsePayload;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
}(groupModule));
|
@ -1,134 +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 operationModule = function () {
|
||||
var log = new Log("/app/modules/business-controllers/operation.js");
|
||||
var utility = require('/app/modules/utility.js').utility;
|
||||
var constants = require('/app/modules/constants.js');
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
|
||||
|
||||
var publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
/**
|
||||
* This method reads the token from the Token client and return the access token.
|
||||
* If the token pair s not set in the session this will send a redirect to the login page.
|
||||
*/
|
||||
function getAccessToken(deviceType, owner, deviceId) {
|
||||
var TokenClient = Packages.org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
|
||||
var accessTokenClient = new TokenClient(deviceType);
|
||||
var accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
|
||||
return accessTokenInfo.getAccess_token();
|
||||
}
|
||||
|
||||
privateMethods.getOperationsFromFeatures = function (deviceType, operationType) {
|
||||
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType;
|
||||
var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
|
||||
var features = responsePayload;
|
||||
var featureList = [];
|
||||
var feature;
|
||||
for (var i = 0; i < features.length; i++) {
|
||||
feature = {};
|
||||
var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"];
|
||||
if (analyticStreams) {
|
||||
for (var stream in analyticStreams) {
|
||||
if (analyticStreams[stream].name == features[i].name) {
|
||||
feature.ui_unit = analyticStreams[stream].ui_unit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
feature["operation"] = features[i].code;
|
||||
feature["name"] = features[i].name;
|
||||
feature["description"] = features[i].description;
|
||||
feature["deviceType"] = deviceType;
|
||||
feature["params"] = [];
|
||||
var metaData = features[i].metadataEntries;
|
||||
if (metaData) {
|
||||
for (var j = 0; j < metaData.length; j++) {
|
||||
feature["params"].push(metaData[j].value);
|
||||
}
|
||||
featureList.push(feature);
|
||||
}
|
||||
}
|
||||
return featureList;
|
||||
}, function (responsePayload) {
|
||||
var response = {};
|
||||
response["status"] = "error";
|
||||
return response;
|
||||
}
|
||||
);
|
||||
return featuresList;
|
||||
};
|
||||
|
||||
publicMethods.getControlOperations = function (deviceType) {
|
||||
var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation");
|
||||
for (var op in operations) {
|
||||
var iconPath = utility.getOperationIcon(deviceType, operations[op].operation);
|
||||
if (iconPath) {
|
||||
operations[op]["icon"] = iconPath;
|
||||
}
|
||||
}
|
||||
return operations;
|
||||
};
|
||||
|
||||
publicMethods.getMonitorOperations = function (deviceType) {
|
||||
return privateMethods.getOperationsFromFeatures(deviceType, "monitor");
|
||||
};
|
||||
|
||||
publicMethods.handlePOSTOperation = function (deviceType, operation, deviceId, params) {
|
||||
var user = session.get(constants.USER_SESSION_KEY);
|
||||
var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation;
|
||||
var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId +
|
||||
'","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' +
|
||||
constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX +
|
||||
getAccessToken(deviceType, user.username, deviceId) + '"}';
|
||||
return post(endPoint, params, JSON.parse(header), "json");
|
||||
};
|
||||
|
||||
publicMethods.handleGETOperation = function (deviceType, operation, operationName, deviceId) {
|
||||
var user = session.get(constants.USER_SESSION_KEY);
|
||||
var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation;
|
||||
var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId +
|
||||
'","protocol":"mqtt", "' + constants.AUTHORIZATION_HEADER + '":"' +
|
||||
constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) +
|
||||
'"}';
|
||||
var result = get(endPoint, {}, JSON.parse(header), "json");
|
||||
if (result.data) {
|
||||
var values = result.data.sensorValue.split(',');
|
||||
if (operationName == 'gps') {
|
||||
result.data.map = {
|
||||
lat: parseFloat(values[0]),
|
||||
lng: parseFloat(values[1])
|
||||
}
|
||||
} else {
|
||||
var sqSum = 0;
|
||||
for (var v in values) {
|
||||
sqSum += Math.pow(values[v], 2);
|
||||
}
|
||||
result.data[operationName] = Math.sqrt(sqSum);
|
||||
}
|
||||
delete result.data['sensorValue'];
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,152 +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 policyModule;
|
||||
policyModule = function () {
|
||||
var log = new Log("/app/modules/business-controllers/policy.js");
|
||||
|
||||
var constants = require('/app/modules/constants.js');
|
||||
var utility = require("/app/modules/utility.js")["utility"];
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
|
||||
|
||||
var publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
privateMethods.handleGetAllPoliciesResponse = function (backendResponse) {
|
||||
var response = {};
|
||||
if (backendResponse.status == 200 && backendResponse.responseText) {
|
||||
var isUpdated = false;
|
||||
var policyListFromRestEndpoint = parse(backendResponse.responseText)["policies"];
|
||||
|
||||
var policyListToView = [];
|
||||
var i, policyObjectFromRestEndpoint, policyObjectToView;
|
||||
for (i = 0; i < policyListFromRestEndpoint.length; i++) {
|
||||
// get list object
|
||||
policyObjectFromRestEndpoint = policyListFromRestEndpoint[i];
|
||||
// populate list object values to view-object
|
||||
policyObjectToView = {};
|
||||
policyObjectToView["id"] = policyObjectFromRestEndpoint["id"];
|
||||
policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"];
|
||||
policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"];
|
||||
policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"];
|
||||
policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]);
|
||||
policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"];
|
||||
|
||||
var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length;
|
||||
var assignedUserCount = policyObjectFromRestEndpoint["users"].length;
|
||||
|
||||
if (assignedRoleCount == 0) {
|
||||
policyObjectToView["roles"] = "None";
|
||||
} else if (assignedRoleCount == 1) {
|
||||
policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0];
|
||||
} else if (assignedRoleCount > 1) {
|
||||
policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0] + ", ...";
|
||||
}
|
||||
|
||||
if (assignedUserCount == 0) {
|
||||
policyObjectToView["users"] = "None";
|
||||
} else if (assignedUserCount == 1) {
|
||||
policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0];
|
||||
} else if (assignedUserCount > 1) {
|
||||
policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0] + ", ...";
|
||||
}
|
||||
|
||||
policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"];
|
||||
|
||||
if (policyObjectFromRestEndpoint["active"] == true &&
|
||||
policyObjectFromRestEndpoint["updated"] == true) {
|
||||
policyObjectToView["status"] = "Active/Updated";
|
||||
isUpdated = true;
|
||||
} else if (policyObjectFromRestEndpoint["active"] == true &&
|
||||
policyObjectFromRestEndpoint["updated"] == false) {
|
||||
policyObjectToView["status"] = "Active";
|
||||
} else if (policyObjectFromRestEndpoint["active"] == false &&
|
||||
policyObjectFromRestEndpoint["updated"] == true) {
|
||||
policyObjectToView["status"] = "Inactive/Updated";
|
||||
isUpdated = true;
|
||||
} else if (policyObjectFromRestEndpoint["active"] == false &&
|
||||
policyObjectFromRestEndpoint["updated"] == false) {
|
||||
policyObjectToView["status"] = "Inactive";
|
||||
}
|
||||
// push view-objects to list
|
||||
policyListToView.push(policyObjectToView);
|
||||
}
|
||||
// generate response
|
||||
response.updated = isUpdated;
|
||||
response.status = "success";
|
||||
response.content = policyListToView;
|
||||
|
||||
return response;
|
||||
} else {
|
||||
response.status = "error";
|
||||
/* backendResponse.responseText == "Scope validation failed"
|
||||
Here the response.context("Scope validation failed") is used other then response.status(401).
|
||||
Reason for this is IDP return 401 as the status in 4 different situations such as,
|
||||
1. UnAuthorized.
|
||||
2. Scope Validation Failed.
|
||||
3. Permission Denied.
|
||||
4. Access Token Expired.
|
||||
5. Access Token Invalid.
|
||||
In these cases in order to identify the correct situation we have to compare the unique value from status and
|
||||
context which is context.
|
||||
*/
|
||||
if (backendResponse.responseText == "Scope validation failed") {
|
||||
response.content = "Permission Denied";
|
||||
} else {
|
||||
response.content = backendResponse.responseText;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
@Updated
|
||||
*/
|
||||
publicMethods.getAllPolicies = function () {
|
||||
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
|
||||
if (!carbonUser) {
|
||||
log.error("User object was not found in the session");
|
||||
throw constants["ERRORS"]["USER_NOT_FOUND"];
|
||||
}
|
||||
try {
|
||||
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
|
||||
"/policies?offset=0&limit=100";
|
||||
return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
@Updated - used by getAllPolicies
|
||||
*/
|
||||
privateMethods.getElementsInAString = function (elementList) {
|
||||
var i, elementsInAString = "";
|
||||
for (i = 0; i < elementList.length; i++) {
|
||||
if (i == elementList.length - 1) {
|
||||
elementsInAString += elementList[i];
|
||||
} else {
|
||||
elementsInAString += elementList[i] + ", ";
|
||||
}
|
||||
}
|
||||
return elementsInAString;
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,540 +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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This module contains user and roles related functionality.
|
||||
*/
|
||||
var userModule = function () {
|
||||
var log = new Log("/app/modules/business-controllers/user.js");
|
||||
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var utility = require("/app/modules/utility.js")["utility"];
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
|
||||
|
||||
/* Initializing user manager */
|
||||
var carbon = require("carbon");
|
||||
var url = carbon.server.address("https") + "/admin/services";
|
||||
var server = new carbon.server.Server(url);
|
||||
|
||||
var publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
/**
|
||||
* Get the carbon user object from the session. If not found - it will throw a user not found error.
|
||||
* @returns {object} carbon user object
|
||||
*/
|
||||
privateMethods.getCarbonUser = function () {
|
||||
var carbon = require("carbon");
|
||||
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
|
||||
var utility = require("/modules/utility.js")["utility"];
|
||||
if (!carbonUser) {
|
||||
log.error("User object was not found in the session");
|
||||
throw constants["ERRORS"]["USER_NOT_FOUND"];
|
||||
}
|
||||
return carbonUser;
|
||||
};
|
||||
|
||||
/**
|
||||
* Only GET method is implemented for now since there are no other type of methods used this method.
|
||||
* @param url - URL to call the backend without the host
|
||||
* @param method - HTTP Method (GET, POST)
|
||||
* @returns An object with 'status': 'success'|'error', 'content': {}
|
||||
*/
|
||||
privateMethods.callBackend = function (url, method) {
|
||||
if (constants["HTTP_GET"] == method) {
|
||||
return serviceInvokers.XMLHttp.get(url,
|
||||
function (backendResponse) {
|
||||
var response = {};
|
||||
response.content = backendResponse.responseText;
|
||||
if (backendResponse.status == 200) {
|
||||
response.status = "success";
|
||||
} else if (backendResponse.status == 400 || backendResponse.status == 401 ||
|
||||
backendResponse.status == 404 || backendResponse.status == 500) {
|
||||
response.status = "error";
|
||||
}
|
||||
return response;
|
||||
}
|
||||
);
|
||||
} else {
|
||||
log.error("Runtime error : This method only support HTTP GET requests.");
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Register user to dc-user-store.
|
||||
*
|
||||
* @param username Username of the user
|
||||
* @param firstname First name of the user
|
||||
* @param lastname Last name of the user
|
||||
* @param emailAddress Email address of the user
|
||||
* @param password Password of the user
|
||||
* @param userRoles Roles assigned to the user
|
||||
*
|
||||
* @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
|
||||
*/
|
||||
publicMethods.registerUser = function (username, firstname, lastname, emailAddress, password, userRoles) {
|
||||
var carbon = require('carbon');
|
||||
var tenantId = carbon.server.tenantId();
|
||||
var url = carbon.server.address('https') + "/admin/services";
|
||||
var server = new carbon.server.Server(url);
|
||||
var userManager = new carbon.user.UserManager(server, tenantId);
|
||||
|
||||
try {
|
||||
if (userManager.userExists(username)) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("A user with name '" + username + "' already exists.");
|
||||
}
|
||||
// http status code 409 refers to - conflict.
|
||||
return constants.HTTP_CONFLICT;
|
||||
} else {
|
||||
var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);
|
||||
userManager.addUser(username, password, userRoles, defaultUserClaims, "default");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("A new user with name '" + username + "' was created.");
|
||||
}
|
||||
// http status code 201 refers to - created.
|
||||
return constants.HTTP_CREATED;
|
||||
}
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
@Updated
|
||||
*/
|
||||
publicMethods.getUsers = 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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users?offset=0&limit=100";
|
||||
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
if (response.status == "success") {
|
||||
response.content = parse(response.content).users;
|
||||
}
|
||||
return response;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a User object from the backend by calling the JAX-RS
|
||||
* @param username
|
||||
* @returns {object} a response object with status and content on success.
|
||||
*/
|
||||
publicMethods.getUser = function (username) {
|
||||
var carbonUser = privateMethods.getCarbonUser();
|
||||
try {
|
||||
utility.startTenantFlow(carbonUser);
|
||||
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
|
||||
encodeURIComponent(username);
|
||||
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
response["content"] = parse(response.content);
|
||||
response["userDomain"] = carbonUser.domain;
|
||||
return response;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a set of roles assigned to a particular user
|
||||
* @param username
|
||||
* @returns {object} a response object with status and content on success.
|
||||
*/
|
||||
publicMethods.getRolesByUsername = function (username) {
|
||||
var carbonUser = privateMethods.getCarbonUser();
|
||||
try {
|
||||
utility.startTenantFlow(carbonUser);
|
||||
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
|
||||
encodeURIComponent(username) + "/roles";
|
||||
return privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
@NewlyAdded
|
||||
*/
|
||||
publicMethods.getUsersByUsername = 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 url = devicemgtProps["httpsURL"] + "/mdm-admin/users/users-by-username";
|
||||
return privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
@Updated
|
||||
*/
|
||||
/**
|
||||
* Get User Roles from user store (Internal roles not included).
|
||||
*/
|
||||
publicMethods.getRoles = 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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
|
||||
"/roles?offset=0&limit=100";
|
||||
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
if (response.status == "success") {
|
||||
response.content = parse(response.content).roles;
|
||||
}
|
||||
return response;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
@Updated
|
||||
*/
|
||||
/**
|
||||
* Get User Roles from user store (Internal roles not included).
|
||||
* @returns {object} a response object with status and content on success.
|
||||
*/
|
||||
publicMethods.getRolesByUserStore = function () {
|
||||
var ROLE_LIMIT = devicemgtProps["pageSize"];
|
||||
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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles?limit=" + ROLE_LIMIT;
|
||||
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
if (response.status == "success") {
|
||||
response.content = parse(response.content).roles;
|
||||
}
|
||||
return response;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get Platforms.
|
||||
*/
|
||||
//TODO Move this piece of logic out of user.js to somewhere else appropriate.
|
||||
publicMethods.getPlatforms = 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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/admin/device-types";
|
||||
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
if (response.status == "success") {
|
||||
response.content = parse(response.content);
|
||||
}
|
||||
return response;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get role
|
||||
*/
|
||||
publicMethods.getRole = function (roleName) {
|
||||
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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
|
||||
"/roles/" + encodeURIComponent(roleName);
|
||||
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
|
||||
response.content = parse(response.content);
|
||||
return response;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Authenticate a user when he or she attempts to login to MDM.
|
||||
*
|
||||
* @param username Username of the user
|
||||
* @param password Password of the user
|
||||
* @param successCallback Function to be called at the event of successful authentication
|
||||
* @param failureCallback Function to be called at the event of failed authentication
|
||||
*/
|
||||
publicMethods.login = function (username, password, successCallback, failureCallback) {
|
||||
var carbonModule = require("carbon");
|
||||
var carbonServer = application.get("carbonServer");
|
||||
try {
|
||||
// check if the user is an authenticated user.
|
||||
var isAuthenticated = carbonServer.authenticate(username, password);
|
||||
if (!isAuthenticated) {
|
||||
failureCallback("authentication");
|
||||
return;
|
||||
}
|
||||
var tenantUser = carbonModule.server.tenantUser(username);
|
||||
var isAuthorizedToLogin = privateMethods.isAuthorizedToLogin(tenantUser);
|
||||
if (!isAuthorizedToLogin) {
|
||||
failureCallback("authorization");
|
||||
return;
|
||||
}
|
||||
session.put(constants.USER_SESSION_KEY, tenantUser);
|
||||
successCallback(tenantUser);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.logout = function (successCallback) {
|
||||
session.invalidate();
|
||||
successCallback();
|
||||
};
|
||||
|
||||
publicMethods.isAuthorized = function (permission) {
|
||||
var carbon = require("carbon");
|
||||
var carbonServer = application.get("carbonServer");
|
||||
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");
|
||||
response.sendError(401, constants.ERRORS.USER_NOT_FOUND);
|
||||
exit();
|
||||
}
|
||||
|
||||
try {
|
||||
utility.startTenantFlow(carbonUser);
|
||||
var tenantId = carbon.server.tenantId();
|
||||
var userManager = new carbon.user.UserManager(server, tenantId);
|
||||
var user = new carbon.user.User(userManager, carbonUser.username);
|
||||
return user.isAuthorized(permission, "ui.execute");
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
privateMethods.isAuthorizedToLogin = function(carbonUser) {
|
||||
var utility = require('/app/modules/utility.js').utility;
|
||||
try {
|
||||
utility.startTenantFlow(carbonUser);
|
||||
var tenantId = carbon.server.tenantId();
|
||||
var userManager = new carbon.user.UserManager(server, tenantId);
|
||||
var user = new carbon.user.User(userManager, carbonUser.username);
|
||||
return user.isAuthorized("/permission/admin/login", "ui.execute");
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getUIPermissions = function () {
|
||||
var permissions = {};
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) {
|
||||
permissions["LIST_DEVICES"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) {
|
||||
permissions["LIST_OWN_DEVICES"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/list")) {
|
||||
permissions["LIST_ALL_GROUPS"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/groups/list")) {
|
||||
permissions["LIST_GROUPS"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/list")) {
|
||||
permissions["LIST_USERS"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/list")) {
|
||||
permissions["LIST_ROLES"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/list")) {
|
||||
permissions["LIST_ALL_POLICIES"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/list")) {
|
||||
permissions["LIST_POLICIES"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/add")) {
|
||||
permissions["ADD_DEVICE"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/groups/add")) {
|
||||
permissions["ADD_GROUP"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/add")) {
|
||||
permissions["ADD_USER"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/remove")) {
|
||||
permissions["REMOVE_USER"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/add")) {
|
||||
permissions["ADD_ROLE"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/add")) {
|
||||
permissions["ADD_ADMIN_POLICY"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/add")) {
|
||||
permissions["ADD_POLICY"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/priority")) {
|
||||
permissions["CHANGE_POLICY_PRIORITY"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/dashboard/view")) {
|
||||
permissions["VIEW_DASHBOARD"] = true;
|
||||
}
|
||||
if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) {
|
||||
permissions["TENANT_CONFIGURATION"] = true;
|
||||
}
|
||||
|
||||
return permissions;
|
||||
};
|
||||
|
||||
publicMethods.addPermissions = function (permissionList, path, init) {
|
||||
var registry, carbon = require("carbon");
|
||||
var carbonServer = application.get("carbonServer");
|
||||
var utility = require('/app/modules/utility.js').utility;
|
||||
var options = {system: true};
|
||||
if (init == "login") {
|
||||
try {
|
||||
var carbonUser = session.get(constants.USER_SESSION_KEY);
|
||||
if (!carbonUser) {
|
||||
log.error("User object was not found in the session");
|
||||
throw constants.ERRORS.USER_NOT_FOUND;
|
||||
}
|
||||
utility.startTenantFlow(carbonUser);
|
||||
var tenantId = carbon.server.tenantId();
|
||||
if (carbonUser) {
|
||||
options.tenantId = tenantId;
|
||||
}
|
||||
registry = new carbon.registry.Registry(carbonServer, options);
|
||||
var i, permission, resource;
|
||||
for (i = 0; i < permissionList.length; i++) {
|
||||
permission = permissionList[i];
|
||||
resource = {
|
||||
collection: true,
|
||||
name: permission.name,
|
||||
properties: {
|
||||
name: permission.name
|
||||
}
|
||||
};
|
||||
if (path != "") {
|
||||
registry.put("/_system/governance/permission/admin/" + path + "/" + permission.key, resource);
|
||||
} else {
|
||||
registry.put("/_system/governance/permission/admin/" + permission.key, resource);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
utility.endTenantFlow();
|
||||
}
|
||||
} else {
|
||||
registry = new carbon.registry.Registry(carbonServer, options);
|
||||
var i, permission, resource;
|
||||
for (i = 0; i < permissionList.length; i++) {
|
||||
permission = permissionList[i];
|
||||
resource = {
|
||||
collection: true,
|
||||
name: permission.name,
|
||||
properties: {
|
||||
name: permission.name
|
||||
}
|
||||
};
|
||||
if (path != "") {
|
||||
registry.put("/_system/governance/permission/admin/" + path + "/" + permission.key, resource);
|
||||
} else {
|
||||
registry.put("/_system/governance/permission/admin/" + permission.key, resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Private method to be used by addUser() to
|
||||
* retrieve secondary user stores.
|
||||
* This needs Authentication since the method access admin services.
|
||||
*
|
||||
* @returns Array of secondary user stores.
|
||||
*/
|
||||
publicMethods.getSecondaryUserStores = function () {
|
||||
var returnVal = [];
|
||||
var endpoint = devicemgtProps["adminService"] + constants["USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT"];
|
||||
var wsPayload = "<xsd:getSecondaryRealmConfigurations xmlns:xsd='http://org.apache.axis2/xsd'/>";
|
||||
serviceInvokers.WS.soapRequest(
|
||||
"urn:getSecondaryRealmConfigurations",
|
||||
wsPayload,
|
||||
endpoint,
|
||||
function (wsResponse) {
|
||||
var domainIDs = stringify(wsResponse.*::['return']. *::domainId.text());
|
||||
if (domainIDs != "\"\"") {
|
||||
var regExpForSearch = new RegExp(constants["USER_STORES_NOISY_CHAR"], "g");
|
||||
domainIDs = domainIDs.replace(regExpForSearch, "");
|
||||
returnVal = domainIDs.split(constants["USER_STORES_SPLITTING_CHAR"]);
|
||||
}
|
||||
}, function (e) {
|
||||
log.error("Error retrieving secondary user stores", e);
|
||||
},
|
||||
constants["SOAP_VERSION"]);
|
||||
return returnVal;
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,59 +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 conf = function () {
|
||||
var conf = application.get("CONF");
|
||||
if (!conf) {
|
||||
conf = require("/app/conf/config.json");
|
||||
var pinch = require("/app/modules/conf-reader/pinch.min.js")["pinch"];
|
||||
var server = require("carbon")["server"];
|
||||
var process = require("process");
|
||||
pinch(conf, /^/,
|
||||
function (path, key, value) {
|
||||
if ((typeof value === "string") && value.indexOf("%https.ip%") > -1) {
|
||||
//noinspection JSUnresolvedFunction
|
||||
return value.replace("%https.ip%", server.address("https"));
|
||||
} else if ((typeof value === "string") && value.indexOf("%http.ip%") > -1) {
|
||||
//noinspection JSUnresolvedFunction
|
||||
return value.replace("%http.ip%", server.address("http"));
|
||||
} else if ((typeof value === "string") && value.indexOf("%date-year%") > -1) {
|
||||
var year = new Date().getFullYear();
|
||||
return value.replace("%date-year%", year);
|
||||
} else {
|
||||
var paramPattern = new RegExp("%(.*?)%", "g");
|
||||
var out = value;
|
||||
while ((matches = paramPattern.exec(value)) !== null) {
|
||||
// This is necessary to avoid infinite loops with zero-width matches
|
||||
if (matches.index === paramPattern.lastIndex) {
|
||||
paramPattern.lastIndex++;
|
||||
}
|
||||
if (matches.length == 2) {
|
||||
var property = process.getProperty(matches[1]);
|
||||
if (property) {
|
||||
out = out.replace(new RegExp("%" + matches[1] + "%", "g"), property);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
);
|
||||
application.put("CONF", conf);
|
||||
}
|
||||
return conf;
|
||||
}();
|
@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2011 František Hába <hello@frantisekhaba.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the 'Software'), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
|
||||
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* Reference:- https://github.com/Baggz/Pinch
|
||||
* */
|
||||
(function(){var k=function(a,c){return a.length!==c.length?!1:a.every(function(a,b){return c[b]===a})},j=function(a,c,d){var b,e;if("[object Array]"===Object.prototype.toString.call(a)){b=0;for(e=a.length;b<e;b++)c.apply(d,[b,a[b],a])}else for(b in a)a.hasOwnProperty(b)&&c.apply(d,[b,a[b],a])},h=function(a){for(var c=[],d=!1,b=0,e=a.length,f="",g=function(){f&&(c.push(f),f="")};b<e;b++)a[b].match(/\[|\]/)?(g(),d="]"===a[b]?!1:!0):'"'!==a[b]&&"'"!==a[b]&&("."===a[b]&&!d?g():f+=a[b]),b===e-1&&g();return c},
|
||||
g=function(a,c,d){var b=-1!==["string","object"].indexOf(typeof a),e="string"===typeof c||c&&c.test&&c.exec,f=-1!==["string","object","function"].indexOf(typeof d);b&&e&&f&&("string"===typeof a?(this.instance=JSON.parse(a),this.json=!0):this.instance=a,this.pattern="string"===typeof c?c.replace(/'/g,'"'):c,this.replacement=d,this.createIndex(this.instance))};g.prototype.createIndex=function(a,c){var d=this;this.index=this.index||[];c=c||"";j(a,function(a,e){var f,a=a+"";f=a.match(/^[a-zA-Z]+$/)?c?
|
||||
c+"."+a:a:a.match(/\d+/)?c+"["+a+"]":c+'["'+a+'"]';d.index.push(f);"object"===typeof e&&d.createIndex(e,f)})};g.prototype.replace=function(){var a=this;j(this.index,function(c,d){if(a.pattern&&a.pattern.test&&a.pattern.exec&&d.match(a.pattern))return a.replaceValue(d);if("string"===typeof a.pattern){var b=h(d),e=h(a.pattern);if(k(b,e))return a.replaceValue(d)}});return this.json?JSON.stringify(this.instance):this.instance};g.prototype.replaceValue=function(a){var c=this,d=h(a);d.reduce(function(b,
|
||||
e,f){if(f===d.length-1)f="function"===typeof c.replacement?c.replacement(a,e,b[e]):c.replacement,b[e]=f;else return b[e]},this.instance)};var i=function(a,c,d,b){a=(new g(a,c,d)).replace();return"function"===typeof b?b(null,a):a};"undefined"!==typeof module&&module.exports?module.exports=i:"undefined"!==typeof define?define(function(){return i}):this.pinch=i})();
|
@ -1,81 +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 WEB_APP_TITLE = "WSO2 CDM";
|
||||
var WEB_APP_CONTEXT = "/devicemgt";
|
||||
var ADMIN_SERVICE_CONTEXT = "/devicemgt_admin";
|
||||
var USER_SESSION_KEY = "_UUF_USER";
|
||||
var UNSPECIFIED = "Unspecified";
|
||||
var httpURL = "httpURL";
|
||||
var httpsURL = "httpsURL";
|
||||
|
||||
var DEVICE_IDENTIFIER = "deviceIdentifier";
|
||||
var DEVICE_NAME = "name";
|
||||
var DEVICE_OWNERSHIP = "ownership";
|
||||
var DEVICE_OWNER = "owner";
|
||||
var DEVICE_TYPE = "type";
|
||||
var DEVICE_VENDOR = "vendor";
|
||||
var DEVICE_MODEL = "model";
|
||||
var DEVICE_PRODUCT = "PRODUCT";
|
||||
var DEVICE_OS_VERSION = "osVersion";
|
||||
var DEVICE_OS_BUILD_DATE = "osBuildDate";
|
||||
var DEVICE_PROPERTIES = "properties";
|
||||
var DEVICE_ENROLLMENT_INFO = "enrolmentInfo";
|
||||
var DEVICE_STATUS = "status";
|
||||
|
||||
var FEATURE_NAME = "featureName";
|
||||
var FEATURE_DESCRIPTION = "featureDescription";
|
||||
|
||||
var PLATFORM_ANDROID = "android";
|
||||
var PLATFORM_WINDOWS = "windows";
|
||||
var PLATFORM_IOS = "ios";
|
||||
|
||||
var LANGUAGE_US = "en_US";
|
||||
|
||||
var VENDOR_APPLE = "Apple";
|
||||
var ERRORS = {
|
||||
"USER_NOT_FOUND": "USER_NOT_FOUND"
|
||||
};
|
||||
|
||||
var USER_STORES_NOISY_CHAR = "\"";
|
||||
var USER_STORES_SPLITTING_CHAR = "\\n";
|
||||
var USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT =
|
||||
"/services/UserStoreConfigAdminService.UserStoreConfigAdminServiceHttpsSoap12Endpoint/";
|
||||
|
||||
var SOAP_VERSION = 1.2;
|
||||
var WEB_SERVICE_ADDRESSING_VERSION = 1.0;
|
||||
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";
|
||||
var APPLICATION_ZIP = "application/zip";
|
||||
var ACCEPT_IDENTIFIER = "Accept";
|
||||
var AUTHORIZATION_HEADER= "Authorization";
|
||||
var BEARER_PREFIX = "Bearer ";
|
||||
var HTTP_GET = "GET";
|
||||
var HTTP_POST = "POST";
|
||||
var HTTP_PUT = "PUT";
|
||||
var HTTP_DELETE = "DELETE";
|
||||
var REFERER = "referer";
|
||||
|
||||
var HTTP_CONFLICT = 409;
|
||||
var HTTP_CREATED = 201;
|
||||
|
||||
var CACHED_CREDENTIALS = "tenantBasedCredentials";
|
||||
var ALLOWED_SCOPES = "scopes";
|
@ -1,40 +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 methods;
|
||||
methods = function () {
|
||||
var log = new Log("modules/enrollments/util/utils.js");
|
||||
|
||||
var publicMethods = {};
|
||||
|
||||
publicMethods.getResource = function (resourcePath) {
|
||||
var file = new File(resourcePath);
|
||||
var resource = null;
|
||||
try {
|
||||
file.open("r");
|
||||
resource = file.readAll();
|
||||
} catch (e) {
|
||||
log.error("Error in reading resource");
|
||||
} finally {
|
||||
file.close();
|
||||
}
|
||||
return resource;
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,34 +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 carbonModule = require("carbon");
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var carbonServer = new carbonModule.server.Server({
|
||||
tenanted: true,
|
||||
url: devicemgtProps["httpsURL"] + "/admin"
|
||||
});
|
||||
application.put("carbonServer", carbonServer);
|
||||
|
||||
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
|
||||
var utility = require("/app/modules/utility.js")["utility"];
|
||||
|
||||
var permissions = {
|
||||
'/permission/admin/device-mgt/user': ['ui.execute'],
|
||||
'/permission/admin/manage/api/subscribe': ['ui.execute']
|
||||
};
|
||||
//userModule.addRole("internal/devicemgt-user", ["admin"], permissions);
|
@ -1,42 +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 onSuccess;
|
||||
var onFail;
|
||||
|
||||
(function () {
|
||||
var log = new Log("/app/modules/login.js");
|
||||
var constants = require("/app/modules/constants.js");
|
||||
onSuccess = function (context) {
|
||||
var utility = require("/app/modules/utility.js").utility;
|
||||
var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
|
||||
if (context.input.samlToken) {
|
||||
apiWrapperUtil.setupTokenPairBySamlGrantType(context.input.username, context.input.samlToken);
|
||||
} else {
|
||||
apiWrapperUtil.setupTokenPairByPasswordGrantType(context.input.username, context.input.password);
|
||||
}
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var carbonServer = require("carbon").server;
|
||||
(new carbonServer.Server({url: devicemgtProps["adminService"]}))
|
||||
.login(context.input.username, context.input.password);
|
||||
};
|
||||
|
||||
onFail = function (error) {
|
||||
log.error(error.message);
|
||||
}
|
||||
})();
|
@ -1,295 +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 utils = function () {
|
||||
var log = new Log("/app/modules/oauth/token-handler-utils.js");
|
||||
|
||||
var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var carbon = require("carbon");
|
||||
|
||||
//noinspection JSUnresolvedVariable
|
||||
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
|
||||
//noinspection JSUnresolvedVariable
|
||||
var String = Packages.java.lang.String;
|
||||
|
||||
var publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
publicMethods["encode"] = function (payload) {
|
||||
//noinspection JSUnresolvedFunction
|
||||
return String(Base64.encodeBase64(String(payload).getBytes()));
|
||||
};
|
||||
|
||||
publicMethods["decode"] = function (payload) {
|
||||
//noinspection JSUnresolvedFunction
|
||||
return String(Base64.decodeBase64(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["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 {
|
||||
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
|
||||
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];
|
||||
}
|
||||
};
|
||||
|
||||
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 tokenData = {};
|
||||
tokenData["accessToken"] = responsePayload["access_token"];
|
||||
tokenData["refreshToken"] = responsePayload["refresh_token"];
|
||||
tokenData["scopes"] = responsePayload["scope"];
|
||||
return tokenData;
|
||||
} 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=" + + deviceMgtProps["oauthProvider"]["appRegistration"]["samlGrantTypeName"]
|
||||
+ "&" + "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 tokenData = {};
|
||||
tokenData["accessToken"] = responsePayload["access_token"];
|
||||
tokenData["refreshToken"] = responsePayload["refresh_token"];
|
||||
tokenData["scopes"] = responsePayload["scope"];
|
||||
return tokenData;
|
||||
} 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";
|
||||
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
|
||||
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
|
||||
//noinspection JSUnresolvedFunction
|
||||
var jwtClient = JWTClientManagerService.getJWTClient();
|
||||
// returning access token by JWT grant type
|
||||
return jwtClient.getAccessToken(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"],
|
||||
deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], null)["accessToken"];
|
||||
}
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,171 +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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* -----------------------------------------------------
|
||||
* 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/modules/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 tokenData;
|
||||
// tokenPair will include current access token as well as current refresh token
|
||||
var arrayOfScopes = devicemgtProps["scopes"];
|
||||
var stringOfScopes = "";
|
||||
arrayOfScopes.forEach(function (entry) {
|
||||
stringOfScopes += entry + " ";
|
||||
});
|
||||
tokenData = tokenUtil.
|
||||
getTokenPairByPasswordGrantType(username,
|
||||
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
|
||||
if (!tokenData) {
|
||||
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 {
|
||||
var tokenPair = {};
|
||||
tokenPair["accessToken"] = tokenData["accessToken"];
|
||||
tokenPair["refreshToken"] = tokenData["refreshToken"];
|
||||
// setting up token pair into session context as a string
|
||||
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
|
||||
|
||||
var scopes = tokenData.scopes.split(" ");
|
||||
// adding allowed scopes to the session
|
||||
session.put(constants["ALLOWED_SCOPES"], scopes);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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 tokenData;
|
||||
// accessTokenPair will include current access token as well as current refresh token
|
||||
tokenData = tokenUtil.
|
||||
getTokenPairBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION");
|
||||
if (!tokenData) {
|
||||
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 {
|
||||
var tokenPair = {};
|
||||
tokenPair["accessToken"] = tokenData["accessToken"];
|
||||
tokenPair["refreshToken"] = tokenData["refreshToken"];
|
||||
// setting up access token pair into session context as a string
|
||||
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
|
||||
|
||||
var scopes = tokenData.scopes.split(" ");
|
||||
// adding allowed scopes to the session
|
||||
session.put(constants["ALLOWED_SCOPES"], scopes);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
}();
|
@ -1,376 +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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* ----------------------------------------------------------------------------
|
||||
* Following module includes invokers
|
||||
* at Jaggery Layer for calling Backend Services, protected by OAuth Tokens.
|
||||
* These Services include both REST and SOAP Services.
|
||||
* ----------------------------------------------------------------------------
|
||||
*/
|
||||
var invokers = function () {
|
||||
var log = new Log("/app/modules/oauth/token-protected-service-invokers.js");
|
||||
|
||||
var publicXMLHTTPInvokers = {};
|
||||
var publicHTTPClientInvokers = {};
|
||||
|
||||
var privateMethods = {};
|
||||
var publicWSInvokers = {};
|
||||
|
||||
var TOKEN_EXPIRED = "Access token expired";
|
||||
var TOKEN_INVALID = "Invalid input. Access token validation failed";
|
||||
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
|
||||
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 is not set in the session, this will return null.
|
||||
*/
|
||||
privateMethods.getAccessToken = function () {
|
||||
var tokenPair = parse(session.get(constants["TOKEN_PAIR"]));
|
||||
if (tokenPair) {
|
||||
return tokenPair["accessToken"];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* ---------------------------------------------------------------------------
|
||||
* Start of XML-HTTP-REQUEST based Interceptor implementations
|
||||
* ---------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled.
|
||||
* @param httpMethod HTTP request type.
|
||||
* @param requestPayload payload/data if exists which is needed to be send.
|
||||
* @param endpoint Backend REST API url.
|
||||
* @param responseCallback a function to be called with response retrieved.
|
||||
* @param count a counter which hold the number of recursive execution
|
||||
*/
|
||||
privateMethods["execute"] = function (httpMethod, requestPayload, endpoint, responseCallback, count) {
|
||||
var xmlHttpRequest = new XMLHttpRequest();
|
||||
|
||||
xmlHttpRequest.open(httpMethod, endpoint);
|
||||
xmlHttpRequest.setRequestHeader(constants["CONTENT_TYPE_IDENTIFIER"], constants["APPLICATION_JSON"]);
|
||||
xmlHttpRequest.setRequestHeader(constants["ACCEPT_IDENTIFIER"], constants["APPLICATION_JSON"]);
|
||||
|
||||
if (devicemgtProps["isOAuthEnabled"]) {
|
||||
var accessToken = privateMethods.getAccessToken();
|
||||
if (!accessToken) {
|
||||
userModule.logout(function () {
|
||||
response.sendRedirect(devicemgtProps["appContext"] + "login");
|
||||
});
|
||||
} else {
|
||||
xmlHttpRequest.setRequestHeader(constants["AUTHORIZATION_HEADER"],
|
||||
constants["BEARER_PREFIX"] + accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (requestPayload) {
|
||||
xmlHttpRequest.send(requestPayload);
|
||||
} else {
|
||||
xmlHttpRequest.send();
|
||||
}
|
||||
|
||||
log.debug("Request : " + httpMethod + " " + endpoint);
|
||||
log.debug("Request payload if any : " + stringify(requestPayload));
|
||||
log.debug("Response status : " + xmlHttpRequest.status);
|
||||
log.debug("Response payload if any : " + xmlHttpRequest.responseText);
|
||||
|
||||
if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED ||
|
||||
xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) {
|
||||
tokenUtil.refreshTokenPair();
|
||||
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count);
|
||||
} else {
|
||||
return responseCallback(xmlHttpRequest);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled.
|
||||
* @param httpMethod HTTP request type.
|
||||
* @param requestPayload payload/data if exists which is needed to be send.
|
||||
* @param endpoint Backend REST API url.
|
||||
* @param responseCallback a function to be called with response retrieved.
|
||||
*/
|
||||
privateMethods["initiateXMLHTTPRequest"] = function (httpMethod, requestPayload, endpoint, responseCallback) {
|
||||
return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0);
|
||||
};
|
||||
|
||||
/**
|
||||
* This method invokes return initiateXMLHttpRequest for get calls.
|
||||
* @param endpoint Backend REST API url.
|
||||
* @param responseCallback a function to be called with response retrieved.
|
||||
*/
|
||||
publicXMLHTTPInvokers["get"] = function (endpoint, responseCallback) {
|
||||
var requestPayload = null;
|
||||
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
publicXMLHTTPInvokers["post"] = function (endpoint, requestPayload, responseCallback) {
|
||||
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
publicXMLHTTPInvokers["put"] = function (endpoint, requestPayload, responseCallback) {
|
||||
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback);
|
||||
};
|
||||
|
||||
/**
|
||||
* This method invokes return initiateXMLHttpRequest for delete calls.
|
||||
* @param endpoint Backend REST API url.
|
||||
* @param responseCallback a function to be called with response retrieved.
|
||||
*/
|
||||
publicXMLHTTPInvokers["delete"] = function (endpoint, responseCallback) {
|
||||
var requestPayload = null;
|
||||
return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint, responseCallback);
|
||||
};
|
||||
|
||||
/**
|
||||
* ---------------------------------------------------------------------------
|
||||
* Start of WS-REQUEST based Interceptor implementations
|
||||
* ---------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* This method add Oauth authentication header to outgoing WS Requests if Oauth authentication is enabled.
|
||||
* @param action
|
||||
* @param endpoint service end point to be triggered.
|
||||
* @param payload soap payload which need to be send.
|
||||
* @param successCallback a function to be called if the respond if successful.
|
||||
* @param errorCallback a function to be called if en error is reserved.
|
||||
* @param soapVersion soapVersion which need to used.
|
||||
*/
|
||||
privateMethods["initiateWSRequest"] = function (action, endpoint, successCallback,
|
||||
errorCallback, soapVersion, payload) {
|
||||
var ws = require("ws");
|
||||
//noinspection JSUnresolvedFunction
|
||||
var wsRequest = new ws.WSRequest();
|
||||
var options = [];
|
||||
if (devicemgtProps["isOAuthEnabled"]) {
|
||||
var accessToken = privateMethods.getAccessToken();
|
||||
if (accessToken) {
|
||||
var authenticationHeaderName = String(constants["AUTHORIZATION_HEADER"]);
|
||||
var authenticationHeaderValue = String(constants["BEARER_PREFIX"] + accessToken);
|
||||
var headers = [];
|
||||
var oAuthAuthenticationData = {};
|
||||
oAuthAuthenticationData.name = authenticationHeaderName;
|
||||
oAuthAuthenticationData.value = authenticationHeaderValue;
|
||||
headers.push(oAuthAuthenticationData);
|
||||
options.HTTPHeaders = headers;
|
||||
} else {
|
||||
response.sendRedirect(devicemgtProps["appContext"] + "login");
|
||||
}
|
||||
}
|
||||
options.useSOAP = soapVersion;
|
||||
options.useWSA = constants["WEB_SERVICE_ADDRESSING_VERSION"];
|
||||
options.action = action;
|
||||
var wsResponse;
|
||||
try {
|
||||
wsRequest.open(options, endpoint, false);
|
||||
if (payload) {
|
||||
wsRequest.send(payload);
|
||||
} else {
|
||||
wsRequest.send();
|
||||
}
|
||||
wsResponse = wsRequest.responseE4X;
|
||||
} catch (e) {
|
||||
return errorCallback(e);
|
||||
}
|
||||
return successCallback(wsResponse);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param successCallback a function to be called if the respond if successful.
|
||||
* @param errorCallback a function to be called if en error is reserved.
|
||||
* @param soapVersion soapVersion which need to used.
|
||||
*/
|
||||
publicWSInvokers["soapRequest"] = function (action, requestPayload, endpoint,
|
||||
successCallback, errorCallback, soapVersion) {
|
||||
return privateMethods.initiateWSRequest(action, endpoint, successCallback,
|
||||
errorCallback, soapVersion, requestPayload);
|
||||
};
|
||||
|
||||
/**
|
||||
* ---------------------------------------------------------------------------
|
||||
* Start of HTTP-CLIENT-REQUEST based Interceptor implementations
|
||||
* ---------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* This method add Oauth authentication header to outgoing HTTPClient Requests if Oauth authentication is enabled.
|
||||
* @param method HTTP request type.
|
||||
* @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.
|
||||
* @param errorCallback a function to be called if en error is reserved.
|
||||
*/
|
||||
privateMethods["initiateHTTPClientRequest"] = function (method, url, successCallback, errorCallback, payload) {
|
||||
//noinspection JSUnresolvedVariable
|
||||
var HttpClient = Packages.org.apache.commons.httpclient.HttpClient;
|
||||
var httpMethodObject;
|
||||
switch (method) {
|
||||
case constants["HTTP_GET"]:
|
||||
//noinspection JSUnresolvedVariable
|
||||
var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod;
|
||||
httpMethodObject = new GetMethod(url);
|
||||
break;
|
||||
case constants["HTTP_POST"]:
|
||||
//noinspection JSUnresolvedVariable
|
||||
var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod;
|
||||
httpMethodObject = new PostMethod(url);
|
||||
break;
|
||||
case constants["HTTP_PUT"]:
|
||||
//noinspection JSUnresolvedVariable
|
||||
var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod;
|
||||
httpMethodObject = new PutMethod(url);
|
||||
break;
|
||||
case constants["HTTP_DELETE"]:
|
||||
//noinspection JSUnresolvedVariable
|
||||
var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod;
|
||||
httpMethodObject = new DeleteMethod(url);
|
||||
break;
|
||||
default:
|
||||
//noinspection JSUnresolvedFunction
|
||||
throw new IllegalArgumentException("Invalid HTTP request method: " + method);
|
||||
}
|
||||
//noinspection JSUnresolvedVariable
|
||||
var Header = Packages.org.apache.commons.httpclient.Header;
|
||||
var header = new Header();
|
||||
header.setName(constants["CONTENT_TYPE_IDENTIFIER"]);
|
||||
header.setValue(constants["APPLICATION_JSON"]);
|
||||
//noinspection JSUnresolvedFunction
|
||||
httpMethodObject.addRequestHeader(header);
|
||||
header = new Header();
|
||||
header.setName(constants["ACCEPT_IDENTIFIER"]);
|
||||
header.setValue(constants["APPLICATION_JSON"]);
|
||||
//noinspection JSUnresolvedFunction
|
||||
httpMethodObject.addRequestHeader(header);
|
||||
|
||||
if (devicemgtProps["isOAuthEnabled"]) {
|
||||
var accessToken = privateMethods.getAccessToken();
|
||||
if (accessToken) {
|
||||
header = new Header();
|
||||
header.setName(constants["AUTHORIZATION_HEADER"]);
|
||||
header.setValue(constants["BEARER_PREFIX"] + accessToken);
|
||||
//noinspection JSUnresolvedFunction
|
||||
httpMethodObject.addRequestHeader(header);
|
||||
} else {
|
||||
response.sendRedirect(devicemgtProps["appContext"] + "login");
|
||||
}
|
||||
}
|
||||
//noinspection JSUnresolvedFunction
|
||||
var stringRequestEntity = new StringRequestEntity(stringify(payload));
|
||||
//noinspection JSUnresolvedFunction
|
||||
httpMethodObject.setRequestEntity(stringRequestEntity);
|
||||
var client = new HttpClient();
|
||||
try {
|
||||
//noinspection JSUnresolvedFunction
|
||||
client.executeMethod(httpMethodObject);
|
||||
//noinspection JSUnresolvedFunction
|
||||
var status = httpMethodObject.getStatusCode();
|
||||
if (status == 200) {
|
||||
//noinspection JSUnresolvedFunction
|
||||
return successCallback(httpMethodObject.getResponseBody());
|
||||
} else {
|
||||
//noinspection JSUnresolvedFunction
|
||||
return errorCallback(httpMethodObject.getResponseBody());
|
||||
}
|
||||
} catch (e) {
|
||||
return errorCallback(response);
|
||||
} finally {
|
||||
//noinspection JSUnresolvedFunction
|
||||
method.releaseConnection();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
publicHTTPClientInvokers["get"] = function (url, successCallback, errorCallback) {
|
||||
var requestPayload = null;
|
||||
return privateMethods.
|
||||
initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, requestPayload);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param errorCallback a function to be called if en error is reserved.
|
||||
*/
|
||||
publicHTTPClientInvokers["post"] = function (url, payload, successCallback, errorCallback) {
|
||||
return privateMethods.
|
||||
initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback, payload);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param errorCallback a function to be called if en error is reserved.
|
||||
*/
|
||||
publicHTTPClientInvokers["put"] = function (url, payload, successCallback, errorCallback) {
|
||||
return privateMethods.
|
||||
initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback, payload);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
publicHTTPClientInvokers["delete"] = function (url, successCallback, errorCallback) {
|
||||
var requestPayload = null;
|
||||
return privateMethods.
|
||||
initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback, requestPayload);
|
||||
};
|
||||
|
||||
var publicMethods = {};
|
||||
publicMethods.XMLHttp = publicXMLHTTPInvokers;
|
||||
publicMethods.WS = publicWSInvokers;
|
||||
publicMethods.HttpClient = publicHTTPClientInvokers;
|
||||
|
||||
return publicMethods;
|
||||
}();
|
File diff suppressed because one or more lines are too long
@ -1,140 +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 utility;
|
||||
utility = function () {
|
||||
|
||||
var constants = require('/app/modules/constants.js');
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var log = new Log("/app/modules/utility.js");
|
||||
var JavaClass = Packages.java.lang.Class;
|
||||
var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
|
||||
var getOsgiService = function (className) {
|
||||
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(JavaClass.forName(className));
|
||||
};
|
||||
|
||||
var deviceTypeConfigMap = {};
|
||||
|
||||
var publicMethods = {};
|
||||
|
||||
publicMethods.startTenantFlow = function (userInfo) {
|
||||
var context, carbon = require('carbon');
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
context.setTenantDomain(carbon.server.tenantDomain({
|
||||
tenantId: userInfo.tenantId
|
||||
}));
|
||||
context.setTenantId(userInfo.tenantId);
|
||||
context.setUsername(userInfo.username || null);
|
||||
};
|
||||
|
||||
publicMethods.endTenantFlow = function () {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
};
|
||||
|
||||
publicMethods.getDeviceManagementService = function () {
|
||||
return getOsgiService('org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService');
|
||||
};
|
||||
|
||||
publicMethods.getUserManagementService = function () {
|
||||
return getOsgiService("org.wso2.carbon.device.mgt.user.core.UserManager");
|
||||
};
|
||||
|
||||
publicMethods.getPolicyManagementService = function () {
|
||||
return getOsgiService("org.wso2.carbon.policy.mgt.core.PolicyManagerService");
|
||||
};
|
||||
|
||||
publicMethods.getIoTServerConfig = function (configName) {
|
||||
var path = "/config/iot-config.json";
|
||||
var file = new File(path);
|
||||
try {
|
||||
file.open("r");
|
||||
var content = file.readAll();
|
||||
} catch (err) {
|
||||
log.error("Error while reading IoT server config file `" + path + "`: " + err);
|
||||
} finally {
|
||||
file.close();
|
||||
}
|
||||
var json = parse(content);
|
||||
return json[configName];
|
||||
};
|
||||
|
||||
publicMethods.getDeviceTypeConfig = function (deviceType) {
|
||||
var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view");
|
||||
|
||||
if (deviceType in deviceTypeConfigMap) {
|
||||
return deviceTypeConfigMap[deviceType];
|
||||
}
|
||||
var deviceTypeConfig;
|
||||
var deviceTypeConfigFile = new File("/app/units/" + unitName + "/private/config.json");
|
||||
if (deviceTypeConfigFile.isExists()) {
|
||||
try {
|
||||
deviceTypeConfigFile.open("r");
|
||||
deviceTypeConfig = parse(deviceTypeConfigFile.readAll());
|
||||
} catch (err) {
|
||||
log.error("Error while reading device config file for `" + deviceType + "`: " + err);
|
||||
} finally {
|
||||
deviceTypeConfigFile.close();
|
||||
}
|
||||
}
|
||||
deviceTypeConfigMap[deviceType] = deviceTypeConfig;
|
||||
return deviceTypeConfig;
|
||||
};
|
||||
|
||||
publicMethods.getOperationIcon = function (deviceType, operation) {
|
||||
var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view");
|
||||
var iconPath = "/app/units/" + unitName + "/public/images/operations/" + operation + ".png";
|
||||
var icon = new File(iconPath);
|
||||
if (icon.isExists()) {
|
||||
return devicemgtProps["appContext"] + "public/" + unitName + "/images/operations/" + operation + ".png";
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getDeviceThumb = function (deviceType) {
|
||||
var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view");
|
||||
var iconPath = "/app/units/" + unitName + "/public/images/thumb.png";
|
||||
var icon = new File(iconPath);
|
||||
if (icon.isExists()) {
|
||||
return devicemgtProps["appContext"] + "public/" + unitName + "/images/thumb.png";
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getTenantedDeviceUnitName = function (deviceType, unitPostfix) {
|
||||
var user = session.get(constants.USER_SESSION_KEY);
|
||||
if (!user) {
|
||||
log.error("User object was not found in the session");
|
||||
throw constants.ERRORS.USER_NOT_FOUND;
|
||||
}
|
||||
var unitName = user.domain + ".cdmf.unit.device.type." + deviceType + "." + unitPostfix;
|
||||
if (new File("/app/units/" + unitName).isExists()) {
|
||||
return unitName;
|
||||
}
|
||||
unitName = "cdmf.unit.device.type." + deviceType + "." + unitPostfix;
|
||||
if (new File("/app/units/" + unitName).isExists()) {
|
||||
return unitName;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,47 +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. --}}
|
||||
|
||||
{{!-- defining controlled access parameters --}}
|
||||
{{#zone "accessControl"}}
|
||||
{{
|
||||
unit "mdm.unit.enrollments.access-control"
|
||||
allowedPlatform = "Android"
|
||||
currentPage = "download-agent"
|
||||
}}
|
||||
{{/zone}}
|
||||
{{!-- Inputting content into defined zones in enrollment layout --}}
|
||||
{{unit "mdm.unit.ui.title" pageTitle = "Android Enrollment | Download and Install Agent"}}
|
||||
{{#zone "headerTitle"}}
|
||||
Android Enrollment
|
||||
{{/zone}}
|
||||
|
||||
{{#zone "content"}}
|
||||
{{
|
||||
unit "mdm.unit.wizard-stepper"
|
||||
steps = "Download and Install Agent"
|
||||
currentStep = "Download and Install Agent"
|
||||
currentStepIndex = 0
|
||||
}}
|
||||
<div class="row">
|
||||
<div class="col-md-4 wr-text">
|
||||
If you haven't already enrolled this device with {{companyName}},
|
||||
download and install the following IoT Server Agent to continue.
|
||||
<div class="wr-buttons">
|
||||
<a href="{{agentDownloadURL}}" class="btn-download-agent">Download IoT Server Agent</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{/zone}}
|
@ -1,36 +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.
|
||||
*/
|
||||
|
||||
function onRequest(context) {
|
||||
var log = new Log("mdm.page.enrollments.android.agent.download");
|
||||
|
||||
var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var viewModel = {};
|
||||
|
||||
// setting android agent download URL
|
||||
// Needs host=>http:9763 since self-signed certificates won't allow downloads in android
|
||||
//TODO: try to retrieve page name from UUF
|
||||
viewModel.agentDownloadURL = mdmProps["managerHTTPSURL"] + mdmProps["appContext"] + "public/mdm.page.enrollments.android.download-agent/asset/" + mdmProps["androidAgentApp"];
|
||||
var companyProps = session.get("COMPANY_DETAILS");
|
||||
if (!companyProps) {
|
||||
viewModel.companyName = mdmProps.generalConfig.companyName;
|
||||
} else {
|
||||
viewModel.companyName = companyProps.companyName;
|
||||
}
|
||||
return viewModel;
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"uri": "/enrollments/android/download-agent",
|
||||
"layout": "mdm.layout.enrollment",
|
||||
"isAnonymous": true
|
||||
}
|
@ -1,17 +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. --}}
|
||||
|
||||
{{!-- This page will route into relevant download url based on User-Agent --}}
|
@ -1,39 +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.
|
||||
*/
|
||||
|
||||
function onRequest(context) {
|
||||
var log = new Log("mdm.page.enrollments.default");
|
||||
var UAParser = require("/app/modules/ua-parser.min.js")["UAParser"];
|
||||
|
||||
var parser = new UAParser();
|
||||
var userAgent = request.getHeader("User-Agent");
|
||||
parser.setUA(userAgent);
|
||||
parser.getResult();
|
||||
var os = parser.getOS();
|
||||
var platform = os.name;
|
||||
|
||||
if (platform == "Android") {
|
||||
response.sendRedirect(context.app.context + "/enrollments/android/download-agent");
|
||||
} else if (platform == "iOS") {
|
||||
response.sendRedirect(context.app.context + "/enrollments/ios/download-agent");
|
||||
} else if (platform == "Windows Phone") {
|
||||
response.sendRedirect(context.app.context + "/enrollments/windows/invoke-agent");
|
||||
} else {
|
||||
response.sendRedirect(context.app.context + "/enrollments/error/unintentional-request");
|
||||
}
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"uri": "/enrollment",
|
||||
"layout": "mdm.layout.enrollment",
|
||||
"isAnonymous": true
|
||||
}
|
@ -1,33 +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. --}}
|
||||
|
||||
{{!-- Inputting content into defined zones in enrollment layout --}}
|
||||
{{unit "mdm.unit.ui.title" pageTitle="Device Enrollment"}}
|
||||
{{#zone "headerTitle"}}
|
||||
Unintentional Request
|
||||
{{/zone}}
|
||||
{{#zone "content"}}
|
||||
<div class="wr-head">
|
||||
<h3>Possible Causes :</h3>
|
||||
</div>
|
||||
[1] You have tried making a request call intended to be made by a different Platform. <br />
|
||||
[2] You have tried accessing enrollment steps out of order. <br />
|
||||
<div class="row">
|
||||
<div class="container col-md-4 wr-buttons">
|
||||
<a href="{{@app.context}}/enrollment" class="btn-download-agent">Redirect</a>
|
||||
</div>
|
||||
</div>
|
||||
{{/zone}}
|
@ -1,6 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"uri": "/enrollments/error/unintentional-request",
|
||||
"layout": "mdm.layout.enrollment",
|
||||
"isAnonymous": true
|
||||
}
|
@ -1,32 +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. --}}
|
||||
|
||||
{{!-- Inputting content into defined zones in enrollment layout --}}
|
||||
{{unit "mdm.unit.ui.title" pageTitle="Page Error"}}
|
||||
{{#zone "headerTitle"}}
|
||||
404 - Resource Not Found
|
||||
{{/zone}}
|
||||
{{#zone "content"}}
|
||||
<div class="wr-head">
|
||||
<h3>Possible Causes :</h3>
|
||||
</div>
|
||||
You are seen this page since the resource you are trying to access is not available.<br/>
|
||||
<div class="row">
|
||||
<div class="container col-md-4 wr-buttons">
|
||||
<a href="{{@app.context}}/enrollment" class="btn-download-agent">Goto Enroll Page</a>
|
||||
</div>
|
||||
</div>
|
||||
{{/zone}}
|
@ -1,6 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"uri": "/error/404",
|
||||
"layout": "mdm.layout.enrollment",
|
||||
"isAnonymous": true
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"uri": "/",
|
||||
"isAnonymous": true,
|
||||
"extends": "mdm.page.error"
|
||||
}
|
@ -1,15 +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. --}}
|
@ -1,79 +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.
|
||||
*/
|
||||
|
||||
function onRequest(context) {
|
||||
var log = new Log("enrollment-access-control-unit backend js");
|
||||
log.debug("calling enrollment-access-control-unit");
|
||||
|
||||
var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var UAParser = require("/app/modules/ua-parser.min.js")["UAParser"];
|
||||
|
||||
var parser = new UAParser();
|
||||
var userAgent = request.getHeader("User-Agent");
|
||||
parser.setUA(userAgent);
|
||||
parser.getResult();
|
||||
var userAgentPlatform = parser.getOS()["name"];
|
||||
|
||||
if (userAgentPlatform != context.unit.params["allowedPlatform"]) {
|
||||
// if userAgentPlatform is not allowed
|
||||
log.error("platform not allowed");
|
||||
response.sendRedirect(context.app.context + "/enrollments/error/unintentional-request");
|
||||
} else {
|
||||
var lastPage = context.unit.params["lastPage"];
|
||||
var nextPage = context.unit.params["nextPage"];
|
||||
var currentPage = context.unit.params["currentPage"];
|
||||
// if userAgentPlatform is allowed,
|
||||
// restricting unordered intermediate page access
|
||||
if (lastPage && currentPage && nextPage) {
|
||||
// meaning it's not first page, but a middle page
|
||||
if (!session.get("lastAccessedPage")) {
|
||||
// meaning a middle page is accessed at first
|
||||
response.sendRedirect(context.app.context + "/enrollments/error/unintentional-request");
|
||||
} else if (!(session.get("lastAccessedPage") == currentPage) &&
|
||||
!(session.get("lastAccessedPage") == lastPage) &&
|
||||
!(session.get("lastAccessedPage") == nextPage)) {
|
||||
response.sendRedirect(context.app.context + "/enrollments/error/unintentional-request");
|
||||
} else if (currentPage) {
|
||||
// if currentPage is set, update lastAccessedPage as currentPage
|
||||
session.put("lastAccessedPage", currentPage);
|
||||
}
|
||||
} else if (lastPage && currentPage && !nextPage) {
|
||||
// meaning it's not first page, not a middle page, but the last page in wizard
|
||||
if (!session.get("lastAccessedPage")) {
|
||||
// this means the last page is accessed at first
|
||||
response.sendRedirect(context.app.context + "/enrollments/error/unintentional-request");
|
||||
} else if (!(session.get("lastAccessedPage") == currentPage) &&
|
||||
!(session.get("lastAccessedPage") == lastPage)) {
|
||||
response.sendRedirect(context.app.context + "/enrollments/error/unintentional-request");
|
||||
} else if (currentPage) {
|
||||
// if currentPage is set, update lastAccessedPage as currentPage
|
||||
session.put("lastAccessedPage", currentPage);
|
||||
}
|
||||
} else if (currentPage) {
|
||||
// meaning it's the first page
|
||||
// if currentPage is set, update lastAccessedPage as currentPage
|
||||
session.put("lastAccessedPage", currentPage);
|
||||
}
|
||||
}
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("last-accessed-page = " + session.get("lastAccessedPage") +
|
||||
" : " + "session-id = " + session.getId());
|
||||
}
|
||||
return context;
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"isAnonymous": true
|
||||
}
|
@ -1,37 +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. --}}
|
||||
|
||||
<div>
|
||||
<div class="row">
|
||||
<div class="container col-md-8 wr-text">
|
||||
Please read the following end user license agreement carefully.
|
||||
In order to complete device enrollment, you must accept these terms.
|
||||
<br /><br />
|
||||
<div class="wr-agreement">
|
||||
<h4>{{companyName}} License Agreement</h4>
|
||||
<p id="license-text">{{license}}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="container col-md-4 wr-buttons">
|
||||
<a href="{{@unit.params.licenseAcceptActionURL}}" class="btn-download-agent">I accept the terms</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{#zone "bottomJs"}}
|
||||
{{js "/js/license-box.js"}}
|
||||
{{/zone}}
|
@ -1,41 +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.
|
||||
*/
|
||||
|
||||
function onRequest(context) {
|
||||
var log = new Log("license-box-agent-unit");
|
||||
log.debug("calling license-box-agent-unit backend js");
|
||||
|
||||
var viewModel = {};
|
||||
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
|
||||
var mdmProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
|
||||
var license = deviceModule.getLicense(context.unit.params["platform"], context.unit.params["languageCode"]);
|
||||
if (license) {
|
||||
viewModel.license = license;
|
||||
} else {
|
||||
viewModel.license = "ERROR: Unable to retrieve License Text.";
|
||||
}
|
||||
|
||||
var companyProps = session.get("COMPANY_DETAILS");
|
||||
if (!companyProps) {
|
||||
viewModel.companyName = mdmProps.generalConfig.companyName;
|
||||
} else {
|
||||
viewModel.companyName = companyProps.companyName;
|
||||
}
|
||||
return viewModel;
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
{
|
||||
"version" : "1.0.0",
|
||||
"isAnonymous" : true
|
||||
}
|
@ -1,22 +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.
|
||||
*/
|
||||
|
||||
$(document).ready(function () {
|
||||
var license = $("#license-text").text();
|
||||
$("#license-text").html(license);
|
||||
});
|
@ -1,74 +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. --}}
|
||||
|
||||
<form class="form-login-box" action="{{@unit.params.loginActionURL}}" method="POST" onsubmit="return validate();">
|
||||
<div class="row">
|
||||
<div class="container col-md-8 wr-text">
|
||||
<!-- start of validation -->
|
||||
<div id="enrollment-error-msg" class="alert alert-danger hidden" role="alert">
|
||||
<span></span>
|
||||
</div>
|
||||
<!-- end of validation -->
|
||||
{{#excludes @unit.params.loginActionURL "windows"}}
|
||||
<div class="wr-input-control">
|
||||
<label class="input-label" for="domain">
|
||||
Domain *
|
||||
</label>
|
||||
<input id="domain" name="domain" type="text" class="form-control" maxlength="30"
|
||||
placeholder="Enter your tenant domain here" />
|
||||
</div>
|
||||
{{/excludes}}
|
||||
<div class="wr-input-control">
|
||||
<label class="input-label" for="username">
|
||||
Username *
|
||||
</label>
|
||||
<input id="username" name="username" type="text" class="form-control" maxlength="30"
|
||||
placeholder="Enter your username here" />
|
||||
</div>
|
||||
<br class="c-both" />
|
||||
<div class="wr-input-control">
|
||||
<label class="input-label" for="password">
|
||||
Password *
|
||||
</label>
|
||||
<input id="password" name="password" type="password" class="form-control" maxlength="30"
|
||||
placeholder="Enter your password here" />
|
||||
</div>
|
||||
<br class="c-both" />
|
||||
<div id="ownership-content" style="visibility:hidden; position:absolute">
|
||||
<div class="radio">
|
||||
<label class="input-label">
|
||||
<input type="radio" name="ownership" value="BYOD" checked>
|
||||
BYOD (This is my own device)
|
||||
</label>
|
||||
</div>
|
||||
<div class="radio">
|
||||
<label class="input-label">
|
||||
<input type="radio" name="ownership" value="COPE">
|
||||
COPE (This is a corporate device)
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="container col-md-4 wr-buttons">
|
||||
<a href="#" class="btn-download-agent">Login</a>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{{#zone "bottomJs"}}
|
||||
{{js "/js/login-box.js"}}
|
||||
{{/zone}}
|
@ -1,30 +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.
|
||||
*/
|
||||
|
||||
function onRequest(context) {
|
||||
context.handlebars.registerHelper("excludes", function (lvalue, rvalue, options) {
|
||||
if (arguments.length < 3) {
|
||||
throw new Error("Handlebars Helper equal needs 2 parameters");
|
||||
}
|
||||
if (lvalue.indexOf(rvalue) > -1) {
|
||||
return options.inverse(this);
|
||||
} else {
|
||||
return options.fn(this);
|
||||
}
|
||||
});
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
{
|
||||
"version" : "1.0.0",
|
||||
"isAnonymous" : true
|
||||
}
|
@ -1,86 +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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* This method will return query parameter value given its name
|
||||
* @param name Query parameter name
|
||||
* @returns {string} Query parameter value
|
||||
*/
|
||||
var getParameterByName = function (name) {
|
||||
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
|
||||
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
|
||||
results = regex.exec(location.search);
|
||||
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
|
||||
};
|
||||
|
||||
var errorMsgWrapper = "#enrollment-error-msg";
|
||||
var errorMsg = errorMsgWrapper + " span";
|
||||
|
||||
/**
|
||||
* This method will execute on login form submission and validate input.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
var validate = function () {
|
||||
var username = $("input#username").val();
|
||||
var password = $("input#password").val();
|
||||
|
||||
if (!username && !password) {
|
||||
$(errorMsg).text("Both username and password are empty. You cannot proceed.");
|
||||
if ($(errorMsgWrapper).hasClass("hidden")) {
|
||||
$(errorMsgWrapper).removeClass("hidden");
|
||||
}
|
||||
return false;
|
||||
} else if (!username && password) {
|
||||
$(errorMsg).text("Username should not be empty.");
|
||||
if ($(errorMsgWrapper).hasClass("hidden")) {
|
||||
$(errorMsgWrapper).removeClass("hidden");
|
||||
}
|
||||
return false;
|
||||
} else if (username && !password) {
|
||||
$(errorMsg).text("Password should not be empty.");
|
||||
if ($(errorMsgWrapper).hasClass("hidden")) {
|
||||
$(errorMsgWrapper).removeClass("hidden");
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
$(document).ready(function () {
|
||||
var error = getParameterByName("error");
|
||||
if (error == "auth-failed") {
|
||||
var defaultMessage = "Please provide a correct username and password to continue.";
|
||||
var customMessage = getParameterByName("message");
|
||||
if (customMessage) {
|
||||
$(errorMsg).text("Authentication failed. " + customMessage);
|
||||
} else {
|
||||
$(errorMsg).text("Authentication failed. " + defaultMessage);
|
||||
}
|
||||
$(errorMsgWrapper).removeClass("hidden");
|
||||
} else if (error == "unexpected") {
|
||||
$(errorMsg).text("An unexpected error occured. Please try again.");
|
||||
$(errorMsgWrapper).removeClass("hidden");
|
||||
}
|
||||
});
|
||||
|
||||
$(".btn-download-agent").click(function () {
|
||||
$(".form-login-box").submit();
|
||||
});
|
||||
|
||||
|
@ -1,24 +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.
|
||||
}}
|
||||
{{#zone "contentTitle"}}
|
||||
<div class="row wr-device-board">
|
||||
<div class="col-lg-12 wr-secondary-bar">
|
||||
<span class="page-sub-title">{{@unit.params.pageHeader}}</span>
|
||||
</div>
|
||||
</div>
|
||||
{{/zone}}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue