Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Login process with passport module in nodejs

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 770
    Comment on it

    Welcome to FindNerd. Today we are going to point out the steps for login process in nodejs. In nodejs we use passport and passport-local modules for authentication. Passport works with express module. Passport process the request to authenticate and then provides hooks to manage the authentication which can be succeed or fail. You can install these modules by using below commands.

     

    npm install --save passport
    npm install --save passport-local

     

    Passport plays with Strategies to authenticate the request. Here we will use the LocalStrategy for authentication. There are more than three hundred strategies available like Local, OpenID, BrowserID, Facebook, Twitter etc

    Passport uses the persistent login sessions. Sessions are necessary for browser applications. We can simply pass the details if we are using our application as API. Now we are going to explain how we can use this module in login process. Please have a look.

     

    //auth.js
    
    var passport = require('passport'),
    	LocalStrategy = require('passport-local').Strategy;
    
    passport.use(new LocalStrategy(
    	function(username, password, done) {
    		if (username === 'findnerd' && password === 'tonk379') {
    			return done(null, {username: 'admin'});
    		}
    
    		return done(null, false);
    	}
    ));
    
    passport.serializeUser(function(user, done) {
    	done(null, user.username);
    });
    
    passport.deserializeUser(function(username, done) {
    	done(null, {username: username});
    });
    
    module.exports = passport;
    

     

    We have created a new file auth.js. It is a custom module for authentication. In first two lines we have loaded the passport and passport-local modules. After that we are using use function to set the LocalStrategy. In this we are checking username, password and returning  done function. If user is authorized then we are passing username in done function. If not then we are passing false. We are also calling serializeUser as well as deserializeUser logics. We can not store all the user details on browser then we can store only userID then get the other details when required.

    Here we are discussing only key points. We will attach full application in the end of the blog. Now it is time to load the above module in app.js file

     

    //app.js
    module.exports = function (flights, db) {
    	var express = require('express');
    	var MongoStore = require('connect-mongo')(express);
    	var passport = require('./auth');
    	var routes = require('./routes')(flights);
    	var path = require('path');	
    	var app = express();
    
    
    app.use(passport.initialize());
    app.use(passport.session());
    
    
    app.get('/login', routes.login);
    	app.post('/login', passport.authenticate('local', {
    		failureRedirect: '/login',
    		successRedirect: '/user'
    	}));
    
    	app.get('/user', routes.user);
    
    	return app;
    
    };

     

    In above code we have loaded the modules, initialized the passport module and session function to start the session. We are using get function to set the routes for login as well as welcome page. On failure we will redirect the page on login and on success we will redirect the page on welcome page that is user. These are the configuration for the passport.

    Now you need to create functions in  routes/index.js file. These functions are login and user. Please have a look.

    functions.login = function(req, res) {
    		res.render('login', {title: 'Log in'});
    	};
    
    	functions.user = function(req, res) {
    		if (req.session.passport.user === undefined) {
    			res.redirect('/login');
    		} else {
    			res.render('user', {title: 'Welcome!',
    				user: req.user
    			})
    		}
    	};

     

    In above login function we are rendering login.jade file for login form and checking user authentication for welcome page to render. Please check login.jade and user.jade below.

    //user.jade
    
    extends layout
    
    block content
    	h1= title
    	p= 'Hello ' + user.username + '!'

     

    //login.jade
    extends layout
    
    block content
    	h1= title
    	form(method='post')
    		input(name='username', class='input-block-level', placeholder='username')
    		input(name='password', class='input-block-level', type='password', placeholder='password')
    		input(type='submit', class='btn btn-primary', value='Log in')
    

    You can download the full application below.

    You can run the application using below command

    // go to app folder
    node server

    Now you can access the pages on browser.

    http://localhost:3000/login

    http://localhost:3000/user

    Thank you for being with us!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: