Skip to content Skip to sidebar Skip to footer

How To Make Express Routes Require Authentication By Default?

I've seen many examples of how to add an authentication middleware to certain routes that need to be restricted to logged-in users (implying that the default is to allow anyone to

Solution 1:

I would use: https://github.com/expressjs/session once the user is authenticated then you can check for valid sessions in your controller that handles the route of express.

Updated Answer

This is how I would do the control user logged

/**
 * Module dependencies
 */var express = require('express'),
  http = require('http'),
  session = require('express-session'),
  app = module.exports = express();

/**
 * Configuration
 */// all environments
app.set('port', process.env.PORT || 3000);
app.set('trust proxy', 1);
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: true
  }
}));


functioncheckUserLoggedIn(req, res, next) {
  return req.session;
}
/**
 * Routes to control by default is logged in with a regular expression
 */
app.get('/user/:use_id/*', function (req, res, next) {
  if (checkUserLoggedIn(req)) {
    console.log('User logged');
    next();
  } else {
    console.log('error');
  }
});
/**
 * User Home
 */
app.get('/user/:use_id/home/', function (req, res, next) {
  if (checkUserLoggedIn(req)) {
    console.log('User logged goes to home');
    next();
  } else {
    console.log('error');
  }
});


/**
 * Home for user that is actually logged
 */
app.get('/guest/dashboard', function (req, res, next) {
  console.log('This is guest dashboard');
});

/**
 * Home for user that is actually logged
 */
app.get('/guest/home', function (req, res, next) {
  console.log('This is guest home');
});


/**
 * Start Server
 */
http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});

Then run

$ node app.js

Go to browser and access http://localhost:3000/home

The regular expression you defined in to control '/*' is getting all the defaults routing and then is going to the next route that matches, thats /home.

This is one way to do it, may be there is a better and more clear way to fit the issue. In the regular expression you control what you mean with default routes and for each case particular.

Post a Comment for "How To Make Express Routes Require Authentication By Default?"