Commit 45343d9b authored by Felix Kopp's avatar Felix Kopp 😴

Add optional authentication middleware

parent ab71bc39
/**
* @file User authentication middleware that does not return 401 when the user
* is not logged in.
* @author Felix Kopp <sandtler@sandtler.club>
*
* @license
* Copyright (c) 2019 Felix Kopp <sandtler@sandtler.club>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const jwt = require('jsonwebtoken');
const jwtSecret = require('../../config/app.js').signingKey;
const errorCodes = require('../io/error-codes.js');
module.exports = (req, res, next) => {
try {
const authHeader = req.headers.authentication.split(' ');
if (authHeader[0] !== 'Bearer' || authHeader.length !== 2) {
throw new Error();
}
const decoded = jwt.verify(authHeader[1], jwtSecret);
req.authData = decoded;
} catch (error) {
req.authData = null;
}
next();
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment