Skip to content

Instantly share code, notes, and snippets.

@rickyalmeidadev
Created February 4, 2022 16:45
Show Gist options
  • Save rickyalmeidadev/b753f9499264663d14d256e91446de0b to your computer and use it in GitHub Desktop.
Save rickyalmeidadev/b753f9499264663d14d256e91446de0b to your computer and use it in GitHub Desktop.
Server-side authentication higher order functions
import nookies from 'nookies'
class ServerSideAuth {
static #key = 'token'
static #cookies = nookies
static #isAuthenticated = token => {
const response = fetch('http://localhost:3000/api/me', {
headers: {
authorization: `Bearer ${token}`,
},
})
return response.status !== 401
}
static #execute = async (context, fn) => {
if (typeof fn === 'function') {
const payload = await fn(context)
if (payload) {
return payload
}
}
return {
props: {},
}
}
static withPublic = fn => async context => {
const cookies = ServerSideAuth.#cookies.get(context)
if (cookies.token) {
const isAuthenticated = ServerSideAuth.#isAuthenticated(cookies.token)
if (!isAuthenticated) {
ServerSideAuth.#cookies.destroy(context, ServerSideAuth.#key)
}
}
return ServerSideAuth.#execute(context, fn)
}
static withAuthFlow = fn => async context => {
const cookies = ServerSideAuth.#cookies.get(context)
if (cookies.token) {
const isAuthenticated = ServerSideAuth.#isAuthenticated(cookies.token)
if (isAuthenticated) {
return {
redirect: {
destination: '/dashboard',
},
}
}
ServerSideAuth.#cookies.destroy(context, ServerSideAuth.#key)
}
return ServerSideAuth.#execute(context, fn)
}
static withPrivate = fn => async context => {
const cookies = ServerSideAuth.#cookies.get(context)
if (!cookies.token) {
return {
redirect: {
destination: '/login',
},
}
}
const isAuthenticated = ServerSideAuth.#isAuthenticated(cookies.token)
if (!isAuthenticated) {
ServerSideAuth.#cookies.destroy(context, ServerSideAuth.#key)
return {
redirect: {
destination: '/login',
},
}
}
return ServerSideAuth.#execute(context, fn)
}
}
export default ServerSideAuth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment