Koa adapter
WIPKoa 2+ middleware. Composes naturally with koa-router and koa-bodyparser.
Setup
import Koa from 'koa'
import Router from '@koa/router'
import bodyParser from 'koa-bodyparser'
import {
authKoaProviderBegin,
authKoaSession,
authKoaSignIn,
authKoaSignOut,
} from '@gentleduck/auth/server/koa'
import { auth } from './lib/auth'
const app = new Koa()
const router = new Router()
app.use(bodyParser())
router.post('/auth/signin', authKoaSignIn(auth))
router.post('/auth/signout', authKoaSignOut(auth))
router.get('/auth/session', authKoaSession(auth))
router.post('/auth/providers/:providerId/begin', (ctx) =>
authKoaProviderBegin(auth, ctx.params.providerId)(ctx),
)
// OAuth callbacks reuse the sign-in handler.
router.get('/auth/google/callback', authKoaSignIn(auth))
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)
Resolving sessions
import { AuthError } from '@gentleduck/auth/core'
router.get('/api/me', async (ctx, next) => {
const auth_ctx = await auth.resolveSession(ctx.req)
if (!auth_ctx) {
ctx.status = 401
ctx.body = { code: 'AUTH/UNAUTHENTICATED' }
return
}
ctx.body = auth_ctx.identity
})
Error handling
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
if (err instanceof AuthError) {
ctx.status = err.status
ctx.body = err.toJSON()
return
}
throw err
}
})