|
1 | 1 | import nc from 'next-connect' |
2 | 2 | import logger from '../lib/logger' |
3 | 3 | import { getToken } from 'next-auth/jwt' |
| 4 | +import Boom from '@hapi/boom' |
4 | 5 |
|
5 | 6 | /** |
6 | 7 | * This file contains the base handler to be used in all API routes. |
@@ -57,9 +58,40 @@ export function createBaseHandler() { |
57 | 58 |
|
58 | 59 | // Add session to request |
59 | 60 | baseHandler.use(async (req, res, next) => { |
60 | | - const token = await getToken({ req }) |
61 | | - if (token) { |
62 | | - req.session = { user_id: token.userId || token.sub } |
| 61 | + /** Handle authorization using either Bearer token auth or |
| 62 | + * using the next-auth session |
| 63 | + */ |
| 64 | + if (req.headers.authorization) { |
| 65 | + // introspect the token |
| 66 | + const [type, token] = req.headers.authorization.split(' ') |
| 67 | + if (type !== 'Bearer') { |
| 68 | + throw Boom.badRequest( |
| 69 | + 'Authorization scheme not supported. Only Bearer scheme is supported' |
| 70 | + ) |
| 71 | + } else { |
| 72 | + const result = await fetch(`${process.env.AUTH_URL}/api/introspect`, { |
| 73 | + method: 'POST', |
| 74 | + headers: { |
| 75 | + Accept: 'application/json', |
| 76 | + 'Content-Type': 'application/json', |
| 77 | + }, |
| 78 | + body: JSON.stringify({ |
| 79 | + token: token, |
| 80 | + }), |
| 81 | + }).then((response) => { |
| 82 | + return response.json() |
| 83 | + }) |
| 84 | + if (result && result.active) { |
| 85 | + req.session = { user_id: result.sub } |
| 86 | + } else { |
| 87 | + throw Boom.badRequest('Invalid token') |
| 88 | + } |
| 89 | + } |
| 90 | + } else { |
| 91 | + const token = await getToken({ req }) |
| 92 | + if (token) { |
| 93 | + req.session = { user_id: token.userId || token.sub } |
| 94 | + } |
63 | 95 | } |
64 | 96 | next() |
65 | 97 | }) |
|
0 commit comments