Created
February 4, 2022 16:45
-
-
Save rickyalmeidadev/b753f9499264663d14d256e91446de0b to your computer and use it in GitHub Desktop.
Server-side authentication higher order functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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