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:
11
seasoned_api/src/webserver/middleware/mustBeAuthenticated.js
Normal file
11
seasoned_api/src/webserver/middleware/mustBeAuthenticated.js
Normal 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;
|
||||||
22
seasoned_api/src/webserver/middleware/tokenToUser.js
Normal file
22
seasoned_api/src/webserver/middleware/tokenToUser.js
Normal 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;
|
||||||
Reference in New Issue
Block a user