Skip to content

Instantly share code, notes, and snippets.

@mikaelkaron
Created August 4, 2023 12:54
Show Gist options
  • Save mikaelkaron/7b81d3f53cd5b5354e092c348a4ceb12 to your computer and use it in GitHub Desktop.
Save mikaelkaron/7b81d3f53cd5b5354e092c348a4ceb12 to your computer and use it in GitHub Desktop.
import { OIDC_AUTH_HANDLERS, OIDC_AUTH_USER } from '@elivery/plugins/openid-auth';
import { FastifyPluginAsync, RegisterOptions, RouteOptions } from 'fastify';
import fp from 'fastify-plugin';
export const authRoutePlugin: FastifyPluginAsync<RegisterOptions> = fp(
async (fastify, options) => await fastify.register(async fastify => {
const {
[OIDC_AUTH_HANDLERS]: { login, logout, verify, refresh }
} = fastify
const errorHandler: RouteOptions['errorHandler'] = (
error,
_request,
reply
) => reply
.type('text/html; charset=utf-8')
.send(`<!DOCTYPE html><script>window.parent?.postMessage(${JSON.stringify({
type: 'error',
error
})}, '*')</script>`)
const handler: RouteOptions['handler'] = async (request, reply) => reply
.status(!!request[OIDC_AUTH_USER] ? 200 : 401)
.type('application/json; charset=utf-8')
.send(request[OIDC_AUTH_USER]);
fastify
.route({
url: '/login',
method: 'GET',
preHandler: fastify.auth([login]),
handler
})
.route({
url: '/login/callback',
method: 'GET',
preHandler: fastify.auth([login, verify], { relation: 'and' }),
errorHandler,
handler: (request, reply) => reply
.type('text/html; charset=utf-8')
.send(`<!DOCTYPE html><script>window.parent?.postMessage(${JSON.stringify({
type: 'login',
principal: request[OIDC_AUTH_USER]
})}, '*')</script>`)
})
.route({
url: '/logout',
method: 'GET',
preHandler: fastify.auth([logout]),
handler
})
.route({
url: '/logout/callback',
method: 'GET',
preHandler: fastify.auth([logout, verify], { relation: 'and' }),
errorHandler,
handler: (_request, reply) => reply
.type('text/html; charset=utf-8')
.send(`<!DOCTYPE html><script>window.parent?.postMessage(${JSON.stringify({
type: 'logout'
})}, '*')</script>`)
})
.route({
url: '/refresh',
method: 'GET',
preHandler: fastify.auth([refresh, verify], { relation: 'and' }),
handler
})
.route({
url: '/whoami',
method: 'GET',
preHandler: fastify.auth([verify]),
handler
})
}, options),
{
fastify: '4.x',
name: '@elivery/auth/routes/openid-auth',
decorators: {
fastify: [OIDC_AUTH_HANDLERS],
request: [OIDC_AUTH_USER]
}
}
);
export default authRoutePlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment