@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
218 lines • 13.7 kB
JavaScript
/**
*
*2026-01-08:
* NOTE: THIS IS OUTDATED AND WILL BE RELACED WHEN Permissions Impossible webpart is updated.
*
*
*/
import { check4This, Check4 } from "../../logic/Links/CheckSearch";
import { doSpHttpFetchOrPostAndCheck } from "../../components/molecules/SpHttp/Sp/doSpHttpFetch";
import { SourcePropsNoWebUrl } from "../../components/molecules/source-props/ISourceProps";
import { makeAbsoluteUrl } from "../../logic/Strings/getSiteCollectionUrlFromLink";
import { createErrorFpsListReturn } from "../../components/molecules/process-results/createErrorFpsListItemsReturn";
import { startPerformOpV2, updatePerformanceEndV2 } from "../../components/molecules/Performance/functions";
/**
* 2025-01-03: New function to fetch SharePoint Online Permission Levels
*
* getPermissionLevelsAPI fetches all permission levels defined at the site level
* from the SharePoint REST API endpoint: /_api/web/RoleDefinitions
*
* Optionally can fetch detailed permission breakdowns for each level by
* parsing the role settings UI or making additional API calls.
*
* import { getPermissionLevelsAPI } from '@mikezimm/fps-core-v7/lib/restAPIs/permissions/getPermissionLevelsAPI';
*
* @param fpsSpService - The SharePoint HTTP service for making API calls
* @param webUrl - The web URL to fetch permission levels from
* @param includeDetails - If true, fetch detailed permission info for each level (optional)
* @param alertMe - Whether to show alert messages on error (optional)
* @param consoleLog - Whether to log results to console (optional)
* @returns Promise with permission levels and optional detailed permission info
*/
export async function getPermissionLevelsAPI(fpsSpService, webUrl, includeDetails = false, alertMe = false, consoleLog = false) {
const useUrl = makeAbsoluteUrl(webUrl);
if (!useUrl) {
// NO WebURL... Throw Alert
if (alertMe === true)
alert(`getPermissionLevelsAPI: ${SourcePropsNoWebUrl}`);
const results = createErrorFpsListReturn(useUrl, '');
results.status = 'NoWeb';
results.permissionLevels = [];
return results;
}
const performanceSettings = { label: 'FetchPermissionLevels', includeMsStr: true, updateMiliseconds: true, op: 'fetch' };
let fetchOp = startPerformOpV2(performanceSettings);
try {
// Fetch all role definitions (permission levels) from the web
const fetchAPIRoles = `${useUrl}/_api/web/RoleDefinitions`;
const rolesResult = await doSpHttpFetchOrPostAndCheck(fetchAPIRoles, 'GET', fpsSpService, '', alertMe, consoleLog, 'role', false, null);
const results = rolesResult;
// Map the fetched items to IFpsPermissionLevelInfo
if (rolesResult.items && Array.isArray(rolesResult.items)) {
results.permissionLevels = rolesResult.items.map((item) => ({
Id: item.Id,
Name: item.Name,
Description: item.Description,
Hidden: item.Hidden,
Order: item.Order,
RoleTypeKind: item.RoleTypeKind,
BasePermissions: item.BasePermissions,
}));
}
else {
results.permissionLevels = [];
}
results.items = rolesResult.items;
results.item = rolesResult.item || rolesResult['list'];
// If detailed permission info is requested, fetch additional details for each level
if (includeDetails && results.permissionLevels.length > 0) {
results.permissionLevelDetails = await Promise.all(results.permissionLevels.map(async (level) => {
const details = await getPermissionLevelDetailsAPI(fpsSpService, useUrl, level.Id, alertMe, consoleLog);
return {
...level,
permissions: details.permissions || [],
};
}));
}
fetchOp = updatePerformanceEndV2({ op: fetchOp, updateMiliseconds: true, count: results.permissionLevels.length });
results.fetchOp = fetchOp;
if (check4This(Check4.fpsShowFetchResults_Eq_true) === true) {
console.log(`fps-core-v7 COMPLETE: getPermissionLevelsAPI ~ 120`, results);
}
return results;
}
catch (error) {
if (alertMe === true)
alert(`getPermissionLevelsAPI error: ${error}`);
const results = createErrorFpsListReturn(useUrl, '');
results.permissionLevels = [];
results.status = 'Error';
return results;
}
}
/**
* Helper function to fetch detailed permission information for a specific permission level
* This parses the BasePermissions bits to determine which individual permissions are enabled
*
* @param fpsSpService - The SharePoint HTTP service
* @param webUrl - The web URL
* @param roleDefinitionId - The ID of the role definition to get details for
* @param alertMe - Whether to show alerts
* @param consoleLog - Whether to log to console
* @returns Object with array of individual permissions and their enabled status
*/
export async function getPermissionLevelDetailsAPI(fpsSpService, webUrl, roleDefinitionId, alertMe = false, consoleLog = false) {
const useUrl = makeAbsoluteUrl(webUrl);
try {
// Fetch the specific role definition
const fetchAPIRole = `${useUrl}/_api/web/RoleDefinitions(${roleDefinitionId})`;
const roleResult = await doSpHttpFetchOrPostAndCheck(fetchAPIRole, 'GET', fpsSpService, '', alertMe, consoleLog, 'permDetail', false, null);
const roleInfo = roleResult.item || roleResult;
const permissions = [];
// Parse BasePermissions to determine which individual permissions are enabled
if (roleInfo.BasePermissions) {
const basePerms = roleInfo.BasePermissions;
permissions.push(...parseBasePermissions(basePerms));
}
if (consoleLog === true) {
console.log(`fps-core-v7: getPermissionLevelDetailsAPI ~ 180`, { roleInfo, permissions });
}
return { permissions };
}
catch (error) {
if (consoleLog === true) {
console.error(`getPermissionLevelDetailsAPI error: ${error}`);
}
return { permissions: [] };
}
}
/**
* Parse SharePoint BasePermissions bit flags to individual permissions
* Maps the Low and High 32-bit values to specific SharePoint permission names
*
* Reference permission bits (as defined in SharePoint):
* List Permissions (bits in Low value):
* - Manage Lists (bit 0)
* - Override List Behaviors (bit 1)
* - Add Items (bit 2)
* - Edit Items (bit 3)
* - Delete Items (bit 4)
* - View Items (bit 5)
*
* And many others in Web Permissions (High value)
*
* @param basePermissions - The BasePermissions object with Low and High values
* @returns Array of IFpsPermissionInfo objects
*/
function parseBasePermissions(basePermissions) {
const permissions = [];
// List Permissions (Low bits)
const listPermissions = [
{ bit: 0, name: 'Manage Lists', description: 'Create and delete lists, add or remove columns in a list, and add or remove public views of a list.' },
{ bit: 1, name: 'Override List Behaviors', description: 'Discard or check in a document which is checked out to another user, and change or override settings which allow users to read/edit only their own items.' },
{ bit: 2, name: 'Add Items', description: 'Add items to lists and add documents to document libraries.' },
{ bit: 3, name: 'Edit Items', description: 'Edit items in lists, edit documents in document libraries, and customize Web Part Pages in document libraries.' },
{ bit: 4, name: 'Delete Items', description: 'Delete items from a list and documents from a document library.' },
{ bit: 5, name: 'View Items', description: 'View items in lists and documents in document libraries.' },
{ bit: 6, name: 'Approve Items', description: 'Approve a minor version of a list item or document.' },
{ bit: 7, name: 'Open Items', description: 'View the source of documents with server-side file handlers.' },
{ bit: 8, name: 'View Versions', description: 'View past versions of a list item or document.' },
{ bit: 9, name: 'Delete Versions', description: 'Delete past versions of a list item or document.' },
{ bit: 10, name: 'Cancel Checkout', description: 'Discard or check in a document which is checked out to another user.' },
{ bit: 11, name: 'Manage Personal Views', description: 'Create, change, and delete personal views of lists.' },
{ bit: 12, name: 'Manage Web Alerts', description: 'Create, change, and delete alerts for lists or documents.' },
];
// Web Permissions (High bits)
const webPermissions = [
{ bit: 0, name: 'Create Lists', description: 'Create lists and document libraries.' },
{ bit: 1, name: 'Create Subsites', description: 'Create subsites such as team sites, meeting workspace sites, and other subsites.' },
{ bit: 2, name: 'Edit Web', description: 'Edit web property, such as Web title and description.' },
{ bit: 3, name: 'Manage Web', description: 'Grant the ability to perform all administration tasks for the Web site as well as manage content.' },
{ bit: 4, name: 'Manage Subwebs', description: 'Create, edit, and delete subsites including meeting workspaces.' },
{ bit: 5, name: 'Create Groups', description: 'Create a group of users that can be used anywhere within the site collection.' },
{ bit: 6, name: 'Manage Groups', description: 'Create, edit, and delete groups; also edit membership of groups.' },
{ bit: 7, name: 'Manage Users', description: 'Create and edit users and groups, including the ability to give users access to the Web site.' },
{ bit: 8, name: 'Manage Permissions', description: 'Create and change permission levels on the Web site and assign permissions to users and groups.' },
{ bit: 9, name: 'Browse User Information', description: 'View information about users of the Web site.' },
{ bit: 10, name: 'Use Client Integration Features', description: 'Use features that launch client applications; without this permission, users must work on documents in server farms and cumbersome upload locations.' },
{ bit: 11, name: 'Use Remote Interfaces', description: 'Use SOAP, WebDAV, or SharePoint Designer interfaces to access the Web site.' },
{ bit: 12, name: 'Manage Alerts', description: 'Manage alerts for all users of the Web site.' },
{ bit: 13, name: 'View Usage Data', description: 'View reports on Web site usage.' },
{ bit: 14, name: 'Create Roles', description: 'Create new permission levels.' },
{ bit: 15, name: 'Create HTML Pages', description: 'Create, change, and delete HTML pages accessible in document libraries.' },
{ bit: 16, name: 'Browse Directories', description: 'Enumerate files and folders in a Web site using SharePoint Designer and Web DAV interfaces.' },
{ bit: 17, name: 'Edit Personal User Information', description: 'Allow a user to edit his or her own user information, such as adding a picture.' },
{ bit: 18, name: 'Manage Web Site', description: 'Grant the ability to perform all administration tasks for the Web site as well as manage content. Includes all permissions.' },
{ bit: 19, name: 'Add and Customize Pages', description: 'Add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a Windows SharePoint Services compatible editor.' },
{ bit: 20, name: 'Apply Themes and Borders', description: 'Apply a theme or borders to the entire Web site.' },
{ bit: 21, name: 'Apply Style Sheets', description: 'Apply a style sheet (.css file) to the Web site.' },
{ bit: 22, name: 'Create Master Pages and Page Layouts', description: 'Create and edit master pages and page layouts in this Web site.' },
{ bit: 23, name: 'Set Web Part Properties', description: 'Create and edit Web Part properties on the Web site. This does not include connecting to server farm instances.' },
{ bit: 24, name: 'View Forms', description: 'View forms, views, and reports, not including user-facing queries.' },
{ bit: 25, name: 'Open', description: 'Open a Web site, list, or folder to access items inside that container.' },
{ bit: 26, name: 'View Pages', description: 'View pages in a Web site.' },
{ bit: 27, name: 'Enumerate Permissions', description: 'Enumerate permissions on Web sites, lists, folders, documents, and list items.' },
];
// Check Low bits (List Permissions)
listPermissions.forEach((perm) => {
const isEnabled = ((basePermissions.Low >> perm.bit) & 1) === 1;
permissions.push({
name: perm.name,
description: perm.description,
enabled: isEnabled,
permissionId: perm.bit,
});
});
// Check High bits (Web Permissions)
webPermissions.forEach((perm) => {
const isEnabled = ((basePermissions.High >> perm.bit) & 1) === 1;
permissions.push({
name: perm.name,
description: perm.description,
enabled: isEnabled,
permissionId: perm.bit + 32, // Offset by 32 to distinguish from Low bits
});
});
return permissions;
}
//# sourceMappingURL=getPermissionLevelsAPI.js.map