Skip to content

Instantly share code, notes, and snippets.

@ChecksumFailed
Created October 31, 2023 13:06
Show Gist options
  • Save ChecksumFailed/5234844da8fbd1262885ea17b4dc2486 to your computer and use it in GitHub Desktop.
Save ChecksumFailed/5234844da8fbd1262885ea17b4dc2486 to your computer and use it in GitHub Desktop.
ServiceNow: Get Active Sessions with username and node
/**
* 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