|
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. |
@@ -67,9 +68,40 @@ export function createBaseHandler() { |
67 | 68 |
|
68 | 69 | // Add session to request |
69 | 70 | baseHandler.use(async (req, res, next) => { |
70 | | - const token = await getToken({ req }) |
71 | | - if (token) { |
72 | | - req.session = { user_id: token.userId || token.sub } |
| 71 | + /** Handle authorization using either Bearer token auth or |
| 72 | + * using the next-auth session |
| 73 | + */ |
| 74 | + if (req.headers.authorization) { |
| 75 | + // introspect the token |
| 76 | + const [type, token] = req.headers.authorization.split(' ') |
| 77 | + if (type !== 'Bearer') { |
| 78 | + throw Boom.badRequest( |
| 79 | + 'Authorization scheme not supported. Only Bearer scheme is supported' |
| 80 | + ) |
| 81 | + } else { |
| 82 | + const result = await fetch(`${process.env.AUTH_URL}/api/introspect`, { |
| 83 | + method: 'POST', |
| 84 | + headers: { |
| 85 | + Accept: 'application/json', |
| 86 | + 'Content-Type': 'application/json', |
| 87 | + }, |
| 88 | + body: JSON.stringify({ |
| 89 | + token: token, |
| 90 | + }), |
| 91 | + }).then((response) => { |
| 92 | + return response.json() |
| 93 | + }) |
| 94 | + if (result && result.active) { |
| 95 | + req.session = { user_id: result.sub } |
| 96 | + } else { |
| 97 | + throw Boom.badRequest('Invalid token') |
| 98 | + } |
| 99 | + } |
| 100 | + } else { |
| 101 | + const token = await getToken({ req }) |
| 102 | + if (token) { |
| 103 | + req.session = { user_id: token.userId || token.sub } |
| 104 | + } |
73 | 105 | } |
74 | 106 | next() |
75 | 107 | }) |
|
0 commit comments