import { isAuthorized } from '../stores/auth'; import { checkAccess } from './auth-helpers'; /** * Creates requireAccess function and binds it to redux. * * @param redux Redux instance * @param {Function} notAuthorizedHandler called when access is denied and user is not authorized (eq 401 code) * @param {Function} accessDeniedHandler called when access is denied for current user (eq 403 code) * @returns {Function} Return function with signature requireAuth(accessLevel, [checkAccessHandler]). * checkAccessHandler is optional, by default checkAccessHandler = checkAccess (from access-helpers.js) */ export default function bindCheckAuth(redux, notAuthorizedHandler, accessDeniedHandler) { return (accessLevel, checkAccessHandler = checkAccess) => (nextState, transition) => { const state = redux.getState().auth; const currentAccessLvl = state.accessLvl; if (checkAccessHandler(accessLevel, currentAccessLvl)) { // Access granted return; } if (!isAuthorized(state)) { notAuthorizedHandler(nextState, transition); return; } accessDeniedHandler(nextState, transition); }; }