Implement both tokens and rate limiting to API

Closes #141, but still needs better UI on failure
This commit is contained in:
Stefan Zermatten
2017-10-12 16:24:12 +02:00
parent 1d2de197a4
commit b308595dac
6 changed files with 161 additions and 4 deletions

View File

@@ -4,7 +4,11 @@ Router.map(function() {
where: "server",
action: function() {
this.response.setHeader("Content-Type", "application/json");
this.response.end(vMixCharacter(this.params._id));
var query = this.params.query;
var key = query && query.key;
ifKeyValid(key, this.response, () =>
this.response.end(vMixCharacter(this.params._id))
);
},
});
this.route("vmixParty", {
@@ -12,7 +16,38 @@ Router.map(function() {
where: "server",
action: function() {
this.response.setHeader("Content-Type", "application/json");
this.response.end(vMixParty(this.params._id));
var query = this.params.query;
var key = query && query.key;
ifKeyValid(key, this.response, () =>
this.response.end(vMixParty(this.params._id))
);
},
});
});
var ifKeyValid = function(apiKey, response, callback){
if (!apiKey){
response.writeHead(403, "You must use an api key to access this api");
response.end();
} else if (!isKeyValid(apiKey)){
response.writeHead(403, "API key is invalid");
response.end();
} else if (isRateLimited(apiKey)){
response.writeHead(429, "Too many requests");
response.end();
} else {
rateLimiter.increment({apiKey})
callback();
}
};
var isKeyValid = function(apiKey){
return !!Meteor.users.findOne({apiKey});
};
var rateLimiter = new RateLimiter();
rateLimiter.addRule({apiKey: String}, 2, 10000);
var isRateLimited = function(apiKey){
return !rateLimiter.check({apiKey}).allowed;
};