Git Product home page Git Product logo

connect-ensure-login's Introduction

connect-ensure-login

This middleware ensures that a user is logged in. If a request is received that is unauthenticated, the request will be redirected to a login page. The URL will be saved in the session, so the user can be conveniently returned to the page that was originally requested.

Install

$ npm install connect-ensure-login

Usage

Ensure Authentication

In this example, an application has a settings page where preferences can be configured. A user must be logged in before accessing this page.

app.get('/settings',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('settings', { user: req.user });
  });

If a user is not logged in when attempting to access this page, the request will be redirected to /login and the original request URL (/settings) will be saved to the session at req.session.returnTo.

Log In and Return To

This middleware integrates seamlessly with Passport. Simply mount Passport's authenticate() middleware at the login route.

app.get('/login', function(req, res) {
  res.render('login');
});

app.post('/login', passport.authenticate('local', { successReturnToOrRedirect: '/', failureRedirect: '/login' }));

Upon log in, Passport will notice the returnTo URL saved in the session and redirect the user back to /settings.

Step By Step

If the user is not logged in, the sequence of requests and responses that take place during this process can be confusing. Here is a step-by-step overview of what happens:

  1. User navigates to GET /settings
    • Middleware sets session.returnTo to /settings
    • Middleware redirects to /login
  2. User's browser follows redirect to GET /login
    • Application renders a login form (or, alternatively, offers SSO)
  3. User submits credentials to POST /login
    • Application verifies credentials
    • Passport reads session.returnTo and redirects to /settings
  4. User's browser follows redirect to GET /settings
    • Now authenticated, application renders settings page

Tests

$ npm install --dev
$ make test

Build Status

Credits

License

The MIT License

Copyright (c) 2012-2013 Jared Hanson <http://jaredhanson.net/>

connect-ensure-login's People

Contributors

jaredhanson avatar leider avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

connect-ensure-login's Issues

What happens if the user doesn't logs in?

If the user doesn't want to log in and goes to another section of the web, when he/she finally logs in the app will send him/her to the old url that req.session.returnTo has stored.

Can I ensure login in non-GET requests?

I've been using this package in a CRUD application, and it's very easy to get working to ensure that a user is not GET'ing what they shouldn't. However, I also need to protect POST and PUT methods.

This is (part) of my code:

const ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn("/login")

// a get method
app.get('/api/trips',       ensureLoggedIn, (req, res) => handleRetrieve("trips"      , req, res))

// and a post one
app.post('/api/trips',      ensureLoggedIn, (req, res) => handleInsertion("trips", req, res))

Now, may be this is obvious, but the result I'm getting is that the POST request is being redirected to "/login", but that is just a 404 (I don't have a POST /login; /login is a GET, the login info is POSTed to /api/login).

Is connect-ensure-login not intended to protect access to other than GET requests? Am I using it wrong?

Thanks a lot.

how to ensure if the user is logged in with twitter only

what if there are multiple options like facebook, twitter, google and local; for the user to login to our app and on a specific route we want to check if the user is logged in with twitter. how can i ensure if the user is authenticated and logged in with twitter. if the user is not logged in with twitter then i want the user to first login with twitter and then redirect to the same page again

Do not redirect

How can I check for login and simply output a 401 code instead of a redirect? I could redirect to a URL that always is HTTP 401, but that's impractical.

May I know where i can visualize { message: 'Incorrect username.' } ?

I am new in Node.js and express. and have some confusion on this configuration.
where can I visualize message in this verify callback?
i have used the middleware connect-flash, but nothing is shown up too.

app.use(require('connect-flash')());
passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

Cannot find module 'ensureLoggedIn'

Hi,
This is great - exactly what I need...

I'm using this with passport-facebook, twitter, etc.

here's my code:
var ensureLoggedIn = require('ensureLoggedIn');
....
....
app.get('/settings', ensureLoggedIn('/login'), function (req, res) {
....

I'm getting the following error...

module.js:340
throw err;
^
Error: Cannot find module 'ensureLoggedIn'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (...\routes.js:23:22)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)

Process finished with exit code 8

Then - I changed the require to 'connect-ensure-login' - but then I'm getting the following error:
app.get('/settings', ensureLoggedIn('/login'), function (req, res) {
^
TypeError: object is not a function
at module.exports (...\routes.js:411:30)
at Object. (...\node-bin\server.bin.js:55:28)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3

Process finished with exit code 8

I must be doing something very basic wrong... can you please help?

Thanks,
Jatin

Do not manage to be automatically redirected to original URL

I'm using the following middleware for the oauth/authorize route:

app.get('/oauth/authorize',
  login.ensureLoggedIn(),
  server.authorize(function(clientId, redirectURI, done) {

  Client.findOne({clientId: clientId}, function(err, client) {
    if (err) { return done(err); }
    if (!client) { return done(null, false); }
    if (client.redirectURI != redirectURI) { return done(null, false); }
    return done(null, client, client.redirectURI);
  });
}),
server.errorHandler(),
function(req, res) {
  res.render('dialog', { transactionID: req.oauth2.transactionID,
                         user: req.user,
                         client: req.oauth2.client
  });
}
);

The connection URL is the following one:

http://localhost:1337/oauth/authorize?client_id=O3UTGRFNI1&response_type=code&redirect_uri=http://localhost:1339&scope=http://localhost:1337

When the user is not logged, he is redirected towards the login page but when he logs he is redirected towards the index page (instead of being redirected towards the above URL). Any idea why this is happening ? I've certainly missed something but I cannot figure out what (probably linked to returnTo).

I've also set up a complete example in the following question:
http://stackoverflow.com/questions/25833533/secure-nodejs-app-with-oauth2-not-automatically-redirected-to-allow-deny-page

how to set redirectTo option?

Howdy, thanks for this great thing,

the top of my file looks something like this

var express = require('express')
var bodyParser = require('body-parser')
.. etc
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn

and then in use:

app.get('/xx', ensureLoggedIn('/loginpage'), (request, response) => { response.render('xx.pug') })

What do I do at the top of the file

to set the redirectTo option to '/loginpage' ? thanks! :)

Doesn't work with GoogleStrategy

  1. User navigates to GET /settings
    • Middleware sets session.returnTo to /settings
    • Middleware redirects to /login
  2. User's browser follows redirect to GET /login
    • Application offers Google
  3. User goes to Google auth endpoint (GET /auth/google)
    • GoogleStategy redirects to google login form
  4. User submits credentials to google login form
    • Google verifies credentials and redirects to GET /auth/google/return

Application crashes with stacktrace:

Failed to verify assertion (message: Invalid association handle)
    at Strategy.authenticate.identifier (.../passport-google/node_modules/passport-openid/lib/passport-openid/strategy.js:184:36)
    at _verifyAssertionData (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1045:12)
    at _verifyAssertionAgainstProvider (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1170:14)
    at _checkSignatureUsingAssociation (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1221:14)
    at Object.openid.loadAssociation (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:111:5)
    at _checkSignatureUsingAssociation (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1213:10)
    at _checkSignature (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1203:5)
    at _verifyAssertionAgainstProvider (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1166:3)
    at _verifyDiscoveredInformation (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:1137:16)
    at openid.discover (.../passport-google/node_modules/passport-openid/node_modules/openid/openid.js:660:7)

Is it possible to ignore the authentication for certain URL?

I want to access a page directly without authentication, but the request should pass through the connect-ensure-login middleware. Is that possible?

var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn()

router.get('/direct', ensureLoggedIn, function(req, res, next) {
res.render('direct');
});

How "is logged in" is not documented.

The documentation should clarify how it's determined if the user is already logged in or not.

The answer is that the user is considered logged in if either req.isAuthenticated or req.isAuthenticated() returns true.

What is req.isAuthenticated ?

Why you check

if (!req.isAuthenticated || !req.isAuthenticated()) {
if (setReturnTo && req.session) {
req.session.returnTo = req.originalUrl || req.url;
}
return res.redirect(url);
}

but not check only req.isAuthenticated()

if ( !req.isAuthenticated()) {
if (setReturnTo && req.session) {
req.session.returnTo = req.originalUrl || req.url;
}
return res.redirect(url);
}

Unknown how to get reference to ensureLoggedIn - improve README.md

Currently the README.md documentation skips from

$ npm install connect-ensure-login

...directly to...

app.get('/settings',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('settings', { user: req.user });
  });

...without indicating how the reference to 'ensureLoggedIn' can be acquired.

I'd expect a require statement, and a var declaration to make this clearer.

How to set this Middleware for all pages but excluding few path?

How can I set this middleware at the top level but excluding some path. I mean, i wanna use this for all the pages inside starts with /blog like this

app.use("/blog", ensureLoggedIn("/login")

But I want to exclude some pages like /blog/, /blog/title-of-the-blog and use it for all other pages after /blog/ r there any ways to achieve it without adding this middleware in each and every path.

successReturnToOrRedirect option is not working

Everything is working fine in the package with my app except successReturnToOrRedirect option not working, redirect me to a wrong url,

This is my login

router.post('/login', passport.authenticate('local', { successReturnToOrRedirect: '/', failureRedirect: '/login' }));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.