How can I maintain my SESSIONS in Node JS ? E.g I want to store UserID in SESSION using Node Js. How can I do that in Node JS ? And can I use that Node JS SESSION in PHP too
Storing session in NODE JS is fairly easy but you need to understands its step, you could handle this manually, also you can use few NPM modules. Passport can help you to authenticate and login and store the session i would recommend you to read its documentation, Passport allow you to authenticate user with different other platform like google, github many more.
If you are going to use passport use these below NPM module
2 -import these modules in you main app.js
const flash = require('express-flash')
const session = require('express-session')
const passport = require('passport')
app.use(session({
secret:'secret',
resave:false,
saveUninitialized:false
}))
app.use(flash())
app.use(passport.initialize())
app.use(passport.session())
3- create passport.js file you can name anything, So basic understanding behind this is that you have to check the valid user coming from your input form, you have to compare the email id with your model if it is valid check for password and then return the user. Once that done serialize and deserialize your user to store in session.. I would recommend to check this part in the documentation for more clear understanding. http://www.passportjs.org/docs/downloads/html/
const localStretgy = require('passport-local').Strategy
const bycrypt = require('bcrypt')
const User = require('../model/User')
const initalize = function(passport){
const auth = async(email,password,done)=>{
try {
const user = await User.findOne({email:email})
if(!user){
throw new Error("Incorrect Email ..!")
}
const match = await bycrypt.compare(password,user.password)
if(!match){
throw new Error('Incorrect Password..!')
}
return done(null,user)
} catch (error) {
console.log(error)
done(null,false,error)
}
}
passport.use(new localStretgy({usernameField:'email'},auth))
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
module.exports = initalize
Now go to your login router use below code
const passport = require('passport')
require('../passport/passport')(passport)
routes.get('/signin',(req,res)=>{
res.render('signin',{
pageTitle:'sign in'
})
})
routes.post('/signin',passport.authenticate('local',{
successRedirect:'/welcome',
failureRedirect:'/',
failureFlash:true
}))