Created
October 31, 2023 13:06
-
-
Save ChecksumFailed/5234844da8fbd1262885ea17b4dc2486 to your computer and use it in GitHub Desktop.
ServiceNow: Get Active Sessions with username and node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Retrieves active user sessions and associated nodes for a list of user IDs. | |
* | |
* @param {string[]} userIDs - An array of user IDs for which to retrieve active sessions. | |
* @returns {Object[]|undefined} - An array of session and node information, or undefined if no active sessions are found. | |
*/ | |
function cf_getActiveUserSessions(userIDs) { | |
/** | |
* Internal function to get active sessions for given user IDs. | |
* | |
* @param {string[]} userIDs - An array of user IDs for which to retrieve active sessions. | |
* @returns {Object} - An object containing arrays of session IDs and corresponding user IDs. | |
*/ | |
function _getActiveSessions(userIDs) { | |
var returnObj = { sessions: [], users: [] }; | |
var qry = | |
!userIDs || userIDs.length == 0 | |
? "name!=NULL" | |
: "nameIN" + userIDs.join(","); | |
new GlideQuery.parse("sys_user_session", qry) | |
.whereNull("invalidated") | |
.select("id", "name") | |
.forEach(function (sessionObj) { | |
returnObj["sessions"].push(sessionObj.id.toString()); | |
returnObj["users"].push(sessionObj.name.toString()); | |
}); | |
return returnObj; | |
} | |
/** | |
* Internal function to get nodes for given session IDs and user IDs. | |
* | |
* @param {string[]} sessionID - An array of session IDs. | |
* @param {string[]} userIDs - An array of user IDs. | |
* @returns {Object[]} - An array of objects containing session, node, and user ID information. | |
*/ | |
function _getNodes(sessionID, userIDs) { | |
return new GlideQuery("syslog_transaction") | |
.where("session", "IN", sessionID) | |
.where("sys_created_by", "IN", userIDs) | |
.aggregate("count") | |
.groupBy("system_id") | |
.groupBy("session") | |
.groupBy("sys_created_by") | |
.select() | |
.map(function (transLogGR) { | |
return { | |
session: transLogGR.group.session, | |
node: transLogGR.group.system_id.split(":")[1], | |
userID: transLogGR.group.sys_created_by, | |
}; | |
}) | |
.toArray(100); | |
} | |
var sessionArr = _getActiveSessions(userIDs); | |
if (!sessionArr || sessionArr.users.length == 0) { | |
return; | |
} | |
return _getNodes(sessionArr.sessions, sessionArr.users); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment