FitTrackee/fittrackee_client/src/utils/history.js

45 lines
1.0 KiB
JavaScript
Raw Normal View History

2020-05-17 18:20:15 +02:00
const routesWithoutAuthentication = [
'/login',
'/register',
'/password-reset',
'/password-reset/request',
'/password-reset/sent',
'/updated-password',
]
const updatePath = (toPath, newPath) => {
if (typeof toPath === 'string' || toPath instanceof String) {
toPath = newPath
} else {
toPath.pathname = newPath
}
return toPath
}
const pathInterceptor = toPath => {
if (
!window.localStorage.authToken &&
2020-05-17 18:20:15 +02:00
!routesWithoutAuthentication.includes(toPath.pathname)
) {
toPath = updatePath(toPath, '/login')
}
if (
window.localStorage.authToken &&
2020-05-17 18:20:15 +02:00
routesWithoutAuthentication.includes(toPath.pathname)
) {
toPath = updatePath(toPath, '/')
}
return toPath
}
export const historyEnhancer = originalHistory => {
originalHistory.location = pathInterceptor(originalHistory.location)
return {
...originalHistory,
push: (path, ...args) =>
originalHistory.push(pathInterceptor(path), ...args),
replace: (path, ...args) =>
originalHistory.replace(pathInterceptor(path), ...args),
}
}