UniversalRouter Auth&Redirect
by Vladimir Kutepov
HTML
<script src="https://unpkg.com/universal-router@3/universal-router.js"></script>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/login">Login</a></li>
<li><a href="/admin/users">Users</a> (auth required)</li>
<li><a href="/admin/user/456?query=and&hash#example">User #456</a> (auth required)</li>
</ul>
<h1>Page Name</h1>
<p>Current location: <span>/</span></p>
<p><label><input type="checkbox" /> Authorized</label></p>
<p><label><input type="checkbox" /> Redirect</label></p>
JavaScript
// import UniversalRouter from 'universal-router'
let authorized = false
let redirect = false
const router = new UniversalRouter([
{ path: '/', action: () => 'Home' },
{ path: '/login', action: () => 'Login' },
{ path: '/admin', children: [
{ path: '/users', action: () => 'Users' },
{ path: '/user/:id', action: (ctx) => `User #${ctx.params.id}` }
], action(ctx) {
if (!authorized) {
return 'Access Denied!'
}
return ctx.next()
} }
])
const container = document.querySelector('h1')
const currentPath = document.querySelector('span')
function render() {
return router.resolve(location.pathname).then(page => {
if (redirect && page === 'Access Denied!') {
history.replaceState(null, 'Login', '/login')
return render()
}
container.innerHTML = page
currentPath.textContent = location.pathname + location.search + location.hash
})
}
const checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes[0].addEventListener('change', event => {
authorized = event.target.checked
})
checkboxes[1].addEventListener('change', event => {
redirect = event.target.checked
})
window.addEventListener('click', event => {
if (event.target.tagName === 'A') {
event.preventDefault()
const anchor = event.target
const state = null
const title = anchor.textContent
const url = anchor.pathname + anchor.search + anchor.hash
history.pushState(state, title, url)
render()
}
})
history.replaceState(null, '', '/')
render()