I have set up my front-end with an interceptor that always adds an Authorization
header if a JWT token
exist.
I have 2 API's, one is used to check authorization, the other one is used to handle any other data request (this is the one I'm working on).
What I want to achieve in my data API is the following:
Create some kind of guard(?) which I can place around certain api routes which checks if a Authorization
header is present. Then it needs to do a call to a different API to check if the token is valid. If this fails, it returns an error, otherwise it continues to do the wanted request.
I 'm new to node, and I don't know the correct and most efficient way to do this. I don't have enough knowledge, so I tried googling it, but with no result.
I'm not asking you guys to write this for me, I'm just looking for ideas on how to do this, so I can research it more in depth, because right now I don't know what to look for or if this is even possible.
Thanks for your help!
EDIT: Here's how I currently handle a request
Route
/**
* Add survey for a participant
*
* URL: /participant/survey
* METHOD: POST
*/
router.post('/participant/survey', function(req, res) {
var bodyValidation = iValidator.json_schema(
schema.addSurvey,
req.body,
'survey'
);
if (bodyValidation.valid == false) {
return res.status(422).send(bodyValidation.errorMessage);
}
participantService
.addSurvey(req.body)
.then(data => {
res.status(200).send({ success: true, survey: data });
})
.catch(err => {
res.status(422).send(err);
});
});
Service
function addSurvey(survey) {
return new Promise((resolve, reject) => {
participantModel
.addSurvey(survey)
.then(data => {
survey.id = data.insertId;
resolve(survey);
})
.catch(err => {
reject(err);
});
});
}
Model
function addSurvey(survey) {
return new Promise((resolve, reject) => {
db.query(
'INSERT INTO ...',
(error, result) => {
if (error) {
dbFunc.connectionRelease;
reject(error);
} else {
dbFunc.connectionRelease;
resolve(result);
}
}
);
});
}