Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save freelancing-solutions/f24d41910fca28ec997e63459f1f4ae7 to your computer and use it in GitHub Desktop.
Save freelancing-solutions/f24d41910fca28ec997e63459f1f4ae7 to your computer and use it in GitHub Desktop.
API Key based auth middle ware for node.js and express API
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const config = require("config");
const routes = require('./routes');
const PORT = process.env.PORT || 3030;
// const redis = require("redis");
// const cache_config = { redis: process.env.REDIS_URL || config.get("redis") };
// const cache = require("express-redis-cache")({
// client: redis.createClient(cache_config.redis)
// });
//
// cache.on("connected", () => {
// // ....
// console.log("cache connected");
// });
// cache.on("disconnected", () => {
// // ....
// console.log("cache disconneted");
// });
// create express app
const app = express();
// parse reqs of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse reqs of content-type - application/json
app.use(bodyParser.json());
// adding cors
app.use(cors());
app.get('/',(req,res) => {
res.status(200).json({message:'welcome to sa-sms crud api'});
});
/*******
* API Key Based Authorization
*******/
const authorize = (req,res,next) => {
const results = {status: false, payload : {}, error:{message: 'error user not authorized'}}
try{
const internal_key = process.env.INTERNAL_KEY || config.get('INTERNAL_KEY');
const route = req.originalUrl;
const routes = route.split('/');
const key = String(routes[routes.length - 1]).trim();
res.locals.api_call = String(routes[routes.length - 2]).trim();
if (internal_key === key){
res.locals.authorized = true;
}else{
res.locals.authorized = false;
return res.status(401).json(results);
}
}catch(error){
res.locals.authorized = false;
results.status = false;
results.error = {message: 'general error : {}'.format(error)}
return res.status(200).json(results);
}
next()
};
app.use(authorize);
app.use('/api/v1/sms/', routes.sms_router);
// listening for requests
app.listen(PORT).on('listening', () => {
console.log(`sa sms rest api running on port : ${PORT} `);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment