Misha Krieger-Raynauld | 242560f | 2022-10-16 19:59:58 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Affero General Public License as |
| 6 | * published by the Free Software Foundation; either version 3 of the |
| 7 | * License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Affero General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Affero General Public |
| 15 | * License along with this program. If not, see |
| 16 | * <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | import { NextFunction, Request, Response } from 'express'; |
Misha Krieger-Raynauld | 2f5d1ce | 2022-10-23 21:13:33 -0400 | [diff] [blame] | 19 | import { HttpStatusCode } from 'jami-web-common'; |
Misha Krieger-Raynauld | 242560f | 2022-10-16 19:59:58 -0400 | [diff] [blame] | 20 | import { jwtVerify } from 'jose'; |
| 21 | import { Container } from 'typedi'; |
| 22 | |
Misha Krieger-Raynauld | 242560f | 2022-10-16 19:59:58 -0400 | [diff] [blame] | 23 | import { Vault } from '../vault.js'; |
| 24 | |
| 25 | export async function authenticateToken(req: Request, res: Response, next: NextFunction) { |
| 26 | const publicKey = Container.get(Vault).publicKey; |
| 27 | |
| 28 | const authorizationHeader = req.headers.authorization; |
| 29 | if (!authorizationHeader) { |
Misha Krieger-Raynauld | 2f5d1ce | 2022-10-23 21:13:33 -0400 | [diff] [blame] | 30 | res.status(HttpStatusCode.Unauthorized).send('Missing Authorization header'); |
Misha Krieger-Raynauld | 242560f | 2022-10-16 19:59:58 -0400 | [diff] [blame] | 31 | return; |
| 32 | } |
| 33 | |
| 34 | const token = authorizationHeader.split(' ')[1]; |
| 35 | if (token === undefined) { |
Misha Krieger-Raynauld | 2f5d1ce | 2022-10-23 21:13:33 -0400 | [diff] [blame] | 36 | res.status(HttpStatusCode.BadRequest).send('Missing JSON web token'); |
Misha Krieger-Raynauld | 242560f | 2022-10-16 19:59:58 -0400 | [diff] [blame] | 37 | return; |
| 38 | } |
| 39 | |
| 40 | try { |
| 41 | const { payload } = await jwtVerify(token, publicKey, { |
| 42 | issuer: 'urn:example:issuer', |
| 43 | audience: 'urn:example:audience', |
| 44 | }); |
| 45 | res.locals.accountId = payload.id as string; |
| 46 | next(); |
| 47 | } catch (err) { |
Misha Krieger-Raynauld | 2f5d1ce | 2022-10-23 21:13:33 -0400 | [diff] [blame] | 48 | res.sendStatus(HttpStatusCode.Unauthorized); |
Misha Krieger-Raynauld | 242560f | 2022-10-16 19:59:58 -0400 | [diff] [blame] | 49 | } |
| 50 | } |