New tokenToUser middleware checks both header and cookie for Auth token
This commit is contained in:
32
seasoned_api/src/webserver/middleware/reqTokenToUser.js
Normal file
32
seasoned_api/src/webserver/middleware/reqTokenToUser.js
Normal 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;
|
||||
@@ -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;
|
||||
Reference in New Issue
Block a user