ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
77 lines • 2.9 kB
JavaScript
import { useCallback } from 'react';
import useAuthProvider, { defaultAuthParams } from "./useAuthProvider.js";
import useLogout from "./useLogout.js";
import { useNotify } from "../notification/index.js";
import { useBasename } from "../routing/index.js";
import { removeDoubleSlashes } from "../routing/useCreatePath.js";
/**
* Get a callback for calling the authProvider.checkAuth() method.
* In case of rejection, redirects to the login page, displays a notification,
* and throws an error.
*
* This is a low level hook. See those more specialized hooks
* for common authentication tasks, based on useCheckAuth.
*
* @see useAuthenticated
* @see useAuthState
*
* @returns {Function} checkAuth callback
*
* @example
*
* import { useCheckAuth } from 'react-admin';
*
* const MyProtectedPage = () => {
* const checkAuth = useCheckAuth();
* useEffect(() => {
* checkAuth().catch(() => {});
* }, []);
* return <p>Private content: EZAEZEZAET</p>
* } // tip: use useAuthenticated() hook instead
*
* const MyPage = () => {
* const checkAuth = useCheckAuth();
* const [authenticated, setAuthenticated] = useState(true); // optimistic auth
* useEffect(() => {
* checkAuth({}, false)
* .then(() => setAuthenticated(true))
* .catch(() => setAuthenticated(false));
* }, []);
* return authenticated ? <Bar /> : <BarNotAuthenticated />;
* } // tip: use useAuthState() hook instead
*/
export const useCheckAuth = () => {
const authProvider = useAuthProvider();
const notify = useNotify();
const logout = useLogout();
const basename = useBasename();
const loginUrl = removeDoubleSlashes(`${basename}/${defaultAuthParams.loginUrl}`);
const checkAuth = useCallback(async (params = {}, logoutOnFailure = true, redirectTo = loginUrl) => {
// The authProvider is optional in react-admin
if (!authProvider) {
return checkAuthWithoutAuthProvider();
}
try {
return await authProvider.checkAuth(params);
}
catch (error) {
if (logoutOnFailure) {
logout({}, error && error.redirectTo != null
? error.redirectTo
: redirectTo);
const shouldSkipNotify = error && error.message === false;
!shouldSkipNotify &&
notify(getErrorMessage(error, 'ra.auth.auth_check_error'), { type: 'error' });
}
throw error;
}
}, [authProvider, logout, notify, loginUrl]);
return checkAuth;
};
const checkAuthWithoutAuthProvider = async () => undefined;
const getErrorMessage = (error, defaultMessage) => typeof error === 'string'
? error
: typeof error === 'undefined' || !error.message
? defaultMessage
: error.message;
//# sourceMappingURL=useCheckAuth.js.map