It is crucial to secure REST endpoints that contain sensitive information accessible only to certain users. The common methods of securing such endpoints include passing an API token, using oAuth tokens, or a login cookie. If userA should not have access to collectionB, it is necessary to perform a validation check within the resource and return an appropriate error code to the browser.
One commonly used error code for unauthorized access on websites is 401: Unauthorized
. Here is a straightforward example:
router.get("/word/:collection/:language/:amount", function(req, res) {
if ( !hasAccess(req.params.userToken) )
{
return res.send(401, {success: false, message: 'no permission'});
}
var collection = req.params.collection,
var language = req.params.language,
var amount = req.params.amount;
return getItems(req, res, collection, language, amount);
}
Edit: Upon revisiting your question, I now understand that the user may need access to both collections at some point. Even in this scenario, server-side validation is still necessary. Here's another example involving quizzes and answers:
router.get("/quiz/finish/:id", function(req, res) {
//Record that this user has completed this quiz
return recordQuizAnswers(req.params.userToken, req.params.quizAnswers);
}
router.get("/quiz/answers/:id", function(req, res) {
//Has this user completed this quiz?
if ( !hasUserTakenQuiz(req.params.userToken) )
{
return res.send(401, {success: false, message: 'Trying to access answers without completing quiz? Cheater...'});
}
return getQuizAnswers(req.params.id);
}
Edit 2: Based on your comment, here is another solution you can consider. Utilize UUID's for IDs rather than auto-incrementing numbers. This approach will prevent users from manipulating IDs to access different quizzes.