Created a middleware for requests that checks for a token in the Authentication field in the header and verifies that the token is valid for a user.

This commit is contained in:
2017-09-27 16:25:54 +02:00
parent 698d2d6072
commit a3de70e2da
2 changed files with 33 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
const mustBeAuthenticated = (req, res, next) => {
if (req.loggedInUser === undefined) {
return res.status(401).send({
success: false,
error: 'You must be logged in.',
}); }
return next();
};
module.exports = mustBeAuthenticated;

View File

@@ -0,0 +1,22 @@
/* 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;