Skip to content

Instantly share code, notes, and snippets.

@MrNaif2018
Created December 7, 2019 20:41
Show Gist options
  • Save MrNaif2018/4b38609505288e03f6caa9fe2e298cbf to your computer and use it in GitHub Desktop.
Save MrNaif2018/4b38609505288e03f6caa9fe2e298cbf to your computer and use it in GitHub Desktop.
export const routeOption = (route, key, value) => {
return route.matched.some((m) => {
if (process.client) {
// Client
return Object.values(m.components).some(
component => component.options && component.options[key] === value
)
} else {
// SSR
return Object.values(m.components).some(component =>
Object.values(component._Ctor).some(
ctor => ctor.options && ctor.options[key] === value
)
)
}
})
}
export const getMatchedComponents = (route, matches = false) => {
return [].concat.apply([], route.matched.map(function (m, index) {
return Object.keys(m.components).map(function (key) {
matches && matches.push(index)
return m.components[key]
})
}))
}
export function normalizePath (path = '') {
// Remove query string
let result = path.split('?')[0]
// Remove redundant / from the end of path
if (result.charAt(result.length - 1) === '/') {
result = result.slice(0, -1)
}
return result
}
export default function (ctx) {
if (!process.client) { return }
// Disable middleware if options: { auth: false } is set on the route
if (routeOption(ctx.route, 'auth', false)) {
return
}
// Disable middleware if no route was matched to allow 404/error page
const matches = []
const Components = getMatchedComponents(ctx.route, matches)
if (!Components.length) {
return
}
const { login, callback } = ctx.$auth.options.redirect
const pageIsInGuestMode = routeOption(ctx.route, 'auth', 'guest')
const insidePage = page => normalizePath(ctx.route.path) === normalizePath(page)
if (ctx.$auth.$state.loggedIn) {
// -- Authorized --
if (!login || insidePage(login) || pageIsInGuestMode) {
ctx.$auth.redirect('home')
}
} else if (!pageIsInGuestMode && (!callback || !insidePage(callback))) {
ctx.$auth.redirect('login')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment