Reputation: 171
I am trying to store client session using raw node.js without express.
When a user logs in I have the username and password. Now, how to store a session in client browser using cookie. And how to identify the user when they refresh the tab or goes to another link.I don't want to use client-sessions
module as I want to understand the approach.
any help will be appreciated.
Upvotes: 2
Views: 2376
Reputation:
First of all, I suggest you to watch everything about authentication in NodeJS It explains cookies in a part very well.
You have to give the browser some data to hold for it to use later, which being cookies
. Browser uses this data to show the server what kind of authentications it has processed before for the server and the user to proceed without repetition.
In node.js, using client-sessions
module, you can set a cookie by calling
app.post('/login', function(req,res){
User.findOne({password: req.body.userPassword}, function(err, user){
if(user){
req.session.user = user; //here you are setting the cookie for the client,
}
})
})
You could also specify what kind of cookie you want to set by just adding it a property
req.session.userEmail = user.email;
Now let's check how the server uses authentication
app.get('/someUrl', function(req,res){
if(req.session.user){
console.log("user exists!");
}
})
You can check what the client sends you by using session
property of req
object => req.session
To bind it with database you need to do,
if(req.session.user){
User.findOne({email: req.session.user.email}, func...)
}
So basically, with each request that client sends, this procedure is used by the server to identify the cookies and to make the web-app user-friendly with no repetition.
It is like giving every student an ID in a school for authentication.
Security
For security, the node module cookie-sessions
encrypt data automatically when we add secret
attribute in app.use()
function. Please see using secret
in client-sessions module
Upvotes: 3