Files
DiceCloud/app/imports/server/rest/middleware/authenticateUserByToken.js
Stefan Zermatten 359f18988c Account functionality extended, API authentication implemented
- Can now add a second email address to your account and delete one of 
your email addresses
- Reset password now works
- Resetting the password of an account without a password set will set 
one
- Email templates overhauled
- Login tokens limited to close previously devastating ($800 database 
bill) security hole
- Login with REST API now works
- Once logged in, authentication of API calls with token works
- Creatures can now be fetched using the API
2022-02-10 19:02:18 +02:00

58 lines
1.5 KiB
JavaScript

var Fiber = Npm.require('fibers');
import { RestMiddleware } from 'meteor/simple:json-routes';
/**
* SimpleRest middleware for validating a Meteor.user's login token
*
* This middleware must be processed after the request.token has been set to a
* valid login token for a Meteor.user account (from a separate layer of
* middleware). If authentication is successful, the request.userId will be set
* to the ID of the authenticated user. An invalid token will result in a error.
*
* @middleware
*/
const authenticateMeteorUserByToken =
function (req, res, next) {
Fiber(function () {
let userId;
try {
userId = getUserIdFromAuthToken(req.authToken);
} catch (e){
RestMiddleware.handleErrorAsJson(e, req, res, next);
return;
}
if (userId) {
req.userId = userId;
}
next();
}).run();
};
/**
* Retrieves the ID of the Meteor.user that the given auth token belongs to
*
* @param token An unhashed auth token
* @returns {String} The ID of the authenticated Meteor.user, or null if token
* is invalid
*/
function getUserIdFromAuthToken(token) {
if (!token) {
return null;
}
var user = Meteor.users.findOne({
'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(token),
});
if (user) {
return user._id;
} else {
const error = new Meteor.Error('Permission denied',
'Invalid authentication token');
error.statusCode = 403;
throw error;
}
}
export default authenticateMeteorUserByToken;