permissions refactor

This commit is contained in:
Jan Prochazka
2022-03-20 13:34:38 +01:00
parent 73d4c43571
commit 153bc6ddde
5 changed files with 40 additions and 11 deletions

View File

@@ -1,16 +1,38 @@
import _escapeRegExp from 'lodash/escapeRegExp';
import _isString from 'lodash/isString';
import _compact from 'lodash/compact';
export function compilePermissions(permissions: string[] | string) {
interface CompiledPermissions {
revoke: RegExp;
allow: RegExp;
}
function compileRegexp(permissions) {
if (permissions.length == 0) return null;
return new RegExp(permissions.map(x => '^' + _escapeRegExp(x).replace(/\\\*/g, '.*') + '$').join('|'));
}
export function compilePermissions(permissions: string[] | string): CompiledPermissions {
if (!permissions) return null;
if (_isString(permissions)) permissions = permissions.split(',');
return permissions.map(x => new RegExp('^' + _escapeRegExp(x).replace(/\\\*/g, '.*') + '$'));
permissions = _compact(permissions.map(x => x.trim()));
const revoke = permissions.filter(x => x.startsWith('~')).map(x => x.substring(1));
const allow = permissions.filter(x => !x.startsWith('~'));
return {
revoke: compileRegexp(revoke),
allow: compileRegexp(allow),
};
}
export function testPermission(tested: string, permissions: RegExp[]) {
export function testPermission(tested: string, permissions: CompiledPermissions) {
if (!permissions) return true;
for (const permission of permissions) {
if (tested.match(permission)) return true;
if (!permissions.revoke) return true;
if (tested.match(permissions.revoke)) {
if (!tested.match(permissions.allow)) {
return false;
}
}
return false;
return true;
}