New tokenToUser middleware checks both header and cookie for Auth token

This commit is contained in:
2022-03-06 10:17:56 +01:00
parent 31b0c998a8
commit 4f7a22fff1
2 changed files with 32 additions and 23 deletions

View File

@@ -0,0 +1,32 @@
/* eslint-disable no-param-reassign */
const configuration = require("src/config/configuration").getInstance();
const Token = require("src/user/token");
const secret = configuration.get("authentication", "secret");
// Token example:
// curl -i -H "Authorization:[token]" localhost:31459/api/v1/user/history
const reqTokenToUser = (req, res, next) => {
const cookieAuthToken = req.cookies.authorization;
const headerAuthToken = req.headers.authorization;
if (cookieAuthToken || headerAuthToken) {
try {
const token = Token.fromString(
cookieAuthToken || headerAuthToken,
secret
);
req.loggedInUser = token.user;
} catch (error) {
req.loggedInUser = undefined;
}
} else {
// guest session
console.debug("No auth token in header or cookie.");
}
next();
};
module.exports = reqTokenToUser;

View File

@@ -1,23 +0,0 @@
/* eslint-disable no-param-reassign */
const configuration = require('src/config/configuration').getInstance();
const secret = configuration.get('authentication', 'secret');
const Token = require('src/user/token');
// Token example:
// curl -i -H "Authorization:[token]" localhost:31459/api/v1/user/history
const tokenToUser = (req, res, next) => {
const rawToken = req.headers.authorization;
if (rawToken) {
try {
const token = Token.fromString(rawToken, secret);
req.loggedInUser = token.user;
} catch (error) {
req.loggedInUser = undefined;
}
}
next();
};
module.exports = tokenToUser;