Skip to content
Related Articles

Related Articles

Improve Article

Disabling Sessions in Passport.js

  • Last Updated : 06 Oct, 2021
Geek Week

In a common web application, the credentials used to authenticate a user will only be transmitted during the login request. Passport will establish a persistent login session after successful authentication. This session is maintained via a cookie in the user’s browser. 

However, in some cases, session support is not required. For instance, API servers supply require credentials with each request to be authenticated. In this scenario, you can disable session support. You, need to set the session option to false.  

app.post('/auth',
  passport.authenticate('local-signin', {
    successRedirect : '/dashboard',
    failureRedirect : '/login',
    session: false
  })
)

Alternatively, a custom callback can be provided to allow the application to handle success or failure.

app.get('/auth', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    // your logic to how you serve your user
  })(req, res, next);
});

In the above example, the passport.authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects and the next method through closure.

Example: In a typical web application the user will redirect to the login page after register. So, here we don’t need to create a session after the new registration.  Let’s see the implementation. 



Project Setup: Create a new NodeJS project and name it Auth

mkdir Auth && cd Auth
npm init -y 

Install Dependencies: 

  • We can use body-parser middleware to parse the request bodies.
    npm i express body-parser
  • We can use any template engine, in our case it is ejs.
    npm i ejs 
  • We can create a unique user id using uuid module.
    npm i uuid
  • Instead of storing user-inputted passwords directly, we store the user password’s hash. We can generate the password’s hash using bcrypt module.
    npm i bcrypt
  • We need to install passport module to use its functionality
    npm i passport
  • Passport offers many strategies, here we are going to use the passport-local strategy.
    npm i passport-local

Project Structure: It will look like this.

  • passport-config.js: This is the passport configuration file.
  • register.ejs: This is the view of the register page.
  • index.js: This main server setup file.

register.ejs




<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
      
    <style>
        .container{
            position: relative;
            width: 400px;
            padding: 8px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            box-shadow: black 0 0 14px 8px;
        }
        label{
            font-size: 17px;
            display: block;
        }
        input{
            display: block;
            margin: 4px;
            padding: 4px 8px;
            height: 31px;
            width: 350px;
            font-size: 22px;
        }
        .btn-submit{
            border-radius: 2px;
            padding: 10px 17px;
            background-color: green;
            border: none;
            color: white;
            font-weight: bold;
            cursor: pointer;
            width: 120px;
            height: 44px;
        }
        .btn-submit:hover{
            opacity: 0.8;
        }
        .brand{
            text-align: center;
            color: #c2bfbf;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="brand">GeeksForGeeks</h1>
        <h2>Register</h2>
  
        <form action="/register" method="POST">
          
            <label for="email">Email: </label>
            <input id="userEmail" name="email" type="email">
      
            <label for="password">Password: </label>
            <input id="userPassword" name="password" type="password">
      
            <input class="btn-submit" type="submit" value="Register">
      
        </form>
    </div>
</body>
</html>

passport-config.js




const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const { v4: uuid } = require('uuid')
  
const initialize = (passport, getUserByEmail, save) => {
  
    // Verify callback function implementation
    const register = async (email, password, done) => {
  
        // Check wheather user is already registered or not
        const user = getUserByEmail(email)
  
        // If user is registered, invoke done()
        if (user != null)
            return done(null, user, { 
                message: "You are already registered" })
  
        // Generate user password's hash
        const hashedPassword = await bcrypt.hash(password, 10)
  
        // Create new user 
        const newUser = {
            // Generate user id
            id: uuid(),
            email: email,
            password: hashedPassword
        }
  
        // Save newly created user to database 
        save(newUser)
  
        // Invoke done()
        return done(null, newUser, { 
            message: "Registration Successful" })
    }
  
    // Middleware 
    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    }, register))
}
  
module.exports = initialize

index.js




// Import Modules
const express = require('express')
const bodyParser = require('body-parser')
const passport = require('passport')
const ejs = require('ejs')
  
const intializePassport = require('./config/passport-config')
  
const app = express()
const port = 8080
  
// Dummy in-memory user database
const Users = []
  
// Returns middleware that only parses urlencoded bodies
// A new body object contained pasrse data add to the
// request object 
app.use( bodyParser.urlencoded( { extended: false } ) )
  
// Pass require logic 
intializePassport(
    passport,
    email => Users.find(user => user.email === email),
    user => Users.push(user)
)
  
// Set EJS as view engine
app.set('view engine', 'ejs')
  
// API endpoint
app.get('/', (req, res)=> res.render('register.ejs'))
      
app.post('/register', (req, res, next)=> {
        
        // Invoke implementation of local strategy 
        passport.authenticate('local-signup'
                     (err, user, info)=>{
  
            // If any error
            if (err)
                res
                    .status(500)
                    .send("<H1> Server Erro! </H1>")
            else{
                  
                // Display the user object
                console.log({
                    Error: err,
                    User: user,
                    Message: info.message
                })
                  
                // Send message to user 
                res.send(`<H1> ${ info.message } <H1>`)
            }
  
        // Pass req, res and next as closure
        })(req, res, next) 
    })
  
// Start server
app.listen(port, () => console.log(`Server listening on port ${port}!`))

Step to run application: Run the index.js file using the following command:

node index.js

Output: We will see the following output on the terminal screen.

Server listening on port 8080

Now open any browser and go to http://localhost:8080/, we will see the following output:

Registration Form

After submitting the form, we will see the Registration Successful on the browser and also see the following output on the terminal screen:

Server Terminal




My Personal Notes arrow_drop_up
Recommended Articles
Page :