blob: fad416587dc8e40ef489e2414648116701bfeab7 [file] [log] [blame]
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -04001/*
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 */
18import { NextFunction, Request, Response } from 'express';
19import { jwtVerify } from 'jose';
20import { Container } from 'typedi';
21
22import { StatusCode } from '../constants.js';
23import { Vault } from '../vault.js';
24
25export 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) {
30 res.status(StatusCode.UNAUTHORIZED).send('Missing Authorization header');
31 return;
32 }
33
34 const token = authorizationHeader.split(' ')[1];
35 if (token === undefined) {
36 res.status(StatusCode.BAD_REQUEST).send('Missing JSON web token');
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) {
48 res.sendStatus(StatusCode.UNAUTHORIZED);
49 }
50}