Skip to content

Instantly share code, notes, and snippets.

@TitasGailius
Created March 27, 2018 12:45
Show Gist options
  • Save TitasGailius/e06c7fa4778a002660b9b5c810b86b77 to your computer and use it in GitHub Desktop.
Save TitasGailius/e06c7fa4778a002660b9b5c810b86b77 to your computer and use it in GitHub Desktop.
export default async ({ store, redirect, req }) => {
/**
* Unautheticated client handler.
*/
const unauthenticated = () => redirect('/login')
/**
* Fetch the user from an API.
*/
const fetch = async () => {
return await store.dispatch('auth/fetchUser').catch(() => unauthenticated)
}
/**
* Perform authentication on the server.
*/
const serverAuthentication = async () => {
if (store.state.auth.user) {
return
}
if (req.signedCookies.access_token) {
return await fetch()
}
return unauthenticated()
}
/**
* Perfom authentication on the client.
*/
const clientAuthentication = async () => {
if (!store.state.auth.user) {
return await fetch()
}
}
return process.server
? serverAuthentication()
: clientAuthentication()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment