Skip to content

Instantly share code, notes, and snippets.

@phalkunz
Last active April 25, 2023 13:15
Show Gist options
  • Save phalkunz/728ec54c7ccbfd3a97ec to your computer and use it in GitHub Desktop.
Save phalkunz/728ec54c7ccbfd3a97ec to your computer and use it in GitHub Desktop.
Setup local (username/password) authentication in express.js (using passport.js)

Setup the project folder

    mkdir passport-local
    npm init
    # Use default values for npm init prompts

Install required packages

    npm install --save express
    npm install --save connect-flash
    npm install --save express-session
    npm install --save body-parser
    npm install --save cookie-parser

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

Create authentication module

In the root folder create a file called "auth.js" with the following content.

    var passport = require('passport'),
        LocalStrategy = require('passport-local').Strategy,
        user = { // This a hard-coded user
            _id: 1,
            username: 'john',
            email: '[email protected]',
            password: 'password'
        };

    // Register a login strategy
    passport.use('login', new LocalStrategy(
        function(username, password, done) {
            // This should check again db
            if(username === user.username && password === user.password) {
                return done(null, user);
            }
            else {
                done(null, false, { message: 'Invalid username and password.' });
            }
        }
    ));

    // Required for storing user info into session 
    passport.serializeUser(function(user, done) {
      done(null, user._id);
    });
     
    // Required for retrieving user from session
    passport.deserializeUser(function(id, done) {
        // The user should be queried against db
        // using the id
        done(null, user);
    });

    module.exports = passport;

Create app module

In the root folder create a file called "app.js" with the following content.

    var express = require('express'),
        app = express(),
        session = require('express-session'),
        flash = require('connect-flash'),
        session = require('express-session'),
        auth = require('./auth.js'),
        bodyParser = require('body-parser');

    app.use('/', express.static(__dirname + '/public'));

    app.use(session({ 
        secret: 'some-secret',
        saveUninitialized: false,
        resave: true
    }));

    // For parsing post request's data/body
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));

    // Tells app to use password session
    app.use(auth.initialize());
    app.use(auth.session());

    app.use(flash());

    // Set up routes
    app.get('/', function(req, res) {
        if(req.user) {
            res.send(
                '<p>You\'re logged in as <strong>' + req.user.username + '</strong>.</p>'
                + '<p><a href="/logout">Log out</a></p>'
            );
        }
        else {
            res.send('<p><a href="/login">Login</a></p>');
        }
    });

    app.get('/login', function(req, res) {
        res.send(
            '<form action="/login" method="POST">'
            + '<h2>Login</h2>'
            + '<p><input name="username"></p>'
            + '<p><input name="password"></p>'
            + '<p><input type="submit" value="Login"></p>'
            + '<p style="color: red;">' + req.flash('error') + '</p>'
            + '</form>'
            
        );
    });

    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

    app.post('/login', 
        auth.authenticate('login', {
            successRedirect: '/',
            failureRedirect: '/login',
            failureFlash: true
        })
    );

    var server = app.listen(3000, function() {
        var port = server.address().port;

        console.log('Server running on http://127.0.0.1:%s', port);
    });
{
"name": "password-local",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": ""
},
"author": "Saophalkun Ponlu",
"license": "The MIT License (MIT)",
"dependencies": {
"body-parser": "^1.12.0",
"connect-flash": "^0.1.1",
"express": "^4.12.2",
"express-session": "^1.10.3",
"passport": "^0.2.1",
"passport-local": "^1.0.0"
}
}
@pcl392578
Copy link

pcl392578 commented Dec 10, 2019

what is the commands to set password and user name i didn't get it????
how i will set for localhost ? "lt --port 3000"

@lejonmanen
Copy link

urlencoded and json are included in Express, in the latest 4.x version. Might want to update to
`` `app.use( express.urlencoded({ extended: true })
app.use( express.json() )```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment