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

4.x.x
mharindu 8 years ago
commit 3331604699

@ -1,56 +1,51 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* KIND, either express or implied. See the License for the * either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
/* /*
* This module contains user and roles related functionality * This module contains user and roles related functionality.
*/ */
var userModule = function () { var userModule = function () {
var log = new Log("/app/modules/user.js"); var log = new Log("/app/modules/user.js");
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js")["utility"]; var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var devicemgtProps = require("/app/conf/devicemgt-props.js").config();
var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker; var serviceInvokers = require("/app/modules/backend-service-invoker.js")["backendServiceInvoker"];
/* Initializing user manager */ /* Initializing user manager */
var carbon = require('carbon'); var carbon = require("carbon");
var tenantId = carbon.server.tenantId(); var url = carbon.server.address("https") + "/admin/services";
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url); var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
var deviceManagementService = utility.getDeviceManagementService();
var EmailMessageProperties = Packages.org.wso2.carbon.device.mgt.common.EmailMessageProperties;
var publicMethods = {}; var publicMethods = {};
var privateMethods = {}; var privateMethods = {};
/** /**
* Get the carbon user object from the session. If not found - it will throw a user not found error. * Get the carbon user object from the session. If not found - it will throw a user not found error.
* @returns {carbon user object} * @returns {object} carbon user object
*/ */
privateMethods.getCarbonUser = function () { privateMethods.getCarbonUser = function () {
var carbon = require('carbon'); var carbon = require("carbon");
var carbonUser = session.get(constants.USER_SESSION_KEY); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require('/app/modules/utility.js').utility; var utility = require("/modules/utility.js")["utility"];
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
return carbonUser; return carbonUser;
}; };
@ -59,83 +54,25 @@ var userModule = function () {
* Only GET method is implemented for now since there are no other type of methods used this method. * 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 url - URL to call the backend without the host
* @param method - HTTP Method (GET, POST) * @param method - HTTP Method (GET, POST)
* @returns { * @returns An object with 'status': 'success'|'error', 'content': {}
* 'status': 'success'|'error',
* 'content': {}
* }
*/ */
privateMethods.callBackend = function (url, method) { privateMethods.callBackend = function (url, method) {
if (constants.HTTP_GET == method) { if (constants["HTTP_GET"] == method) {
var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { return serviceInvokers.XMLHttp.get(url,
var response = {}; function (backendResponse) {
response.content = responsePayload["responseContent"]; var response = {};
if (responsePayload["responseContent"] == null && responsePayload != null) { response.content = backendResponse.responseText;
response.content = responsePayload; 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;
} }
response.status = "success"; );
return response;
},
function (responsePayload) {
var response = {};
response.content = responsePayload;
response.status = "error";
return response;
});
return response;
} else { } else {
log.error("Programming error : This method only support HTTP GET requests."); log.error("Runtime error : This method only support HTTP GET requests.");
}
};
/*
@Deprecated
*/
/**
* Add user to mdm-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 userRoles Roles assigned to the user
*
* @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
*/
publicMethods.addUser = function (username, firstname, lastname, emailAddress, userRoles) {
var statusCode, carbon = require('carbon');
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 tenantId = carbon.server.tenantId();
var userManager = new carbon.user.UserManager(server, tenantId);
if (userManager.userExists(username)) {
if (log.isDebugEnabled()) {
log.debug("A user with name '" + username + "' already exists.");
}
// http status code 409 refers to - conflict.
statusCode = 409;
} else {
var initialUserPassword = privateMethods.generateInitialUserPassword();
var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);
userManager.addUser(username, initialUserPassword, userRoles, defaultUserClaims, "default");
privateMethods.inviteUserToEnroll(username, initialUserPassword);
if (log.isDebugEnabled()) {
log.debug("A new user with name '" + username + "' was created.");
}
// http status code 201 refers to - created.
statusCode = 201;
}
return statusCode;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
} }
}; };
@ -179,197 +116,6 @@ var userModule = function () {
} }
}; };
/*
@Deprecated
*/
/**
* Remove an existing user from mdm-user-store.
*
* @param username Username of the user
* @returns {number} HTTP Status code 200 if succeeded, 409 if the user does not exist
*/
publicMethods.removeUser = function (username) {
var statusCode, carbon = require('carbon');
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 tenantId = carbon.server.tenantId();
var userManager = new carbon.user.UserManager(server, tenantId);
if (userManager.userExists(username)) {
userManager.removeUser(username);
if (log.isDebugEnabled()) {
log.debug("An existing user with name '" + username + "' was removed.");
}
// http status code 200 refers to - success.
statusCode = 200;
} else {
if (log.isDebugEnabled()) {
log.debug("A user with name '" + username + "' does not exist to remove.");
}
// http status code 409 refers to - conflict.
statusCode = 409;
}
return statusCode;
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/*
@Deprecated
*/
/**
* Private method to be used by addUser() to
* generate an initial user password for a user.
* This will be the password used by a user for his initial login to the system.
*
* @returns {string} Initial User Password
*/
privateMethods.generateInitialUserPassword = function () {
var passwordLength = 6;
//defining the pool of characters to be used for initial password generation
var lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
var upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numericCharset = "0123456789";
var totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
var totalCharsetLength = totalCharset.length;
var initialUserPassword = "";
for (var i = 0; i < passwordLength; ++i) {
initialUserPassword += totalCharset.charAt(Math.floor(Math.random() * totalCharsetLength));
}
if (log.isDebugEnabled()) {
log.debug("Initial password created for new user : " + initialUserPassword);
}
return String(initialUserPassword);
};
/*
@Deprecated
*/
/**
* Build default user claims.
*
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
*
* @returns {Object} Default user claims to be provided
*/
privateMethods.buildDefaultUserClaims = function (firstname, lastname, emailAddress) {
var defaultUserClaims = {
"http://wso2.org/claims/givenname": firstname,
"http://wso2.org/claims/lastname": lastname,
"http://wso2.org/claims/emailaddress": emailAddress
};
if (log.isDebugEnabled()) {
log.debug("ClaimMap created for new user : " + stringify(defaultUserClaims));
}
return defaultUserClaims;
};
/*
@Deprecated
*/
/**
* Send an initial invitation email to a user with username/password attached
* for the very-first enrollment with WSO2 MDM.
*
* @param username Username of the user
* @param password Password of the user
*/
privateMethods.inviteUserToEnroll = function (username, password) {
var carbon = require('carbon');
var enrollmentURL = devicemgtProps.generalConfig.host + devicemgtProps.webAgentContext + "download-agent";
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;
}
//var user = userManagementService.getUser(username, carbonUser.tenantId);
try {
utility.startTenantFlow(carbonUser);
var tenantId = carbon.server.tenantId();
var userManager = new carbon.user.UserManager(server, tenantId);
var emailTo = [];
var user = userManager.getUser(username);
emailTo[0] = privateMethods.getEmail(username, userManager);
var emailMessageProperties = new EmailMessageProperties();
emailMessageProperties.setMailTo(emailTo);
emailMessageProperties.setFirstName(privateMethods.getFirstName(username, userManager));
emailMessageProperties.setUserName(username);
emailMessageProperties.setPassword(password);
emailMessageProperties.setEnrolmentUrl(enrollmentURL);
deviceManagementService.sendRegistrationEmail(emailMessageProperties);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/*
@Deprecated
*/
privateMethods.getEmail = function (username, userManager) {
return userManager.getClaim(username, "http://wso2.org/claims/emailaddress", null)
};
/*
@Deprecated
*/
privateMethods.getFirstName = function (username, userManager) {
return userManager.getClaim(username, "http://wso2.org/claims/givenname", null)
};
/*
@Deprecated
*/
privateMethods.getLastName = function (username, userManager) {
return userManager.getClaim(username, "http://wso2.org/claims/lastname", null)
};
/*
@Deprecated
*/
publicMethods.inviteUser = function (username) {
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;
}
var enrollmentURL = devicemgtProps.generalConfig.host + devicemgtProps.webAgentContext + "download-agent";
try {
utility.startTenantFlow(carbonUser);
var tenantId = carbon.server.tenantId();
var userManager = new carbon.user.UserManager(server, tenantId);
var user = userManager.getUser(username);
var emailProperties = new EmailMessageProperties();
var emailTo = [];
emailTo[0] = privateMethods.getEmail(username, userManager);
emailProperties.setMailTo(emailTo);
//emailProperties.setFirstName(user.getFirstName());
emailProperties.setFirstName(privateMethods.getFirstName(username, userManager));
emailProperties.setEnrolmentUrl(enrollmentURL);
deviceManagementService.sendEnrolmentInvitation(emailProperties);
} catch (e) {
throw e;
} finally {
utility.endTenantFlow();
}
};
/* /*
@Updated @Updated
*/ */
@ -382,9 +128,12 @@ var userModule = function () {
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users"; var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users?offset=0&limit=100";
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).users;
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -395,22 +144,16 @@ var userModule = function () {
/** /**
* Return a User object from the backend by calling the JAX-RS * Return a User object from the backend by calling the JAX-RS
* @param username * @param username
* @returns { * @returns {object} a response object with status and content on success.
* 'status': 'success'|'error',
* 'content': {
"username": "abc",
"firstname": "abc",
"lastname": "efj",
"emailAddress": "abc@abc.com"
}
* }
*/ */
publicMethods.getUser = function (username) { publicMethods.getUser = function (username) {
var carbonUser = privateMethods.getCarbonUser(); var carbonUser = privateMethods.getCarbonUser();
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/view?username=" + username; var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
var response = privateMethods.callBackend(url, constants.HTTP_GET); encodeURIComponent(username);
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
response["content"] = parse(response.content);
response["userDomain"] = carbonUser.domain; response["userDomain"] = carbonUser.domain;
return response; return response;
} catch (e) { } catch (e) {
@ -419,18 +162,19 @@ var userModule = function () {
utility.endTenantFlow(); utility.endTenantFlow();
} }
}; };
/** /**
* TODO: comment * Returns a set of roles assigned to a particular user
* @param username * @param username
* @returns {*} * @returns {object} a response object with status and content on success.
*/ */
publicMethods.getRolesByUsername = function (username) { publicMethods.getRolesByUsername = function (username) {
var carbonUser = privateMethods.getCarbonUser(); var carbonUser = privateMethods.getCarbonUser();
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/roles?username=" + username; var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
var response = privateMethods.callBackend(url, constants.HTTP_GET); encodeURIComponent(username) + "/roles";
return response; return privateMethods.callBackend(url, constants["HTTP_GET"]);
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -450,8 +194,8 @@ var userModule = function () {
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/users-by-username"; var url = devicemgtProps["httpsURL"] + "/mdm-admin/users/users-by-username";
return privateMethods.callBackend(url, constants.HTTP_GET) return privateMethods.callBackend(url, constants["HTTP_GET"]);
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -467,15 +211,19 @@ var userModule = function () {
*/ */
publicMethods.getRoles = function () { publicMethods.getRoles = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require('/app/modules/utility.js')["utility"]; var utility = require("/app/modules/utility.js")["utility"];
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"]; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles"; var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles";
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -488,18 +236,24 @@ var userModule = function () {
*/ */
/** /**
* Get User Roles from user store (Internal roles not included). * Get User Roles from user store (Internal roles not included).
* @returns {object} a response object with status and content on success.
*/ */
publicMethods.getRolesByUserStore = function (userStore) { publicMethods.getRolesByUserStore = function () {
var ROLE_LIMIT = devicemgtProps["pageSize"];
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require('/app/modules/utility.js')["utility"]; var utility = require("/app/modules/utility.js")["utility"];
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"]; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + encodeURIComponent(userStore); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles?limit=" + ROLE_LIMIT;
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
@ -510,40 +264,45 @@ var userModule = function () {
/** /**
* Get Platforms. * Get Platforms.
*/ */
//TODO Move this piece of logic out of user.js to somewhere else appropriate.
publicMethods.getPlatforms = function () { publicMethods.getPlatforms = function () {
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require('/app/modules/utility.js')["utility"]; var utility = require("/app/modules/utility.js")["utility"];
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"]; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types"; var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/admin/device-types";
return privateMethods.callBackend(url, constants.HTTP_GET); var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
} catch (e) { } catch (e) {
throw e; throw e;
} finally { } finally {
utility.endTenantFlow(); utility.endTenantFlow();
} }
}; };
/*
@Updated
*/
/** /**
* Get role * Get role
*/ */
publicMethods.getRole = function (roleName) { publicMethods.getRole = function (roleName) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]); var carbonUser = session.get(constants["USER_SESSION_KEY"]);
var utility = require('/app/modules/utility.js')["utility"]; var utility = require("/app/modules/utility.js")["utility"];
if (!carbonUser) { if (!carbonUser) {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"]; throw constants["ERRORS"]["USER_NOT_FOUND"];
} }
try { try {
utility.startTenantFlow(carbonUser); utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/role?rolename=" + encodeURIComponent(roleName); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
var response = privateMethods.callBackend(url, constants.HTTP_GET); "/roles/" + encodeURIComponent(roleName);
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
response.content = parse(response.content);
return response; return response;
} catch (e) { } catch (e) {
throw e; throw e;
@ -687,30 +446,6 @@ var userModule = function () {
return permissions; return permissions;
}; };
/**
* Add new role with permissions.
*
* @param roleName Name of the role
* @param users List of users to assign the role
* @param permissions List of permissions
*/
publicMethods.addRole = function (roleName, users, permissions) {
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.roleExists(roleName)) {
userManager.addRole(roleName, users, permissions);
} else {
log.info("Role exist with name: " + roleName);
}
} catch (e) {
throw e;
}
};
publicMethods.addPermissions = function (permissionList, path, init) { publicMethods.addPermissions = function (permissionList, path, init) {
var registry, carbon = require("carbon"); var registry, carbon = require("carbon");
var carbonServer = application.get("carbonServer"); var carbonServer = application.get("carbonServer");
@ -776,24 +511,29 @@ var userModule = function () {
* retrieve secondary user stores. * retrieve secondary user stores.
* This needs Authentication since the method access admin services. * This needs Authentication since the method access admin services.
* *
* @returns {string array} Array of secondary user stores. * @returns Array of secondary user stores.
*/ */
publicMethods.getSecondaryUserStores = function () { publicMethods.getSecondaryUserStores = function () {
var returnVal = []; var returnVal = [];
var endpoint = devicemgtProps.adminService + constants.USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT; var endpoint = devicemgtProps["adminService"] + constants["USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT"];
var wsPayload = "<xsd:getSecondaryRealmConfigurations xmlns:xsd='http://org.apache.axis2/xsd'/>"; var wsPayload = "<xsd:getSecondaryRealmConfigurations xmlns:xsd='http://org.apache.axis2/xsd'/>";
serviceInvokers.WS.soapRequest( serviceInvokers.WS.soapRequest(
"urn:getSecondaryRealmConfigurations", endpoint, wsPayload, function (wsResponse) { "urn:getSecondaryRealmConfigurations",
wsPayload,
endpoint,
function (wsResponse) {
var domainIDs = stringify(wsResponse.*::['return']. *::domainId.text()); var domainIDs = stringify(wsResponse.*::['return']. *::domainId.text());
if (domainIDs != "\"\"") { if (domainIDs != "\"\"") {
var regExpForSearch = new RegExp(constants.USER_STORES_NOISY_CHAR, "g"); var regExpForSearch = new RegExp(constants["USER_STORES_NOISY_CHAR"], "g");
domainIDs = domainIDs.replace(regExpForSearch, ""); domainIDs = domainIDs.replace(regExpForSearch, "");
returnVal = domainIDs.split(constants.USER_STORES_SPLITTING_CHAR); returnVal = domainIDs.split(constants["USER_STORES_SPLITTING_CHAR"]);
} }
}, function (e) { }, function (e) {
log.error("Error retrieving secondary user stores", e); log.error("Error retrieving secondary user stores", e);
}, constants.SOAP_VERSION); },
constants["SOAP_VERSION"]);
return returnVal; return returnVal;
}; };
return publicMethods; return publicMethods;
}(); }();

@ -15,7 +15,7 @@
specific language governing permissions and limitations specific language governing permissions and limitations
under the License. under the License.
}} }}
{{unit "cdmf.unit.ui.title" pageTitle="User Management"}} {{unit "cdmf.unit.ui.title" pageTitle="User Management | Add User"}}
{{#zone "breadcrumbs"}} {{#zone "breadcrumbs"}}
<li> <li>
@ -50,8 +50,8 @@
<div id="user-create-error-msg" class="alert alert-danger hidden" role="alert"> <div id="user-create-error-msg" class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span> <i class="icon fw fw-error"></i><span></span>
</div> </div>
<label class="wr-input-label" title="List of available secondary user stores"> <label class="wr-input-label" title="Select the domain of the user store from the drop-down given below. The domain of the default user store is PRIMARY">
User Stores User Store Domain
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span> <span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label> </label>
<div class="wr-input-control"> <div class="wr-input-control">
@ -96,12 +96,10 @@
<div id="emailField" class=" form-group wr-input-control"> <div id="emailField" class=" form-group wr-input-control">
<input type="email" id="emailAddress" class="form-control"/> <input type="email" id="emailAddress" class="form-control"/>
<span class="glyphicon glyphicon-remove form-control-feedback hidden emailError"></span> <span class="glyphicon glyphicon-remove form-control-feedback hidden emailError"></span>
<label class=" hidden error email-required" for="summary">This field is <label class=" hidden error email-required" for="summary">This field is required.</label>
required.</label>
<label class=" hidden error email-invalid" for="summary">Invalid Email Address.</label> <label class=" hidden error email-invalid" for="summary">Invalid Email Address.</label>
</div> </div>
<label class="wr-input-label" <label class="wr-input-label" title="Optional field that can have 0-to-many roles for the user">
title="Optional field that can have 0-to-many roles for the user">
User Roles User Roles
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span> <span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label> </label>
@ -123,7 +121,6 @@
<p class="page-sub-title">User was added successfully.</p> <p class="page-sub-title">User was added successfully.</p>
<br> <br>
An invitation mail will be sent to this user to initiate device enrollment. An invitation mail will be sent to this user to initiate device enrollment.
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-body"> <div class="panel-body">
<div class="qr-code col-lg-5 col-md-6 col-centered"></div> <div class="qr-code col-lg-5 col-md-6 col-centered"></div>
@ -132,8 +129,7 @@
<br>Please click <b>"Add Another User"</b>, if you wish to add another user or click <br>Please click <b>"Add Another User"</b>, if you wish to add another user or click
<b>"View User List"</b> to complete the process and go back to the user list. <b>"View User List"</b> to complete the process and go back to the user list.
<hr/> <hr/>
<button class="wr-btn" onclick="window.location.href='{{@app.context}}/users'">View User List <button class="wr-btn" onclick="window.location.href='{{@app.context}}/users'">View User List</button>
</button>
<a href="{{@app.context}}/user/add" class="cu-btn-inner"> <a href="{{@app.context}}/user/add" class="cu-btn-inner">
<span class="fw-stack"> <span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i> <i class="fw fw-ring fw-stack-2x"></i>

@ -23,20 +23,24 @@
* @returns {*} A context object that returns the dynamic state of this page to be presented * @returns {*} A context object that returns the dynamic state of this page to be presented
*/ */
function onRequest(context) { function onRequest(context) {
//var log = new Log("/app/pages/cdmf.page.user.create server-side js");
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/user.js")["userModule"];
var response = userModule.getRolesByUserStore("PRIMARY"); var devicemgtProps = require("/app/conf/devicemgt-props.js").config();
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var page = {}; var page = {};
page["charLimit"] = devicemgtProps.usernameLength; var response = userModule.getRolesByUserStore();
if (response["status"] == "success") { if (response["status"] == "success") {
page["roles"] = response["content"]; page["roles"] = response["content"];
} }
page["usernameJSRegEx"] = devicemgtProps.userValidationConfig.usernameJSRegEx; page["charLimit"] = devicemgtProps["usernameLength"];
page["usernameHelpMsg"] = devicemgtProps.userValidationConfig.usernameHelpMsg; page["usernameJSRegEx"] = devicemgtProps["userValidationConfig"]["usernameJSRegEx"];
page["usernameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.usernameRegExViolationErrorMsg; page["usernameHelpMsg"] = devicemgtProps["userValidationConfig"]["usernameHelpMsg"];
page["firstnameJSRegEx"] = devicemgtProps.userValidationConfig.firstnameJSRegEx; page["usernameRegExViolationErrorMsg"] = devicemgtProps["userValidationConfig"]["usernameRegExViolationErrorMsg"];
page["firstnameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.firstnameRegExViolationErrorMsg; page["firstnameJSRegEx"] = devicemgtProps["userValidationConfig"]["firstnameJSRegEx"];
page["lastnameJSRegEx"] = devicemgtProps.userValidationConfig.lastnameJSRegEx; page["firstnameRegExViolationErrorMsg"] = devicemgtProps["userValidationConfig"]["firstnameRegExViolationErrorMsg"];
page["lastnameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.lastnameRegExViolationErrorMsg; page["lastnameJSRegEx"] = devicemgtProps["userValidationConfig"]["lastnameJSRegEx"];
page["lastnameRegExViolationErrorMsg"] = devicemgtProps["userValidationConfig"]["lastnameRegExViolationErrorMsg"];
return page; return page;
} }

@ -1,5 +1,5 @@
{ {
"version": "1.0.0", "version": "1.0.0",
"uri": "/user/add", "uri": "/user/add",
"layout": "cdmf.layout.default" "layout": "cdmf.layout.default"
} }

@ -6,12 +6,12 @@
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* KIND, either express or implied. See the License for the * either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
@ -30,6 +30,7 @@ function inputIsValid(regExp, inputString) {
var validateInline = {}; var validateInline = {};
var clearInline = {}; var clearInline = {};
var deviceMgtAPIsBasePath = "/api/device-mgt/v1.0";
var enableInlineError = function (inputField, errorMsg, errorSign) { var enableInlineError = function (inputField, errorMsg, errorSign) {
var fieldIdentifier = "#" + inputField; var fieldIdentifier = "#" + inputField;
@ -160,37 +161,41 @@ function emailIsValid(email) {
return regExp.test(email); return regExp.test(email);
} }
$("#userStore") $("#userStore").change(
.change(function () { function () {
var str = ""; var str = "";
$("select option:selected").each(function () { $("select option:selected").each(function () {
str += $(this).text() + " "; str += $(this).text() + " ";
}); });
var addUserAPI = "/devicemgt_admin/roles/" + str; var getRolesAPI = deviceMgtAPIsBasePath + "/roles/"+ str;
invokerUtil.get( invokerUtil.get(
addUserAPI, getRolesAPI,
function (data) { function (data) {
data = JSON.parse(data); data = JSON.parse(data);
if (data.errorMessage) { if (data.errorMessage) {
$(errorMsg).text("Selected user store prompted an error : " + data.errorMessage); $(errorMsg).text("Selected user store prompted an error : " + data.errorMessage);
$(errorMsgWrapper).removeClass("hidden"); $(errorMsgWrapper).removeClass("hidden");
} else if (data["statusCode"] == 200) { } else if (data["statusCode"] == 200) {
$("#roles").empty(); $("#roles").empty();
for (var i = 0; i < data.responseContent.length; i++) { for (var i = 0; i < data.responseContent.length; i++) {
var newOption = $('<option value="' + data.responseContent[i] + '">' + data.responseContent[i] + '</option>'); var newOption = $('<option value="' + data.responseContent[i] + '">' + data.responseContent[i] + '</option>');
$('#roles').append(newOption); $('#roles').append(newOption);
}
}
} }
); }
}).change(); },
function (jqXHR) {
}
);
}
).change();
$(document).ready(function () { $(document).ready(function () {
$("#emailValidationText").hide(); $("#emailValidationText").hide();
$("select.select2[multiple=multiple]").select2({ $("select.select2[multiple=multiple]").select2({
tags: false tags: false
}); });
/** /**
* Following click function would execute * Following click function would execute
@ -202,7 +207,7 @@ $(document).ready(function () {
var usernameInput = $("input#username"); var usernameInput = $("input#username");
var firstnameInput = $("input#firstname"); var firstnameInput = $("input#firstname");
var lastnameInput = $("input#lastname"); var lastnameInput = $("input#lastname");
var charLimit = parseInt($("input#username").attr("limit")); //var charLimit = parseInt($("input#username").attr("limit"));
var domain = $("#userStore").val(); var domain = $("#userStore").val();
var username = usernameInput.val().trim(); var username = usernameInput.val().trim();
var firstname = firstnameInput.val(); var firstname = firstnameInput.val();
@ -244,44 +249,36 @@ $(document).ready(function () {
addUserFormData.emailAddress = emailAddress; addUserFormData.emailAddress = emailAddress;
addUserFormData.roles = roles; addUserFormData.roles = roles;
var addUserAPI = "/devicemgt_admin/users"; var addUserAPI = deviceMgtAPIsBasePath + "/users";
invokerUtil.post( invokerUtil.post(
addUserAPI, addUserAPI,
addUserFormData, addUserFormData,
function (data) { function (data, textStatus, jqXHR) {
data = JSON.parse(data); if (jqXHR.status == 201) {
if (data.errorMessage) { // Clearing user input fields.
$(errorMsg).text("Selected user store prompted an error : " + data.errorMessage); $("input#username").val("");
$(errorMsgWrapper).removeClass("hidden"); $("input#firstname").val("");
} else if (data["statusCode"] == 201) { $("input#lastname").val("");
// Clearing user input fields. $("input#email").val("");
$("input#username").val(""); $("select#roles").select2("val", "");
$("input#firstname").val(""); // Refreshing with success message
$("input#lastname").val(""); $("#user-create-form").addClass("hidden");
$("input#email").val(""); $("#user-created-msg").removeClass("hidden");
$("select#roles").select2("val", ""); generateQRCode("#user-created-msg .qr-code");
// Refreshing with success message
$("#user-create-form").addClass("hidden"); }
$("#user-created-msg").removeClass("hidden"); }, function (data) {
} else if (data["statusCode"] == 409) { var payload = JSON.parse(data.responseText);
$(errorMsg).text(data["messageFromServer"]); if (data.status == 409) {
$(errorMsgWrapper).removeClass("hidden"); $(errorMsg).text("User : " + username + " already exists. Pick another username.");
} else if (data["statusCode"] == 500) { } else if (data.status == 500) {
$(errorMsg).text("An unexpected error occurred at backend server. Please try again later."); $(errorMsg).text("An unexpected error occurred at backend server. Please try again later.");
$(errorMsgWrapper).removeClass("hidden"); } else {
} $(errorMsg).text(payload.message);
}, function (data) {
data = JSON.parse(data.responseText);
if (data["statusCode"] == 409) {
$(errorMsg).text("User : " + username + " already exists. Pick another username.");
} else if (data["statusCode"] == 500) {
$(errorMsg).text("An unexpected error occurred at backend server. Please try again later.");
} else {
$(errorMsg).text(data.errorMessage);
}
$(errorMsgWrapper).removeClass("hidden");
} }
$(errorMsgWrapper).removeClass("hidden");
}
); );
} }
}); });

@ -1,21 +1,23 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* KIND, either express or implied. See the License for the * either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
var deviceMgtAPIsBasePath = "/api/device-mgt/v1.0";
/** /**
* Checks if provided input is valid against RegEx input. * Checks if provided input is valid against RegEx input.
* *
@ -35,10 +37,10 @@ function inputIsValid(regExp, inputString) {
$(function () { $(function () {
var sortableElem = '.wr-sortable'; var sortableElem = '.wr-sortable';
$(sortableElem).sortable({ $(sortableElem).sortable({
beforeStop: function () { beforeStop: function () {
var sortedIDs = $(this).sortable('toArray'); $(this).sortable('toArray');
} }
}); });
$(sortableElem).disableSelection(); $(sortableElem).disableSelection();
}); });
@ -46,11 +48,9 @@ var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container"; var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content"; var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body"; var body = "body";
var isInit = true; //var isInit = true;
$(".icon .text").res_text(0.2); $(".icon .text").res_text(0.2);
var resetPasswordServiceURL = "/devicemgt_admin/users/reset-password";
/* /*
* set popup maximum height function. * set popup maximum height function.
*/ */
@ -80,11 +80,9 @@ function hidePopup() {
*/ */
function getSelectedUsernames() { function getSelectedUsernames() {
var usernameList = []; var usernameList = [];
var userList = $("#user-grid").find('> tbody > tr'); var userList = $("#user-grid").find('tr.DTTT_selected');
userList.each(function () { userList.each(function () {
if ($(this).hasClass('DTTT_selected')) { usernameList.push($(this).data('username'));
usernameList.push($(this).attr('data-username'));
}
}); });
return usernameList; return usernameList;
} }
@ -96,7 +94,7 @@ function getSelectedUsernames() {
*/ */
$("a.invite-user-link").click(function () { $("a.invite-user-link").click(function () {
var usernameList = getSelectedUsernames(); var usernameList = getSelectedUsernames();
var inviteUserAPI = "/devicemgt_admin/users/email-invitation"; var inviteUserAPI = deviceMgtAPIsBasePath + "/users/send-invitation";
if (usernameList.length == 0) { if (usernameList.length == 0) {
$(modalPopupContent).html($("#errorUsers").html()); $(modalPopupContent).html($("#errorUsers").html());
@ -108,20 +106,25 @@ $("a.invite-user-link").click(function () {
$("a#invite-user-yes-link").click(function () { $("a#invite-user-yes-link").click(function () {
invokerUtil.post( invokerUtil.post(
inviteUserAPI, inviteUserAPI,
usernameList, usernameList,
function () { // The success callback
function (data, textStatus, jqXHR) {
if (jqXHR.status == 200) {
$(modalPopupContent).html($('#invite-user-success-content').html()); $(modalPopupContent).html($('#invite-user-success-content').html());
$("a#invite-user-success-link").click(function () { $("a#invite-user-success-link").click(function () {
hidePopup(); hidePopup();
}); });
},
function () {
$(modalPopupContent).html($('#invite-user-error-content').html());
$("a#invite-user-error-link").click(function () {
hidePopup();
});
} }
},
// The error callback
function (jqXHR) {
console.log("error in invite-user API, status code: " + jqXHR.status);
$(modalPopupContent).html($('#invite-user-error-content').html());
$("a#invite-user-error-link").click(function () {
hidePopup();
});
}
); );
}); });
@ -135,34 +138,33 @@ $("a.invite-user-link").click(function () {
* when a user clicks on "Remove" link * when a user clicks on "Remove" link
* on User Listing page in WSO2 Devicemgt Console. * on User Listing page in WSO2 Devicemgt Console.
*/ */
function removeUser(uname, uid) { function removeUser(username) {
var username = uname; var removeUserAPI = deviceMgtAPIsBasePath + "/users/" + username;
var userid = uid;
var removeUserAPI = "/devicemgt_admin/users?username=" + username;
$(modalPopupContent).html($('#remove-user-modal-content').html()); $(modalPopupContent).html($('#remove-user-modal-content').html());
showPopup(); showPopup();
$("a#remove-user-yes-link").click(function () { $("a#remove-user-yes-link").click(function () {
invokerUtil.delete( invokerUtil.delete(
removeUserAPI, removeUserAPI,
function () { // success callback
$("#" + userid).remove(); function (data, textStatus, jqXHR) {
// get new user-list-count if (jqXHR.status == 200) {
var newUserListCount = $(".user-list > span").length;
// update user-listing-status-msg with new user-count
$("#user-listing-status-msg").text("Total number of Users found : " + newUserListCount);
// update modal-content with success message // update modal-content with success message
$(modalPopupContent).html($('#remove-user-success-content').html()); $(modalPopupContent).html($('#remove-user-success-content').html());
$("a#remove-user-success-link").click(function () { $("a#remove-user-success-link").click(function () {
hidePopup(); hidePopup();
}); location.reload();
},
function () {
$(modalPopupContent).html($('#remove-user-error-content').html());
$("a#remove-user-error-link").click(function () {
hidePopup();
}); });
} }
},
// error callback
function (jqXHR) {
console.log("error in remove-user API, status code: " + jqXHR.status);
$(modalPopupContent).html($('#remove-user-error-content').html());
$("a#remove-user-error-link").click(function () {
hidePopup();
});
}
); );
}); });
@ -202,29 +204,30 @@ function resetPassword(uname) {
$(errorMsgWrapper).removeClass("hidden"); $(errorMsgWrapper).removeClass("hidden");
} else { } else {
var resetPasswordFormData = {}; var resetPasswordFormData = {};
resetPasswordFormData.username = user; //resetPasswordFormData.username = user;
resetPasswordFormData.newPassword = window.btoa(unescape(encodeURIComponent(confirmedPassword))); resetPasswordFormData.newPassword = unescape(confirmedPassword);
var resetPasswordServiceURL = deviceMgtAPIsBasePath + "/admin/users/"+ user +"/credentials";
invokerUtil.post( invokerUtil.post(
resetPasswordServiceURL, resetPasswordServiceURL,
resetPasswordFormData, resetPasswordFormData,
function (data) { // The success callback // The success callback
data = JSON.parse(data); function (data, textStatus, jqXHR) {
if (data.statusCode == 201) { if (jqXHR.status == 200) {
$(modalPopupContent).html($('#reset-password-success-content').html()); $(modalPopupContent).html($('#reset-password-success-content').html());
$("a#reset-password-success-link").click(function () { $("a#reset-password-success-link").click(function () {
hidePopup(); hidePopup();
}); });
}
}, function (data) { // The error callback
if (data.statusCode == 400) {
$(errorMsg).text("Old password does not match with the provided value.");
$(errorMsgWrapper).removeClass("hidden");
} else {
$(errorMsg).text("An unexpected error occurred. Please try again later.");
$(errorMsgWrapper).removeClass("hidden");
}
} }
},
// The error callback
function (jqXHR) {
console.log("error in reset-password API, status code: " + jqXHR.status);
var payload = JSON.parse(jqXHR.responseText);
$(errorMsg).text(payload.message);
$(errorMsgWrapper).removeClass("hidden");
}
); );
} }
}); });
@ -250,7 +253,7 @@ $("#search-btn").click(function () {
* when a user clicks on the list item * when a user clicks on the list item
* initial mode and with out select mode. * initial mode and with out select mode.
*/ */
function InitiateViewOption() { function initiateViewOption() {
if ($("#can-view").val()) { if ($("#can-view").val()) {
$(location).attr('href', $(this).data("url")); $(location).attr('href', $(this).data("url"));
} else { } else {
@ -259,74 +262,112 @@ function InitiateViewOption() {
} }
} }
function loadUsers(searchParam) { function loadUsers() {
$("#loading-content").show(); var loadingContentIcon = "#loading-content";
var userListing = $("#user-listing"); $(loadingContentIcon).show();
var userListingSrc = userListing.attr("src");
$.template("user-listing", userListingSrc, function (template) { var dataFilter = function (data) {
var serviceURL = "/devicemgt_admin/users"; data = JSON.parse(data);
if (searchParam) {
serviceURL = serviceURL + "/view-users?username=" + searchParam; var objects = [];
}
var successCallback = function (data) { $(data.users).each(function (index) {
if (!data) { objects.push({
$('#ast-container').addClass('hidden'); username: data.users[index].username,
$('#user-listing-status-msg').text('No users are available to be displayed.'); firstname: data.users[index].firstname ? data.users[index].firstname: '' ,
return; lastname: data.users[index].lastname ? data.users[index].lastname : '',
emailAddress : data.users[index].emailAddress ? data.users[index].emailAddress: '',
DT_RowId : "user-" + data.users[index].username})
});
var json = {
"recordsTotal": data.count,
"recordsFiltered": data.count,
"data": objects
};
return JSON.stringify(json);
};
var fnCreatedRow = function(nRow, aData, iDataIndex) {
console.log(JSON.stringify(aData));
$(nRow).attr('data-type', 'selectable');
$(nRow).attr('data-username', aData["username"]);
};
var columns = [
{
class: "remove-padding icon-only content-fill",
data: null,
defaultContent:
'<div class="thumbnail icon">' +
'<i class="square-element text fw fw-user" style="font-size: 30px;"></i>' +
'</div>'
},
{
class: "fade-edge",
data: null,
render: function (data, type, row, meta) {
return '<h4>' + data.firstname + ' ' + data.lastname + '</h4>';
} }
var canRemove = $("#can-remove").val(); },
var canEdit = $("#can-edit").val(); {
var canResetPassword = $("#can-reset-password").val(); class: "fade-edge remove-padding-top",
data = JSON.parse(data); data: null,
data = data.responseContent; render: function (data, type, row, meta) {
var viewModel = {}; return '<i class="fw-user"></i> ' + data.username;
viewModel.users = data;
for (var i = 0; i < viewModel.users.length; i++) {
viewModel.users[i].userid = viewModel.users[i].username.replace(/[^\w\s]/gi, '');
if (canRemove) {
viewModel.users[i].canRemove = true;
}
if (canEdit) {
viewModel.users[i].canEdit = true;
}
if (canResetPassword) {
viewModel.users[i].canResetPassword = true;
}
viewModel.users[i].adminUser = $("#user-table").data("user");
} }
if (data.length > 0) { },
$('#ast-container').removeClass('hidden'); {
$('#user-listing-status-msg').text(""); class: "fade-edge remove-padding-top",
var content = template(viewModel); data: null,
$("#ast-container").html(content); render: function (data, type, row, meta) {
} else { return '<a href="mailto:' + data.emailAddress + ' " class="wr-list-email"><i class="fw-mail"></i> ' +
$('#ast-container').addClass('hidden'); data.emailAddress + ' </a>';
$('#user-listing-status-msg').text('No users are available to be displayed.');
} }
$("#loading-content").hide(); },
if (isInit) { {
$('#user-grid').datatables_extended(); class: "text-right content-fill text-left-on-grid-view no-wrap",
isInit = false; data: null,
render: function (data, type, row, meta) {
return '<a href="/emm/users/edit-user?username=' + data.username + '" data-username="' + data.username +
'" data-click-event="edit-form" class="btn padding-reduce-on-grid-view edit-user-link"> ' +
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' +
'<i class="fw fw-edit fw-stack-1x"></i>' +
' </span> <span class="hidden-xs hidden-on-grid-view">Edit</span> </a>' +
'<a href="#" data-username="' + data.username + '" data-user-id=' + data.username +
' data-click-event="remove-form" onclick="javascript:removeUser(\'' + data.username + '\', \'' +
data.username + '\')" class="btn padding-reduce-on-grid-view remove-user-link">' +
'<span class="fw-stack"> <i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-delete fw-stack-1x">' +
'</i> </span> <span class="hidden-xs hidden-on-grid-view">Remove</span> </a>' +
'<a href="#" data-username="' + data.username + '" data-user-id="' + data.username +
'" data-click-event="edit-form" onclick="javascript:resetPassword(\'' + data.username +
'\')" class="btn padding-reduce-on-grid-view remove-user-link"> <span class="fw-stack">' +
'<i class="fw fw-ring fw-stack-2x">' +
'</i> <i class="fw fw-key fw-stack-1x"></i> <span class="fw-stack fw-move-right fw-move-bottom"> ' +
'<i class="fw fw-circle fw-stack-2x fw-stroke fw-inverse"><' +
'/i> <i class="fw fw-circle fw-stack-2x"></i> <i class="fw fw-refresh fw-stack-1x fw-inverse">' +
'</i> </span> </span> <span class="hidden-xs hidden-on-grid-view">Reset</span> </a>'
} }
$(".icon .text").res_text(0.2); }
};
invokerUtil.get(serviceURL, ];
successCallback,
function (message) { $("#user-grid").datatables_extended_serverside_paging(null, '/api/device-mgt/v1.0/users', dataFilter, columns, fnCreatedRow, null);
$('#ast-container').addClass('hidden');
$('#user-listing-status-msg').text('Invalid search query. Try again with a valid search query'); $("#loading-content").hide();
}
);
});
} }
$(document).ready(function () { $(document).ready(function () {
loadUsers(); loadUsers();
$(".viewEnabledIcon").click(function () { $(".viewEnabledIcon").click(function () {
InitiateViewOption(); initiateViewOption();
}); });
if (!$("#can-invite").val()) { if (!$("#can-invite").val()) {
$("#invite-user-button").remove(); $("#invite-user-button").remove();
} }
}); });

@ -52,6 +52,11 @@
<span class="fw-stack"> <span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i> <i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-key fw-stack-1x"></i> <i class="fw fw-key fw-stack-1x"></i>
<span class="fw-stack fw-move-right fw-move-bottom">
<i class="fw fw-circle fw-stack-2x fw-stroke fw-inverse"></i>
<i class="fw fw-circle fw-stack-2x"></i>
<i class="fw fw-refresh fw-stack-1x fw-inverse"></i>
</span>
</span> </span>
<span class="hidden-xs hidden-on-grid-view">Reset</span> <span class="hidden-xs hidden-on-grid-view">Reset</span>
</a> </a>

@ -298,15 +298,13 @@
Enter new password Enter new password
<br><br> <br><br>
<div> <div>
<input type="password" class="form-control modal-input operationDataKeys" id="new-password" <input type="password" class="form-control modal-input operationDataKeys" id="new-password" data-key="message"/>
data-key="message"/>
</div> </div>
<br> <br>
Retype new password Retype new password
<br><br> <br><br>
<div> <div>
<input type="password" class="form-control modal-input operationDataKeys" <input type="password" class="form-control modal-input operationDataKeys" id="confirmed-password" data-key="message"/>
id="confirmed-password" data-key="message"/>
</div> </div>
<br> <br>
</h4> </h4>
@ -338,6 +336,7 @@
</div> </div>
</div> </div>
</div> </div>
{{/zone}} {{/zone}}
{{#zone "common-navigation"}} {{#zone "common-navigation"}}
<!--Later add the navigation menu from here--> <!--Later add the navigation menu from here-->

@ -26,13 +26,13 @@ function onRequest(context) {
return options.fn(this); return options.fn(this);
} }
}); });
var page = {}; var page = {};
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/user.js")["userModule"];
var deviceMgtProps = require("/app/conf/devicemgt-props.js").config(); var deviceMgtProps = require("/app/conf/devicemgt-props.js").config();
page["adminUser"] = deviceMgtProps["adminUser"];
page["permissions"] = userModule.getUIPermissions(); page["permissions"] = userModule.getUIPermissions();
if (userModule.isAuthorized("/permission/admin/device-mgt/users/delete")) {
page["removePermitted"] = true;
}
if (userModule.isAuthorized("/permission/admin/device-mgt/users/remove")) { if (userModule.isAuthorized("/permission/admin/device-mgt/users/remove")) {
page["removePermitted"] = true; page["removePermitted"] = true;
@ -51,6 +51,5 @@ function onRequest(context) {
page["resetPasswordPermitted"] = true; page["resetPasswordPermitted"] = true;
} }
page["adminUser"] = deviceMgtProps.adminUser;
return page; return page;
} }

@ -19,9 +19,10 @@
{{~css "css/dataTables.bootstrap.css"}} {{~css "css/dataTables.bootstrap.css"}}
{{~css "css/dataTables.responsive.css"}} {{~css "css/dataTables.responsive.css"}}
{{/zone}} {{/zone}}
{{~#zone "bottomJs"}} {{#zone "bottomJs"}}
{{~js "js/jquery.dataTables.min.js"}} {{~js "js/jquery.dataTables.min.js"}}
{{~js "js/dataTables.bootstrap.js"}} {{~js "js/dataTables.bootstrap.js"}}
{{~js "js/dataTables.responsive.min.js"}} {{~js "js/dataTables.responsive.min.js"}}
{{~js "js/dataTables.extended.js"}} {{~js "js/dataTables.extended.js"}}
{{~js "js/dataTables.extended.serversidepaging.js"}}
{{/zone}} {{/zone}}

@ -0,0 +1,281 @@
/*
* 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.
*/
/*
* =========================================================
* data-tables extended function (Server-side Pagination)
* =========================================================
*/
/**
* @namespace $
* The $ is just a function.
* It is actually an alias for the function called jQuery.
* For ex: $(this) means jQuery(this) and S.fn.x means jQuery.fn.x
*/
$.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter,
columns, fnCreatedRow, fnDrawCallback) {
var elem = $(this);
// EMM related function
if (initiateViewOption) {
$(".viewEnabledIcon").bind("click", initiateViewOption);
}
//--- End of EMM related codes
$(elem).DataTable(
$.extend({},{
serverSide: true,
bSortCellsTop: true,
ajax : {
url: "/emm/api/data-tables/invoker",
data : function (params) {
var filter = "";
var i;
for (i = 0; i < params.columns.length; i++) {
// console.log(i);
filter += "&" + params.columns[i].data + "=" + params.columns[i].search.value;
}
// console.log(filter);
params.offset = params.start;
params.limit = params.length;
params.filter = filter;
params.url = url;
},
dataFilter: dataFilter
},
columns: columns,
responsive: false,
autoWidth: false,
dom:'<"dataTablesTop"' +
'f' +
'<"dataTables_toolbar">' +
'>' +
'rt' +
'<"dataTablesBottom"' +
'lip' +
'>',
language: {
searchPlaceholder: 'Search by Role name',
search: ''
},
fnCreatedRow: fnCreatedRow,
"fnDrawCallback": fnDrawCallback,
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var filterColumn = $('.filter-row th', elem);
/**
* Create & add select/text filters to each column
*/
if (filterColumn.eq(column.index()).hasClass('select-filter')) {
var select = $('<select class="form-control"><option value="">All</option></select>')
.appendTo(filterColumn.eq(column.index()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
//.search(val ? '^' + val + '$' : '', true, false)
.search(val ? val : '', true, false)
.draw();
if (filterColumn.eq(column.index()).hasClass('data-platform')) {
if (val == null || val == undefined || val == "") {
$("#operation-bar").hide();
$("#operation-guide").show();
} else {
$("#operation-guide").hide();
$("#operation-bar").show();
loadOperationBar(val);
}
}
});
$(column).each(function () {
if ($(column.nodes()).attr('data-search')) {
var titles = [];
column.nodes().unique().sort().each(function (d, j) {
var title = $(d).attr('data-display');
if ($.inArray(title, titles) < 0) {
titles.push(title);
if (title !== undefined) {
select.append('<option value="' + title + '">' + title + '</option>')
}
}
});
} else {
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
}
});
} else if (filterColumn.eq(column.index()).hasClass('text-filter')) {
var title = filterColumn.eq(column.index()).attr('data-for');
$(filterColumn.eq(column.index()).empty()).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');
filterColumn.eq(column.index()).find('input').on('keyup change', function () {
column.search($(this).val()).draw();
if ($('.dataTables_empty').length > 0) {
$('.bulk-action-row').addClass("hidden");
} else {
$('.bulk-action-row').removeClass("hidden");
}
});
}
});
/**
* search input default styles override
*/
var search_input = $(this).closest('.dataTables_wrapper').find('div[id$=_filter] input');
search_input.before('<i class="fw fw-search search-icon"></i>').removeClass('input-sm');
/**
* create sorting dropdown menu for list table advance operations
*/
var dropdownmenu = $('<ul class="dropdown-menu arrow arrow-top-right dark sort-list add-margin-top-2x"><li class="dropdown-header">Sort by</li></ul>');
$('.sort-row th', elem).each(function () {
if (!$(this).hasClass('no-sort')) {
dropdownmenu.append('<li><a href="#' + $(this).html() + '" data-column="' + $(this).index() + '">' + $(this).html() + '</a></li>');
}
});
/**
* append advance operations to list table toolbar
*/
$('.dataTable.list-table').closest('.dataTables_wrapper').find('.dataTablesTop .dataTables_toolbar').html('' +
'<ul class="nav nav-pills navbar-right remove-margin" role="tablist">' +
'<li><button data-click-event="toggle-selectable" class="btn btn-default btn-primary select-enable-btn">Select</li>' +
'<li><button data-click-event="toggle-selected" id="dt-select-all" class="btn btn-default btn-primary disabled">Select All</li>' +
'<li><button data-click-event="toggle-list-view" data-view="grid" class="btn btn-default"><i class="fw fw-grid"></i></button></li>' +
'<li><button data-click-event="toggle-list-view" data-view="list" class="btn btn-default"><i class="fw fw-list"></i></button></li>' +
'<li><button class="btn btn-default" data-toggle="dropdown"><i class="fw fw-sort"></i></button>' + dropdownmenu[0].outerHTML + '</li>' +
'</ul>'
);
/**
* sorting dropdown menu select function
*/
$('.dataTables_wrapper .sort-list li a').click(function () {
$(this).closest('li').siblings('li').find('a').removeClass('sorting_asc').removeClass('sorting_desc');
var thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
if (!($(this).hasClass('sorting_asc')) && !($(this).hasClass('sorting_desc'))) {
$(this).addClass('sorting_asc');
thisTable.fnSort([[$(this).attr('data-column'), 'asc']]);
}
else if ($(this).hasClass('sorting_asc')) {
$(this).switchClass('sorting_asc', 'sorting_desc');
thisTable.fnSort([[$(this).attr('data-column'), 'desc']]);
}
else if ($(this).hasClass('sorting_desc')) {
$(this).switchClass('sorting_desc', 'sorting_asc');
thisTable.fnSort([[$(this).attr('data-column'), 'asc']]);
}
});
var rowSelectedClass = 'DTTT_selected selected';
/**
* Enable/Disable selection on rows
*/
$('.dataTables_wrapper [data-click-event=toggle-selectable]').click(function () {
var button = this,
thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
if ($(button).html() == 'Select') {
thisTable.addClass("table-selectable");
$(button).addClass("active").html('Cancel');
$(button).parent().next().children("button").removeClass("disabled");
// EMM related code
$(".viewEnabledIcon").unbind("click");
//--- End of EMM related codes
} else if ($(button).html() == 'Cancel') {
thisTable.removeClass("table-selectable");
$(button).addClass("active").html('Select');
$(button).parent().next().children().addClass("disabled");
// EMM related function
$(".viewEnabledIcon").bind("click", initiateViewOption);
//--- End of EMM related codes
}
});
/**
* select/deselect all rows function
*/
$('.dataTables_wrapper [data-click-event=toggle-selected]').click(function () {
var button = this,
thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
if (!$(button).hasClass('disabled')) {
if ($(button).html() == 'Select All') {
thisTable.api().rows().every(function () {
$(this.node()).addClass(rowSelectedClass);
$(button).html('Deselect All');
});
}
else if ($(button).html() == 'Deselect All') {
thisTable.api().rows().every(function () {
$(this.node()).removeClass(rowSelectedClass);
$(button).html('Select All');
});
}
}
});
/**
* on row click select/deselect row function
*/
$('body').on('click', '[data-type=selectable]', function () {
var rowSelectedClass = 'DTTT_selected selected';
$(this).toggleClass(rowSelectedClass);
var button = this,
thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
thisTable.api().rows().every(function () {
if (!$(this.node()).hasClass(rowSelectedClass)) {
$(button).closest('.dataTables_wrapper').find('[data-click-event=toggle-selected]').html('Select All');
}
});
});
/**
* list table list/grid view toggle function
*/
var toggleButton = $('[data-click-event=toggle-list-view]');
toggleButton.click(function () {
if ($(this).attr('data-view') == 'grid') {
$(this).closest('.dataTables_wrapper').find('.dataTable').addClass('grid-view');
//$(this).closest('li').hide();
//$(this).closest('li').siblings().show();
}
else {
$(this).closest('.dataTables_wrapper').find('.dataTable').removeClass('grid-view');
//$(this).closest('li').hide();
//$(this).closest('li').siblings().show();
}
})
}
},settings)
);
};

@ -26,10 +26,9 @@ var invokerUtil = function () {
restAPIRequestDetails["requestMethod"] = requestMethod; restAPIRequestDetails["requestMethod"] = requestMethod;
restAPIRequestDetails["requestURL"] = requestURL; restAPIRequestDetails["requestURL"] = requestURL;
restAPIRequestDetails["requestPayload"] = JSON.stringify(requestPayload); restAPIRequestDetails["requestPayload"] = JSON.stringify(requestPayload);
var appContext = devicemgtProps["appContext"];
var request = { var request = {
url: appContext + "api/invoker/execute/", url: context + "/api/invoker/execute/",
type: "POST", type: "POST",
contentType: "application/json", contentType: "application/json",
data: JSON.stringify(restAPIRequestDetails), data: JSON.stringify(restAPIRequestDetails),

@ -15,10 +15,7 @@
specific language governing permissions and limitations specific language governing permissions and limitations
under the License. under the License.
}} }}
{{#zone "bottomJs"}} {{#zone "content"}}
{{js "js/js.cookie.js"}}
{{js "js/invoker-lib.js"}}
<div id="error-msg" class="hide"> <div id="error-msg" class="hide">
<div class="content"> <div class="content">
<div class="row"> <div class="row">
@ -34,4 +31,11 @@
</div> </div>
</div> </div>
</div> </div>
{{/zone}} {{/zone}}
{{#zone "bottomJs"}}
<script type="text/javascript">
var context = "{{@app.context}}"
</script>
{{js "js/js.cookie.js"}}
{{js "js/invoker-lib.js"}}
{{/zone}}

@ -29,7 +29,7 @@ public class CertificateAuthenticator implements WebappAuthenticator {
private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth"; private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth";
private static final String MUTUAL_AUTH_HEADER = "mutual-auth-header"; private static final String MUTUAL_AUTH_HEADER = "mutual-auth-header";
private static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header"; private static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header";
private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header"; private static final String CERTIFICATE_VERIFICATION_HEADER = "Mdm-Signature";
private static final String CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate"; private static final String CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate";
@Override @Override
@ -55,7 +55,6 @@ public class CertificateAuthenticator implements WebappAuthenticator {
authenticationInfo.setStatus(Status.CONTINUE); authenticationInfo.setStatus(Status.CONTINUE);
} }
String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER);
try { try {
// When there is a load balancer terminating mutual SSL, it should pass this header along and // When there is a load balancer terminating mutual SSL, it should pass this header along and
// as the value of this header, the client certificate subject dn should be passed. // as the value of this header, the client certificate subject dn should be passed.
@ -78,7 +77,7 @@ public class CertificateAuthenticator implements WebappAuthenticator {
} }
} else if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null) { } else if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null) {
String certHeader = request.getHeader(certVerificationHeader); String certHeader = request.getHeader(CERTIFICATE_VERIFICATION_HEADER);
if (certHeader != null && if (certHeader != null &&
AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService(). AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService().
verifySignature(certHeader)) { verifySignature(certHeader)) {

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);

@ -0,0 +1,8 @@
CREATE TABLE DM_DEVICE_CERTIFICATE (
ID INTEGER IDENTITY NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE VARBINARY(max) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
)ENGINE = InnoDB;

@ -0,0 +1,8 @@
CREATE TABLE DM_DEVICE_CERTIFICATE (
ID NUMBER(10) NOT NULL,
SERIAL_NUMBER VARCHAR2(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID NUMBER(10) DEFAULT 0,
USERNAME VARCHAR2(500) DEFAULT NULL,
PRIMARY KEY (ID)
)

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID BIGSERIAL NOT NULL PRIMARY KEY,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BYTEA DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL
);

@ -1,3 +1,4 @@
instructions.configure = \ instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/wso2certs.jks,target:${installFolder}/../../resources/security/wso2certs.jks,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/wso2certs.jks,target:${installFolder}/../../resources/security/wso2certs.jks,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/certificate-config.xml,target:${installFolder}/../../conf/certificate-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/certificate-config.xml,target:${installFolder}/../../conf/certificate-config.xml,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/dbscripts/cdm/,target:${installFolder}/../../../dbscripts/cdm,overwrite:true);\

@ -17,15 +17,6 @@ CREATE TABLE IF NOT EXISTS DM_GROUP (
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE ( CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER auto_increment NOT NULL, ID INTEGER auto_increment NOT NULL,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,

@ -17,15 +17,6 @@ CREATE TABLE DM_GROUP (
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE DM_DEVICE_CERTIFICATE (
ID INTEGER IDENTITY NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE VARBINARY(max) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE DM_DEVICE ( CREATE TABLE DM_DEVICE (
ID INTEGER identity NOT NULL, ID INTEGER identity NOT NULL,
DESCRIPTION VARCHAR(max) DEFAULT NULL, DESCRIPTION VARCHAR(max) DEFAULT NULL,

@ -6,15 +6,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
PRIMARY KEY (ID) PRIMARY KEY (ID)
)ENGINE = InnoDB; )ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
)ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS DM_DEVICE ( CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER AUTO_INCREMENT NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,

@ -44,16 +44,6 @@ WHEN (NEW.ID IS NULL)
SELECT DM_GROUP_seq.NEXTVAL INTO :NEW.ID FROM DUAL; SELECT DM_GROUP_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
END; END;
/ /
CREATE TABLE DM_DEVICE_CERTIFICATE (
ID NUMBER(10) NOT NULL,
SERIAL_NUMBER VARCHAR2(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID NUMBER(10) DEFAULT 0,
USERNAME VARCHAR2(500) DEFAULT NULL,
PRIMARY KEY (ID)
)
/
-- Generate ID using sequence and trigger -- Generate ID using sequence and trigger
CREATE SEQUENCE DM_DEVICE_CERTIFICATE_seq START WITH 1 INCREMENT BY 1 NOCACHE CREATE SEQUENCE DM_DEVICE_CERTIFICATE_seq START WITH 1 INCREMENT BY 1 NOCACHE
/ /

@ -5,14 +5,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID BIGSERIAL NOT NULL PRIMARY KEY,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BYTEA DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS DM_DEVICE ( CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID BIGSERIAL NOT NULL PRIMARY KEY, ID BIGSERIAL NOT NULL PRIMARY KEY,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,

Loading…
Cancel
Save