bernsie bernsie - 1 month ago 16
Node.js Question

How to do Authentication with Node.js and MEAN stack?

I am currently working on a text based game with a small team of developers. The game requires login and we are using the MEAN (MongoDB, Express, Angular, Node) Stack for the application codebase, however i am stuck on authentication, as a rails developer i am used to being able to drop in a gem and use the helpers available.

has anybody has any experience with MEAN and Authentication?

Answer

the MEAN stack by linnovate uses Passport.js for its authentication. Passport uses different strategies for authentication. One of these strategies is a username and password pair, which they call LocalStrategy.

Here is one of the samples from the Passportjs-Local Github Examples Page

Step 1: Require Passport

First you require the module after doing npm install passport

var passport = require('passport');

Step 2: Configure 'Verify' Function

Use the LocalStrategy within Passport. Strategies in passport require a verify function, which accept credentials (in this case, a username and password), and invoke a callback with a user object. In the real world, this would query a database; however, in this example we are using a baked-in set of users.

passport.use(new LocalStrategy(
  function(username, password, done) {

  // Find the user by username.  If there is no user with the given
  // username, or the password is not correct, set the user to `false` to
  // indicate failure and set a flash message.  Otherwise, return the
  // authenticated `user`.

  findByUsername(username, function(err, user) {
      if (err) { return done(err); }
      if (!user) { 
          return done(null, false, { message: 'Unknown user ' + username }); 
      }
      if (user.password != password) { 
          return done(null, false, { message: 'Invalid password' }); 
      }
        return done(null, user);
      })
    });
  }
));

Step 3: Initialize Passport on app

You need to tell Express that you will be using passport and that it will be managing sessions for you. This is done by using the app.use() during app configuration.

app.use(passport.initialize());
app.use(passport.session());

Step 4: Configure Middleware on the login URI

Next we need to create a method that will accept when a user tries to login to the app using by POST-ing to a specific URI. It will look like this.

// POST /login
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
//
//   curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
    res.redirect('/');
  });

Step 5: Set up Sessions You may have to create your own serialization for User objects that are being stored in the sessions. That is done with the following

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});