@lopatnov/namespace-guards
v3.0.1
Published
Route and service guards for @lopatnov/namespace. Intercept navigation and protect namespace keys with access checks.
Maintainers
Readme
@lopatnov/namespace-guards
Route guards and namespace access checks for @lopatnov/namespace. Intercept navigation with predicates, redirect unauthenticated users, and protect namespace keys from unauthorized reads.
Install
npm install @lopatnov/namespace @lopatnov/namespace-router @lopatnov/namespace-guardsQuick start
Route guard
import { createNamespace, get } from '@lopatnov/namespace';
import { createRouter, start } from '@lopatnov/namespace-router';
import { guard } from '@lopatnov/namespace-guards';
const ns = createNamespace();
const router = createRouter(ns, { mode: 'hash', root: '#app' });
// Redirect unauthenticated users
const unguard = guard(router, '/dashboard/*', ({ path }) => {
const user = get(ns, 'user');
return user ? true : '/login';
});
start(router);
// Remove the guard when no longer needed
unguard();Namespace protection
import { protect, allowed } from '@lopatnov/namespace-guards';
protect(ns, 'admin.config', () => get<boolean>(ns, 'user.isAdmin') === true);
allowed(ns, 'admin.config'); // false if user is not adminAPI
| Function | Description |
|----------|-------------|
| guard(router, pattern, fn) | Register a route guard. Returns unsubscribe function |
| protect(ns, key, fn) | Protect a namespace key with an access predicate. Returns unsubscribe function |
| allowed(ns, key) | Returns true if all predicates for the key pass |
Guard function
type GuardFn = (ctx: GuardContext) => boolean | string;
interface GuardContext {
path: string;
query: URLSearchParams;
}Return values:
true— allow navigationfalse— cancel (stay on current page)string— redirect to this path
Patterns
Route patterns support :param named segments and * wildcard, identical to route() in @lopatnov/namespace-router.
License
Apache-2.0 © lopatnov
