nuxt-users
Version:
A comprehensive user management module for Nuxt 3 and Nuxt 4 applications with authentication, authorization, database support, and CLI tools
53 lines (52 loc) • 1.7 kB
JavaScript
export const pathMatchesPattern = (path, pattern) => {
if (path === pattern) {
return true;
}
if (pattern === "*") {
return true;
}
if ((pattern.match(/\*/g) || []).length > 1) {
const regexPattern = pattern.replace(/\*/g, "[^/]*");
const regex = new RegExp(`^${regexPattern}`);
return regex.test(path);
}
if (pattern.endsWith("/*")) {
const basePattern = pattern.slice(0, -2);
return path === basePattern || path.startsWith(basePattern + "/");
}
if (pattern.includes("*")) {
const regexPattern = pattern.replace(/\*/g, "[^/]*");
const regex = new RegExp(`^${regexPattern}`);
return regex.test(path);
}
return false;
};
export const hasPermission = (userRole, path, method, permissions) => {
const safeMethods = ["OPTIONS", "HEAD", "TRACE"];
if (safeMethods.includes(method.toUpperCase())) {
return true;
}
if (!permissions || Object.keys(permissions).length === 0) {
return false;
}
const rolePermissions = permissions[userRole];
if (!rolePermissions) {
return false;
}
return rolePermissions.some((permission) => {
if (typeof permission === "string") {
return pathMatchesPattern(path, permission);
}
if (typeof permission === "object" && permission.path && permission.methods) {
const pathMatches = pathMatchesPattern(path, permission.path);
if (!pathMatches) {
return false;
}
return permission.methods.some((allowedMethod) => allowedMethod.toUpperCase() === method.toUpperCase());
}
return false;
});
};
export const isWhitelisted = (path, whitelist) => {
return whitelist.some((whitelistedPath) => pathMatchesPattern(path, whitelistedPath));
};