UNPKG

techveda-react-auth

Version:

Techveda's React Authentication Library with context and hooks

34 lines 1.67 kB
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime"; import { useAuth } from '../hooks/useAuth'; export var ProtectedRoute = function (_a) { var children = _a.children, role = _a.role, permission = _a.permission, _b = _a.redirectTo, redirectTo = _b === void 0 ? '/login' : _b, _c = _a.fallback, fallback = _c === void 0 ? null : _c, _d = _a.loadingComponent, loadingComponent = _d === void 0 ? null : _d; var _e = useAuth(), user = _e.user, isAuthenticated = _e.isAuthenticated, hasRole = _e.hasRole, hasPermission = _e.hasPermission, loading = _e.loading; if (loading) return _jsx(_Fragment, { children: loadingComponent || fallback }); if (!isAuthenticated) { if (typeof window !== 'undefined') { window.location.href = redirectTo; } return _jsx(_Fragment, { children: fallback }); } if (role) { var roles = Array.isArray(role) ? role : [role]; if (!roles.some(function (r) { return hasRole(r); })) { if (typeof window !== 'undefined') { window.location.href = '/unauthorized'; } return _jsx(_Fragment, { children: fallback }); } } if (permission) { var permissions = Array.isArray(permission) ? permission : [permission]; if (!permissions.some(function (p) { return hasPermission(p); })) { if (typeof window !== 'undefined') { window.location.href = '/unauthorized'; } return _jsx(_Fragment, { children: fallback }); } } return _jsx(_Fragment, { children: children }); }; //# sourceMappingURL=ProtectedRoute.js.map