Passport.js Integration

Passport.js Integration

·

3 min read

Lets setup a basic program with Login and Register routing.

const express = require(`express`);
const mongoose = require(`mongoose`);
const app = express();
const Users = require("./schema/user")

//global variables
const URI = "mongodb://27017.0.0.0.1/yourDatabase"
//

//setting up the view engine//
app.set(`view-engine`,`ejs`)

//mounting up the middlewares//

app.use(express.urlencoded({extended:true}))


// listening to the servers and connecting the mongoDB//
app.listen(`3000`,()=>{console.log("server online @port 3000"});
mongoose.connect(URI).then(()=>console.log(`connected to ${URI}`)

//to setup routes below//

now to setup the Schema.

const mongoose = require(`mongoose`)

const userSchema = new mongoose.Schema({
username : {
   type: String,
   unique : true
},
password : {
   type : String,
}
})

const userModel = new mongoose.model(userSchema, "Users");

module.exports = userModel;

Import the newly created userModel into app.js using:

const Users = require("./user")

now we need to setup up ejs and all its files and to do that we need to use app.set() method to configure our express application along with that we can also use app.use() to mount middleware so that they will run everytime when user gets redirected to any of the routes.

app.set(`view-engine`,`ejs`)  // setting the view templating engine to EJS.
app.use(express.urlencoded({extended:true})) // express inbuild bodyparser method

now we need to install some packages to integrate passport authentication in our application :

npm install express-session passport passport-local passport-local-mongoose

and require them in our app.js file

const passport = require(`passport`);// this is our main passport package
const session = require(`express-session`); //express-session package which helps our application to setup sessions
const localStratergy = require(`passport-local`); // local HTMLform statergy in passport for authentication throught html forms.

now we need some boilerplate code to configure and use these packages in our application.

app.use(session({
resave : false,
secret:"our secret key",
saveUninitialized: false,
}))

app.use(passport.initialize());
app.use(passport.session());
passport.use(Users.createStratergy());
passport.serializeUser(Users.seralizeUser());
passport.deserializeUser(Users.deserializeUser());

also we need to add the passport-local-mongoose package into our mongoose model which we created for it to encrypt,hash and decrypt our data automatically.

const mongoose = require(`mongoose`)
const PLM = require('passport-local-mongoose') // importing the package
const userSchema = new mongoose.Schema({
username : {
   type: String,
   unique : true
},
password : {
   type : String,
}
})

userSchema.plugin(PLM); // this is how we mount a 
//package into our schema model to use its functionality 
//and enhance our model capabilites even further.

const userModel = new mongoose.model(userSchema, "Users");

module.exports = userModel;

Now its time to setup our get routes.

//to setup routes below//

//get routes//
app.get(`/`,(req,res)=>{
res.render("homepage") // this will render our homepage.ejs file whenever the user navigates to our "/" route})

app.get(`/login`,(req,res)=>{
res.render("login");
})

app.get(`/register`,(req,res)=>{
res.render("register");
})

and our login post routes :

app.post(`/login`,(req,res)=>{
const newUser = new Users({
username : req.body.username,
password : req.body.password,
 })
req.login((err)=>{
if(err){
console.log(err)
res.redirect("/login")
  }
else{
passport.authenticate("local")(req,res,()=>{
res.redirect(`/profile`)
    })
   }
 })
})

then our register post route :

app.post(`/register/`,(req,res)=>{
Users.register({username : req.body.username},req.body.password,(err,user)=>{
if(err){
   console.log(err)
   res.redirect("/register") 
  }
else{
   passport.authenticate("local")(req,res,()=>{
     res.redirect(`/profile`) 
   })
  }
 })
})

lastly our logout route :

app.post(`/logout`,(req,res,next)=>{
req.logout((err)=>{
if(err){
next(err)
}
res.redirect(`/homepage`)
})
})