ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
69 lines • 2.66 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { useEffect } from 'react';
import { useNavigate } from 'react-router';
import { useCanAccess, } from './useCanAccess';
import { useBasename } from '../routing';
/**
* A hook that calls the authProvider.canAccess() method for a provided resource and action (and optionally a record).
* It redirects to the /access-denied page if the user doesn't have the required permissions.
* It redirects to the /authentication-error page if the authProvider.canAccess throws an error.
*
* The return value updates according to the request state:
*
* - start: { isPending: true }
* - success: { isPending: false }
* - error: { error: [error from provider], isPending: false }
*
* Useful to enable or disable features based on users permissions.
*
* @param {Object} params Any params you want to pass to the authProvider
* @param {string} params.resource The resource to check access for
* @param {string} params.action The action to check access for
* @param {Object} params.record Optional. The record to check access for
*
* @returns Return the react-query result.
*
* @example
* import { useRequireAccess } from 'react-admin';
*
* const PostDetail = () => {
* const { isPending } = useRequireAccess({
* resource: 'posts',
* action: 'read',
* });
* if (isPending) {
* return null;
* }
*
* return <PostEdit />;
* };
*/
export var useRequireAccess = function (params) {
var _a = useCanAccess(params), canAccess = _a.canAccess, data = _a.data, error = _a.error, rest = __rest(_a, ["canAccess", "data", "error"]);
var navigate = useNavigate();
var basename = useBasename();
useEffect(function () {
if (rest.isPending)
return;
if (canAccess === false) {
navigate("".concat(basename, "/access-denied"));
}
}, [basename, canAccess, navigate, rest.isPending]);
useEffect(function () {
if (error) {
navigate("".concat(basename, "/authentication-error"));
}
}, [basename, navigate, error]);
return rest;
};
//# sourceMappingURL=useRequireAccess.js.map