@slashid/docusaurus-theme-slashid
Version:
SlashID theme for Docusaurus.
100 lines (94 loc) • 3.07 kB
JavaScript
/* ============================================================================
* Copyright (c) SlashID
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* ========================================================================== */
import globToRegexp from "glob-to-regexp";
export function shouldPathRender(path, privatePaths, user) {
if (!privatePaths || !path) return true;
const matchingPrivatePaths = privatePaths.filter((privatePath) => {
let matches = false;
if (typeof privatePath.path === "string") {
matches = path.includes(privatePath.path);
} else if (privatePath.path instanceof RegExp) {
matches = privatePath.path.test(path);
}
if (!matches) return false;
if (!user) return true;
if (privatePath.groups) {
const userGroups = user.getGroups();
return !privatePath.groups.every((group) => userGroups.includes(group));
}
// invalid config - should render
return false;
});
return matchingPrivatePaths.length === 0;
}
/**
* Tests if the given item should be rendered based on the user state and the front matter config.
* @param slashIDProps set by the front matter on the relevant page
* @param user SlashID User instance
* @returns a {boolean} indicating whether the user should be able to see the item
*/
export function shouldItemRender(slashIDProps, user) {
// paths take precedence
if (!slashIDProps || !slashIDProps.auth) {
return true;
}
const { groups } = slashIDProps;
if (!user) {
return false;
}
if (groups) {
const userGroups = user.getGroups();
return groups.every((group) => userGroups.includes(group));
}
return true;
}
export function isCategory(item) {
return item.hasOwnProperty("items") && item.type === "category";
}
export function isHtmlSidebarItem(item) {
return item.type === "html";
}
export function shouldNoItemsRender(items, user, getSlashIDProps) {
return (
items.filter((item) => {
if (isCategory(item)) {
return shouldNoItemsRender(item.items, user, getSlashIDProps);
} else {
// custom items should always be rendered as they might have custom rules
if (isHtmlSidebarItem(item)) return true;
return shouldItemRender(getSlashIDProps(item), user);
}
}).length === 0
);
}
/**
* Ensure the privatePaths config is converted to RegExp instances if globs are used.
*/
export function convertGlobToRegex(config) {
if (config?.privatePaths) {
let convertedPaths = [];
convertedPaths = config.privatePaths.map((pathConfig) => {
if (typeof pathConfig.path === "string") {
try {
return {
...pathConfig,
path: globToRegexp(pathConfig.path),
};
} catch (e) {
console.error(`Invalid glob pattern: ${pathConfig}`);
return pathConfig;
}
}
return pathConfig;
});
return {
...config,
privatePaths: convertedPaths,
};
}
return config;
}