Refactoring user-create page and related modules

4.x.x
dilanua 8 years ago
parent b636738be3
commit 24d846a328

@ -1,5 +1,5 @@
/*
* 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,
* Version 2.0 (the "License"); you may not use this file except
@ -10,8 +10,8 @@
*
* 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
* "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.
*/
@ -25,32 +25,30 @@ var userModule = function () {
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js")["utility"];
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 */
var carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var carbon = require("carbon");
var url = carbon.server.address("https") + "/admin/services";
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 deviceManagementService = utility.getDeviceManagementService();
//var EmailMessageProperties = Packages.org.wso2.carbon.device.mgt.common.EmailMessageProperties;
var publicMethods = {};
var privateMethods = {};
/**
* 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 () {
var carbon = require('carbon');
var carbonUser = session.get(constants.USER_SESSION_KEY);
var utility = require('/app/modules/utility.js').utility;
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;
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
return carbonUser;
};
@ -59,31 +57,25 @@ var userModule = function () {
* 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 {
* 'status': 'success'|'error',
* 'content': {}
* }
* @returns An object with 'status': 'success'|'error', 'content': {}
*/
privateMethods.callBackend = function (url, method) {
if (constants.HTTP_GET == method) {
var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
if (constants["HTTP_GET"] == method) {
return serviceInvokers.XMLHttp.get(url,
function (backendResponse) {
var response = {};
response.content = responsePayload["responseContent"];
if (responsePayload["responseContent"] == null && responsePayload != null) {
response.content = responsePayload;
}
response.content = backendResponse.responseText;
if (backendResponse.status == 200) {
response.status = "success";
return response;
},
function (responsePayload) {
var response = {};
response.content = responsePayload;
} else if (backendResponse.status == 400 || backendResponse.status == 401 ||
backendResponse.status == 404 || backendResponse.status == 500) {
response.status = "error";
}
return response;
});
return response;
}
);
} else {
log.error("Programming error : This method only support HTTP GET requests.");
log.error("Runtime error : This method only support HTTP GET requests.");
}
};
@ -101,43 +93,43 @@ var userModule = function () {
*
* @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();
}
};
// 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();
// }
// };
/**
* Register user to dc-user-store.
@ -188,39 +180,39 @@ var userModule = function () {
* @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();
}
};
// 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
@ -232,25 +224,25 @@ var userModule = function () {
*
* @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);
};
// 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
@ -264,17 +256,17 @@ var userModule = function () {
*
* @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;
};
// 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
@ -286,89 +278,89 @@ var userModule = function () {
* @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();
}
};
// 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)
};
// 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)
};
// 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)
};
// 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();
}
};
// 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
@ -382,9 +374,12 @@ var userModule = function () {
}
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users";
return privateMethods.callBackend(url, constants.HTTP_GET);
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 {
@ -395,22 +390,16 @@ var userModule = function () {
/**
* Return a User object from the backend by calling the JAX-RS
* @param username
* @returns {
* 'status': 'success'|'error',
* 'content': {
"username": "abc",
"firstname": "abc",
"lastname": "efj",
"emailAddress": "abc@abc.com"
}
* }
* @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"] + constants.ADMIN_SERVICE_CONTEXT + "/users/view?username=" + username;
var response = privateMethods.callBackend(url, constants.HTTP_GET);
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) {
@ -419,18 +408,19 @@ var userModule = function () {
utility.endTenantFlow();
}
};
/**
* TODO: comment
* Returns a set of roles assigned to a particular user
* @param username
* @returns {*}
* @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"] + constants.ADMIN_SERVICE_CONTEXT + "/users/roles?username=" + username;
var response = privateMethods.callBackend(url, constants.HTTP_GET);
return response;
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" +
encodeURIComponent(username) + "/roles";
return privateMethods.callBackend(url, constants["HTTP_GET"]);
} catch (e) {
throw e;
} finally {
@ -450,8 +440,8 @@ var userModule = function () {
}
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/users-by-username";
return privateMethods.callBackend(url, constants.HTTP_GET)
var url = devicemgtProps["httpsURL"] + "/mdm-admin/users/users-by-username";
return privateMethods.callBackend(url, constants["HTTP_GET"]);
} catch (e) {
throw e;
} finally {
@ -467,15 +457,19 @@ var userModule = function () {
*/
publicMethods.getRoles = function () {
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) {
log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles";
return privateMethods.callBackend(url, constants.HTTP_GET);
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles";
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 {
@ -488,18 +482,24 @@ var userModule = function () {
*/
/**
* 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 utility = require('/app/modules/utility.js')["utility"];
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"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + encodeURIComponent(userStore);
return privateMethods.callBackend(url, constants.HTTP_GET);
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 {
@ -510,17 +510,22 @@ var userModule = function () {
/**
* 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"];
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"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types";
return privateMethods.callBackend(url, constants.HTTP_GET);
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 {
@ -535,15 +540,17 @@ var userModule = function () {
*/
publicMethods.getRole = function (roleName) {
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) {
log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
try {
utility.startTenantFlow(carbonUser);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/role?rolename=" + encodeURIComponent(roleName);
var response = privateMethods.callBackend(url, constants.HTTP_GET);
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;
@ -776,24 +783,29 @@ var userModule = function () {
* retrieve secondary user stores.
* 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 () {
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'/>";
serviceInvokers.WS.soapRequest(
"urn:getSecondaryRealmConfigurations", endpoint, wsPayload, function (wsResponse) {
"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");
var regExpForSearch = new RegExp(constants["USER_STORES_NOISY_CHAR"], "g");
domainIDs = domainIDs.replace(regExpForSearch, "");
returnVal = domainIDs.split(constants.USER_STORES_SPLITTING_CHAR);
returnVal = domainIDs.split(constants["USER_STORES_SPLITTING_CHAR"]);
}
}, function (e) {
log.error("Error retrieving secondary user stores", e);
}, constants.SOAP_VERSION);
},
constants["SOAP_VERSION"]);
return returnVal;
};
return publicMethods;
}();

@ -15,7 +15,7 @@
specific language governing permissions and limitations
under the License.
}}
{{unit "cdmf.unit.ui.title" pageTitle="User Management"}}
{{unit "cdmf.unit.ui.title" pageTitle="User Management | Add User"}}
{{#zone "breadcrumbs"}}
<li>
@ -50,8 +50,8 @@
<div id="user-create-error-msg" class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<label class="wr-input-label" title="List of available secondary user stores">
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 Store Domain
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
@ -96,12 +96,10 @@
<div id="emailField" class=" form-group wr-input-control">
<input type="email" id="emailAddress" class="form-control"/>
<span class="glyphicon glyphicon-remove form-control-feedback hidden emailError"></span>
<label class=" hidden error email-required" for="summary">This field is
required.</label>
<label class=" hidden error email-required" for="summary">This field is required.</label>
<label class=" hidden error email-invalid" for="summary">Invalid Email Address.</label>
</div>
<label class="wr-input-label"
title="Optional field that can have 0-to-many roles for the user">
<label class="wr-input-label" title="Optional field that can have 0-to-many roles for the user">
User Roles
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
@ -123,7 +121,6 @@
<p class="page-sub-title">User was added successfully.</p>
<br>
An invitation mail will be sent to this user to initiate device enrollment.
<div class="panel panel-default">
<div class="panel-body">
<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
<b>"View User List"</b> to complete the process and go back to the user list.
<hr/>
<button class="wr-btn" onclick="window.location.href='{{@app.context}}/users'">View User List
</button>
<button class="wr-btn" onclick="window.location.href='{{@app.context}}/users'">View User List</button>
<a href="{{@app.context}}/user/add" class="cu-btn-inner">
<span class="fw-stack">
<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
*/
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 response = userModule.getRolesByUserStore("PRIMARY");
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var devicemgtProps = require("/app/conf/devicemgt-props.js").config();
var page = {};
page["charLimit"] = devicemgtProps.usernameLength;
var response = userModule.getRolesByUserStore();
if (response["status"] == "success") {
page["roles"] = response["content"];
}
page["usernameJSRegEx"] = devicemgtProps.userValidationConfig.usernameJSRegEx;
page["usernameHelpMsg"] = devicemgtProps.userValidationConfig.usernameHelpMsg;
page["usernameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.usernameRegExViolationErrorMsg;
page["firstnameJSRegEx"] = devicemgtProps.userValidationConfig.firstnameJSRegEx;
page["firstnameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.firstnameRegExViolationErrorMsg;
page["lastnameJSRegEx"] = devicemgtProps.userValidationConfig.lastnameJSRegEx;
page["lastnameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.lastnameRegExViolationErrorMsg;
page["charLimit"] = devicemgtProps["usernameLength"];
page["usernameJSRegEx"] = devicemgtProps["userValidationConfig"]["usernameJSRegEx"];
page["usernameHelpMsg"] = devicemgtProps["userValidationConfig"]["usernameHelpMsg"];
page["usernameRegExViolationErrorMsg"] = devicemgtProps["userValidationConfig"]["usernameRegExViolationErrorMsg"];
page["firstnameJSRegEx"] = devicemgtProps["userValidationConfig"]["firstnameJSRegEx"];
page["firstnameRegExViolationErrorMsg"] = devicemgtProps["userValidationConfig"]["firstnameRegExViolationErrorMsg"];
page["lastnameJSRegEx"] = devicemgtProps["userValidationConfig"]["lastnameJSRegEx"];
page["lastnameRegExViolationErrorMsg"] = devicemgtProps["userValidationConfig"]["lastnameRegExViolationErrorMsg"];
return page;
}

@ -10,8 +10,8 @@
*
* 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
* "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.
*/
@ -30,6 +30,7 @@ function inputIsValid(regExp, inputString) {
var validateInline = {};
var clearInline = {};
var deviceMgtAPIsBasePath = "/api/device-mgt/v1.0";
var enableInlineError = function (inputField, errorMsg, errorSign) {
var fieldIdentifier = "#" + inputField;
@ -160,16 +161,16 @@ function emailIsValid(email) {
return regExp.test(email);
}
$("#userStore")
.change(function () {
$("#userStore").change(
function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
var addUserAPI = "/devicemgt_admin/roles/" + str;
var getRolesAPI = deviceMgtAPIsBasePath + "/roles/"+ str;
invokerUtil.get(
addUserAPI,
getRolesAPI,
function (data) {
data = JSON.parse(data);
if (data.errorMessage) {
@ -182,9 +183,13 @@ $("#userStore")
$('#roles').append(newOption);
}
}
},
function (jqXHR) {
}
);
}).change();
}
).change();
$(document).ready(function () {
$("#emailValidationText").hide();
@ -202,7 +207,7 @@ $(document).ready(function () {
var usernameInput = $("input#username");
var firstnameInput = $("input#firstname");
var lastnameInput = $("input#lastname");
var charLimit = parseInt($("input#username").attr("limit"));
//var charLimit = parseInt($("input#username").attr("limit"));
var domain = $("#userStore").val();
var username = usernameInput.val().trim();
var firstname = firstnameInput.val();
@ -244,17 +249,13 @@ $(document).ready(function () {
addUserFormData.emailAddress = emailAddress;
addUserFormData.roles = roles;
var addUserAPI = "/devicemgt_admin/users";
var addUserAPI = deviceMgtAPIsBasePath + "/users";
invokerUtil.post(
addUserAPI,
addUserFormData,
function (data) {
data = JSON.parse(data);
if (data.errorMessage) {
$(errorMsg).text("Selected user store prompted an error : " + data.errorMessage);
$(errorMsgWrapper).removeClass("hidden");
} else if (data["statusCode"] == 201) {
function (data, textStatus, jqXHR) {
if (jqXHR.status == 201) {
// Clearing user input fields.
$("input#username").val("");
$("input#firstname").val("");
@ -264,21 +265,17 @@ $(document).ready(function () {
// Refreshing with success message
$("#user-create-form").addClass("hidden");
$("#user-created-msg").removeClass("hidden");
} else if (data["statusCode"] == 409) {
$(errorMsg).text(data["messageFromServer"]);
$(errorMsgWrapper).removeClass("hidden");
} else if (data["statusCode"] == 500) {
$(errorMsg).text("An unexpected error occurred at backend server. Please try again later.");
$(errorMsgWrapper).removeClass("hidden");
generateQRCode("#user-created-msg .qr-code");
}
}, function (data) {
data = JSON.parse(data.responseText);
if (data["statusCode"] == 409) {
var payload = JSON.parse(data.responseText);
if (data.status == 409) {
$(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.");
} else {
$(errorMsg).text(data.errorMessage);
$(errorMsg).text(payload.message);
}
$(errorMsgWrapper).removeClass("hidden");
}

Loading…
Cancel
Save