Why does Swagger endpoint require headers? - javascript

So I have added some swagger configuration in a routes folder like so:
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from '../swagger/swagger.json';
const router = express.Router();
router.get('/api-docs', swaggerUi.setup(swaggerDocument));
export { router as swaggerRouter }
Now there is an authentication process in the root app.ts file, but my understanding is if I add the swagger endpoint before it executes the authenticate logic, it should not ask for headers:
app.get('/', (req, res) => {
res.send('Howdy!');
});
app.use(swaggerRouter);
app.use(async (req, res, next) => {
const result = await auth.verifyAuth(req).catch((err) => {
return err;
});
if (result.httpCode == 200) {
res.locals.authResult = result
next()
} else {
res.send(result)
}
});
So the authentication logic from where verifyAuth comes from would make for a good middleware to target endpoints instead of the whole entire application, but to refactor it to work as such a middleware is a pain because the author wrote every function to depend on every other function.
And yet, if I add a random endpoint above that authenticate logic like:
router.get('/pingMe', (req, res) => {}
You can go to that one without being asked to provide headers.
What am I missing?
I literally removed the authentication logic and I am still unable to get to the swagger endpoint without being asked for headers.

Related

How to access application-level middleware from router?

I am trying to access my application-level middleware from router in a project generated with express application generator.
Middleware is used to query database with user ID received from router.
I feel like I'm missing something very simple (or fundamental) but can't get around the problem (this being my first Node.js project). So more than best practice I'm looking for a simple solution
I've tried using different app methods including post.
/app.js
var MyAppMidW = function (req, res, next) {
res.send(queryDB(req));
next()
}
app.use(MyAppMidW);
/routes/index.js
router.get("/dbquery", (req, res) => {
if (req.header('auth-header')) {
res.send(req.app.get.MyAppMidW(req.header('auth-header'))); //The problem
}
else {
res.send(req.app.get('defaultData')); //This works
}
});
Error messages include "$middleware is not a function" and "$middleware is not defined".
Solution
/app.js
app.MyAppMidW = function (req) {
queryDB(req);
}
/routes/index.js
router.get("/dbquery", (req, res) => {
if (req.header('auth-header')) {
req.app.MyAppMidW(req.header('auth-header'))); //Makes a database query
res.send(req.app.get('defaultData')); //Fetches database query result
}
else {
res.send(req.app.get('defaultData'));
}
});
If you do it like this
app.use(MyAppMidW);
Every request will query your db, and thats not what you want. I guess you use the MVC design pattern.
In your route folder you have something like this:
import appController from "../controllers/app.js"
router.get("/dbquery", appController.MyAppQuery)
And in your controllers folder you have your logic that querys the db
exports.MyAppQuery = (req, res){
//If u use mongodb for example
YourModel.find().then(data => {
res.json(data)
})
}
You need to call app.set("MyAppMidW", MyAppMidW) and then you can use get. Or do this inside the app.js file
app.MyAppMidW = function (req, res, next) {
res.send(queryDB(req));
next()
}
Then call it by req.app.get('MyAppMidW')(req.header('auth-header')) or req.app.MyAppMidW(req.header('auth-header')) inside the routes file.
But middleware is called automatically when you say app.use(MyAppMidW) the function is called by default on each request. So no need to call it explicitly inside the router function.

Express - Give a base path to res.redirect()

I'm not sure if this issue is something that can easily be fixed but here's the scenario. Say we have an express app() with a separate router().
const express = require('express')
const app = express()
const router = express.Router()
router.get('/', (req, res) => {
res.redirect('/bar')
})
app.use('/foo', router)
app.listen('8000')
Say we send a request to http://localhost:8000/foo/. I need the res.redirect('/bar') to redirect to http://localhost:8000/foo/bar instead of redirecting to http://localhost:8000/bar. The only key component here is that we cannot use redirects that are relative to the current route, so res.redirect('bar') would not be suitable for us.
Is there any way that we can override res.redirect()'s functionality to prepend /foo to every redirect? Also, I cannot modify every res.redirect() with req.originalUrl or anything similar.
Thanks a lot
Figured out how to do it with middleware -
app.use((req, res, next) => {
const redirector = res.redirect
res.redirect = function (url) {
url = '/foo' + url
redirector.call(this, url)
}
next()
})

Pass data between express router and middleware

I'm trying to write express middleware to check the validity of a JWT in the Authorization header. This seems quite easy but I don't want it to run on all routes (e.g. not on login/signup routers).
So, I'd like to specify in the router declaration that a route should require a valid token. E.g. something like this
const controllers = require('../controllers');
module.exports = (app) => {
app.post('/auth/signup', controllers.auth.signup.post);
app.post('/auth/login', controllers.auth.login.post);
app.get('/teams', controllers.teams.get, {requiresToken:true});
};
Except, .post and .get don't take a third parameter and the controller only takes (req,res,next) parameters so I can't really see a way of passing startic data for each route. I'm sure I'm missing something simple
This is how i created a middleware to pass the data into
module.exports = function(options) {
return function (req, res, next) {
//write your code here
// here you can access options variable
console.log(options.data)
next();
}
}
How you call that middleware is like this
app.use(middleware({'data' : 'Test'}));
To use on route basis
app.post('/userRegistration', middleware({'data' : 'Test'}), (req, res) => {});
You can exclude the auth subroute from this middleware using negative lookup regexp:
const controllers = require('../controllers');
module.exports = (app) => {
app.use(/\/((?!auth).)*/, yourJwtTokenValidatorMethod); // replace with your jwt token validator middleware
app.post('/auth/signup', controllers.auth.signup.post);
app.post('/auth/login', controllers.auth.login.post);
app.get('/teams', controllers.teams.get, {requiresToken:true});
};

Conditionally load router middleware Express JS

I have a Express JS code where I load a middleware that defines certain end-points on a router. The endpoints are specific to the user login and logout. I am adding a new authentication in which case I receive my auth token from a different service. When I receive the token from a different service I don't want those end-points to be loaded.
This is my server.js file
let app = express();
const authEndpoints = require('auth'); // this defines router endpoints
const alreadyAuth = require('checkHeaders'); // this middleware checks if request
// already has the auth headers and set res.locals.alreadyAuthenticated to true else false
app.use('/', alreadyAuth);
app.use('/',function(req, res, next) {
if(res.locals.alreadyAuthenticated === false)
next();
else {
console.log('authentication already exists skipping authEndpoints loading');
next('route');
}
}, authEndpoints); // login, logout
//continue here
app.use('/',nextMiddleware);
auth.js file
'use strict';
const express = require('express');
const path = require('path');
const router = express.Router();
router.get('/login', (req, res) => {
// some code
res.sendFile('login.html');
}
router.get('/logout', (req, res) => {
// some code
});
module.exports = router;
I see the console log that prints 'authentication already exists skipping authEndpoints loading' but the endpoints /login and /logout are still accessible.
Also when I comment the whole section
app.use('/',function(req, res, next) {
if(res.locals.alreadyAuthenticated === false)
next();
else {
console.log('authentication already exists skipping authEndpoints loading');
next('route');
}
}, authEndpoints); // login, logout
then the endpoints are not loaded.
Can someone please clarify If this not the way next('route') should be used.
From the top of my head, try adding a isAuthenticated (whatever is your equivalent to this) check to the /login and /logout routes code you listed. if it's authenticated, do a redirect to the protected page, else return the user the login form (or logout thing..). :)
I think that is better if you use the middleware "alreadyAuth" for every request, no matter the route:
app.use(alreadyAuth);
In this way you check the headers in every request for every route. In the "checkHeaders" middleware, you must use an if statement that redirect the user to the login page if is not authenticated, and use next() in the case that is already authenticated.
let checkHeaders = function(req, res, next) {
//some code that check headers
if(isAuthenticate === false) {
res.redirect("/login");
} else {
next();
};
}
Now, all the end points after this middleware are not accessible if the user is not authenticated. So you can use a logout endpoint, or whatever.
Good Luck!

Hot reloading with express and chokidar causes a http headers sent error when using multiple routes

I've been trying a variety of setups for hot reloading and one that I've come across is the https://github.com/glenjamin/ultimate-hot-reloading-example/. Modifying this boilerplate code as a starting point, I've come across the following problem in my server code:
// server.js
import chokidar from 'chokidar';
import express from 'express';
const app = express();
// this is the middleware for handline all of my routes
app.use(function (req, res, next) {
require('./server/index')(req, res, next);
// if I commented out any additional routes, the setup would work fine
require('./server/foo')(req, res, next);
require('./server/catch-all')(req, res, next);
});
//this watches the server folder for changes
const watcher = chokidar.watch('./server');
watcher.on('ready', function () {
watcher.on('all', function () {
console.log("Clearing /server/ module cache from server");
Object.keys(require.cache).forEach(function (id) {
if (/[\/\\]server[\/\\]/.test(id)) delete require.cache[id];
});
});
});
app.listen(3000, 'localhost', function (err) {
if (err) throw err;
const addr = this.address();
console.log('Listening at http://%s:%d', addr.address, addr.port);
});
The above is the server code that handles clearing the cache by watching for changes with the chokidar module. If I have just one route required inside the app.use middleware function (which listens for every incoming request), I can get it to work. However if have multiple routes, the following error occurs:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
This is a common issue posted on stack overflow, but all of the solutions I've come across and attempted haven't worked. My route files are as follows:
//index.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res, next) => {
res.send("greagrehgarhegrehuh").end();
return next('router');
});
module.exports = router;
//end of index.js
//foo.js
import express from 'express';
const router = express.Router();
router.get('/foo', (req, res, next) => {
res.send("foo").end();
return next('router');
});
module.exports = router;
//end of foo.js
//catch-all.js
import express from 'express';
const router = express.Router();
router.get('*', (req, res, next) => {
res.send("catch all").end();
return next('router');
});
module.exports = router;
// end of catch-all.js
All three routes do the same thing, bar the endpoint. So far I've explicitly called end on each to end the response, used return next('router') to skip the rest of the middleware functions and have also tried doing it without the above as well. Any ideas on what I'm missing here to get this working? Here's a github project that showcases the issue
https://github.com/RonanQuigley/express-chokidar-hot-reload
UPDATE
So I actually removed the next calls and seem to have almost got it working by doing the following:
app.use(function (req, res, next) {
require('./server/index')(req, res, next);
require('./server/foo')(req, res, next);
});
// a second app.use middleware, that does the same
// as the catch all // * router.get from my original post
app.use(function (req, res, next) {
app.get('*', (req, res) => res.send('catch all'));
})
However, I can't use this second app.use with another require call to a file with an express router like the others. So it seems that express runs through the middleware stack, reaches the * and tries to set the header twice.
The reason I need the * is normally if a user requests an endpoint that doesn't exist, Node correctly shows up with cannot GET/. However, for some reason, with the setup I've outlined express will then crash. My workaround is using * at the end of the middleware stack and I'd just use a res.redirect to send the user back to wherever, but this causes the above issue I've outlined in my original post. So not sure how to get around that one.
So currently I have either:
1) Hot reloading works without the require for a router.get('*'), but when the user navigates to an endpoint that doesn't exist, express will crash.
2) Hot reloading works with the app.get('*') inside a second app.use call, but I can't then use a router to move this into a separate file.
Okay, so posting this solution up for my own future reference and in case somebody else stumbles into this problem.
After speaking with the express devs, it turns out that this is indeed possible with a combination of the following:
// you need to use comma separated routes
app.use(
dynamic('./server/index'),
dynamic('./server/foo')
);
// require the library at runtime and apply the req, res, next arguments
function dynamic(lib) {
return function (req, res, next) {
return require(lib).apply(this, arguments)
}
}
In the case of webpack, this would break it as you can't use require as an expression. So use the following to get around that:
function createRoutes(router) {
const dynamic = (lib) => {
return function (req, res, next) {
// let webpack generate a regex expression from this require
// if we don't you would get a critical dependency warning
// which would result in the routes not being found
return require("./src/" + lib + ".js").apply(this, arguments);
}
}
router.use(
dynamic('index'),
dynamic('foo'),
);
return router;
}
Let's step back a bit and talk about middleware.
Say you have a function which runs some kind of middleware.
const runMiddleware = (req, res, next) => {
console.log(`this will run everytime a HTTP request comes in`);
}
Then to use that middleware within express:
app.use(runMiddleware);
Every time any (GET, POST, DELETE, etc) request comes in, this function is run.
Essentially you are doing the same thing below - You are wrapping three (3) route calls with a single function. This function is calling all of these routes at once, hence res is actually being sent 3 times in a row in the example below:
app.use(function (req, res, next) { // runs every time any request comes in
require('./server/index')(req, res, next); // res sent, ok
require('./server/foo')(req, res, next); // res sent, err
require('./server/catch-all')(req, res, next); // res sent, err
});
Here is a basic way of handling routes:
const index = require('./server/index');
const foo = require('./server/foo');
app.use('/', index);
app.use('/foo', foo);
// catch everything else
app.use(function (req, res) {
res.send('catch all');
})

Categories

Resources