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
}))
To maintain a session is now older You should try with JWT token
, It is very effective and easy. But still to maintain the session in Node js:
In your Express Config:
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(cookieParser());
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
rolling: true,
cookie: {
path: '/',
maxAge: 60000 * 1000
},
name: 'SID'
}));
Store session after Login:
var session = req.session;
if (user) {
session.user = user._id;
session.save();
console.log(session);
}
Check Session from middleware:
var session = req.session;
if (session.user) {
req.userid = session.user;
next();
} else {
return res.status(401).send({
code: 401,
message: Constant.authentication_fails
});
}
Hope you will get clear idea about session.
First install session
npm install express-session --save
initialization Session on your server page
var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({secret: 'ssshhhhh',saveUninitialized: true,resave: true}));
store session
sess=req.session;
var user_id=1;
sess.user_id=user_id;
Access Session
sess=req.session;
sess.user_id
Follow below steps:
1. npm install express-session --save
2. Write below code:
var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({secret: 'your secret key', saveUninitialized: true, resave: true}));
var userId = 1234;
app.get('/', function (req, res, next) {
req.session.userId = userId;
});
You could use express-session middleware. Combine it with connect-redis or connect-mongo to store your sessions inside a database and save memory if memory is valuable to you (like in a cloud setup).
https://github.com/expressjs/session
https://www.npmjs.com/package/express-sessions
If you store it in say mongodb , use php mongo driver to pick it up from there.
Session that gives access/permission to view user's area, as well as it's a credential so we can use it over the application. I used jsonwebtoken to make a token which will have user's details with time after successful login attempt by user. I stored it in redis, and can be used for a pre-declared time limit.