Advertisement
okpalan

express-quota

Nov 9th, 2023 (edited)
534
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.03 KB | Source Code | 0 0
  1. var express = require('express');
  2. var app = express();
  3. const api= require('./api');
  4.  
  5. var apiKey = 'myapikey';
  6. var apiSecret = 'myapisecret';
  7.  
  8. app.use(function (req, res, next) {
  9.   // check for API key in header
  10.   if (!req.headers.hasOwnProperty('x-api-key')) {
  11.     return res.status(401).json({
  12.       error: 'No API key provided'
  13.     });
  14.   }
  15.  
  16.   // verify API key
  17.   if (req.headers['x-api-key'] !== apiKey) {
  18.     return res.status(401).json({
  19.       error: 'Invalid API key'
  20.     });
  21.   }
  22.  
  23.   // check for API secret in header
  24.   if (!req.headers.hasOwnProperty('x-api-secret')) {
  25.     return res.status(401).json({
  26.       error: 'No API secret provided'
  27.     });
  28.   }
  29.  
  30.   // verify API secret
  31.   if (req.headers['x-api-secret'] !== apiSecret) {
  32.     return res.status(401).json({
  33.       error: 'Invalid API secret'
  34.     });
  35.   }
  36.  
  37.   next();
  38. });
  39.  
  40. // rate limit middleware
  41. app.use(function (req, res, next) {
  42.   // check for rate limit header
  43.   if (!req.headers.hasOwnProperty('x-rate-limit')) {
  44.     return res.status(429).json({
  45.       error: 'No rate limit provided'
  46.     });
  47.   }
  48.  
  49.   // verify rate limit
  50.   if (req.headers['x-rate-limit'] !== '60') {
  51.     return res.status(429).json({
  52.       error: 'Invalid rate limit'
  53.     });
  54.   }
  55.  
  56.   // check for rate limit remaining header
  57.   if (!req.headers.hasOwnProperty('x-rate-limit-remaining')) {
  58.     return res.status(429).json({
  59.       error: 'No rate limit remaining provided'
  60.     });
  61.   }
  62.  
  63.   // verify rate limit remaining
  64.   if (req.headers['x-rate-limit-remaining'] === '0') {
  65.     return res.status(429).json({
  66.       error: 'Rate limit exceeded'
  67.     });
  68.   }
  69.  
  70.   next();
  71. });
  72.  
  73. // your API routes go here
  74. app.use('/api', api);
  75.  
  76. // usage:
  77. // download:
  78. // https://github.com/okpalan/express-quota
  79. // curl -X POST -H "x-api-key: myapikey" -H "x-api-secret: myapisecret" -H "x-rate-limit: 60" -H "x-rate-limit-remaining: 59" -H "Content-Type: application/json" -d '{"name": "John"}' http://localhost:3000/api/users
  80.  
  81.  
  82. console.log("Node server running on port 3000");
  83. app.listen(3000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement