blob: c6992d3145474101d53e604f2120fb3f04fe548b [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';
Misha Krieger-Raynauld2f5d1ce2022-10-23 21:13:33 -040019import { HttpStatusCode } from 'jami-web-common';
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040020import { jwtVerify } from 'jose';
21import { Container } from 'typedi';
22
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040023import { 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) {
Misha Krieger-Raynauld2f5d1ce2022-10-23 21:13:33 -040030 res.status(HttpStatusCode.Unauthorized).send('Missing Authorization header');
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040031 return;
32 }
33
34 const token = authorizationHeader.split(' ')[1];
35 if (token === undefined) {
Misha Krieger-Raynauld2f5d1ce2022-10-23 21:13:33 -040036 res.status(HttpStatusCode.BadRequest).send('Missing JSON web token');
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040037 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-Raynauld2f5d1ce2022-10-23 21:13:33 -040048 res.sendStatus(HttpStatusCode.Unauthorized);
Misha Krieger-Raynauld242560f2022-10-16 19:59:58 -040049 }
50}