ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
73 lines • 2.88 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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useRequireAccess = void 0;
var react_1 = require("react");
var react_router_1 = require("react-router");
var useCanAccess_1 = require("./useCanAccess");
var routing_1 = require("../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 />;
* };
*/
var useRequireAccess = function (params) {
var _a = (0, useCanAccess_1.useCanAccess)(params), canAccess = _a.canAccess, data = _a.data, error = _a.error, rest = __rest(_a, ["canAccess", "data", "error"]);
var navigate = (0, react_router_1.useNavigate)();
var basename = (0, routing_1.useBasename)();
(0, react_1.useEffect)(function () {
if (rest.isPending)
return;
if (canAccess === false) {
navigate("".concat(basename, "/access-denied"));
}
}, [basename, canAccess, navigate, rest.isPending]);
(0, react_1.useEffect)(function () {
if (error) {
navigate("".concat(basename, "/authentication-error"));
}
}, [basename, navigate, error]);
return rest;
};
exports.useRequireAccess = useRequireAccess;
//# sourceMappingURL=useRequireAccess.js.map
;