Update EJS Layout with Session - node.js

My ejs layout provides the current user's username on the main menu through sessions
<a href="">
<% if (typeof currentUser === 'undefined'){%>
<% } else { %>
<a style="text-decoration:none;" href="/users/logout">Logout</a>
<% } %>
</a>
Now when I destroy the session and redirect to the main page, the currentUser's infomation is still showing, although logging currentuser returns undefined. Is there a way to force the layout to update itself to show current information?

Related

How to edit the render information with if else in ejs file

Hi i am trying to add condition for the render value in ejs file. i want to do something if value is equal to blah blah. I tried as shown below.
<% if (user) { %>
<div class="user_info">
<div>
<p>User Name<%= user.username %></p>
<p>User bio<%= user.user_bio %></p>
//here i want to put if else statement
//like this
<% if (user.user_age = null){ %>
<p>Your age is not defined. </p>
<% } %>
<% else if (user.user_age = 10){ %>
<p>You are a <%= user.user_age %> old tween!! </p>
<% } %>
<% else { %>
<p>You are a <%= user.user_age %> old Adult!! </p>
<% } %>
</div>
</div>
<% } else { %>
<p>No User!</p>
<% } %>
Clearly this if else statement i tried is not working.
How can i do this?
I have worked on this type of project something like that of whatsapp web,
its going to be a little hard because there are not many good tutorials out there, but I can give you some tips or steps you need to follow, to give the code would be very lengthy and its propriety code that I've worked on so I cant share that.
First of all to connect to server using a mobile or qr scanner you have to have a private or seperate socket to connect to the server. For that you can have to use web sockets which is a big task but you can use a simple socket library socket.io its fairly easy.
You will have to create a unique socket and key which you need to pass through the r itself(you have to render the qr code image through node js with the key as value) for that you can use 'qrcode' npm package.
For now your task here is done.
The difficult part starts here. You have to make an android/ios app to use that data which will use it in its own way, for ex in whatsapp when you can qr code from app it logs you in to your account and load contacts, messages, etc on the screen.
Im not an android or app developer for now, that part has to solved by you.

Conditional operators in ejs

This might sound really easy. There is a very similar
answer but somehow my code is behaving abruptly and driving me crazy. I have spent last 4-5 hours on this. Any help would be great.
I am building a Socket.IO chat app using Node + Express + Passport. I want to compare the userId of the current user with that of other users connected. I want to show him all users except himself to chat with in Socket.IO.
Read comments on code for clarity :
users.js
app.get('/users', function (req, res) {
var connectedUsers = require('../app').chatUsers; // => This is an array of all logged in user and I am getting this all correctly.
if (req.isAuthenticated()) {
res.render('users', {
currentUser: req.user,
users: connectedUsers,
title: 'OnLineUsers'
});
}
});
users.ejs
<h3>CurrentUser : <%- currentUser.id %></h3> // => This Prints like **abcdefg**
<% for(var i = 0;i < users.length ; i++){ %>
<h3>UserID: <%- users[i].id %></h3> // => This also prints the same **abcdefg** if only one user is connected.
<% if( currentUser.id !== users[i].id){ %> // => But this Conditional Operator does not works and show the current user himself.
<ul>
<li>
<h3> <%= users[i].name %></h3>
<a href="/socket" id="chatRoomUrl">
<button type="submit" class="btn-success">Chat</button>
</a>
</li>
</ul>
<% } %>
<% } %>
Thanks in advance. If there is any silly mistake on my part, please excuse me for wasting your time.
Your code is fine. Maybe there is space in two property. Try :
currentUser.id.trim() !== users[i].id.trim()
Change your following line, notice the change:
<h3> <%= users[i].name %></h3>
to this:
<h3> <%- users[i].name %></h3>

Unable to display flash message in view with ejs template

I am a newbie in NodeJS. I have a problem that I am unable to show flash message in my view.
Here is my Controller,
index : function(req, res){
res.locals.flash = _.clone(req.session.flash);
res.locals.layout = false;
res.view('login');
},
login : function(req, res){
....
if(!admin){
req.session.flash = {
err : 'User is not found.' // My flash message
}
res.locals.layout = false;
res.redirect('login');
return;
}
.....
}
Here is my view,
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
<% JSON.stringify(flash.err) %>
</div>
<% } %>
When login is false, it show only an empty alert box.
And I have a second problem. When I refresh page, The alert box isn't disappeared.
Could someone help me please.
Thanks a lot.
The alert box keeps on appearing because the req.session.flash object persists the session, so you need to null that out once it's used, or you can just simply use req.flash(), which does that for you. So change your index method to something like this:
index: function(req, res) {
// req.flash() returns the contents of req.session.flash and flushes it
// so it doesn't appear on next page load. No need to clone.
res.locals.flash = req.flash();
res.locals.layout = false;
res.view('login');
},
Now, onto the second problem. The error messages aren't appearing because you aren't using the proper EJS syntax to output escaped values into the view. All you need to do is change your code to this:
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
// Change <% to <%=
<%= flash.err %>
</div>
<% } %>
No need to JSON.stringify, unless you like the quotes. Notice that I changed the <% to <%=, which in EJS means "escape this and output it". It's not template HTML or anything like that, so it's okay to escape it anyway.

Access localStorage from ejs template

I am trying to save some data sent by the server to an EJS template in localStorage on the client side. However, when I try to access localStorage in the template, I get localStorage is undefined.
Here is a part of my page.ejs:
<% localStorage.setItem('info', JSON.stringify({'user': user})) %>
where user is a value received from the server.
Is this possible?
There are a few options depending on what you want to do. I came across this post looking to do something a little different but here is one way:
After the template renders and passes the data user, add a script tag to modify localStorage.
<!-- example.ejs -->
<!-- check for user on page load -->
<% if (typeof user != "undefined") { %>
<!-- make user available to script tag -->
<% var user = user %>
<!-- use script tag to access ejs data and local storage -->
<script>
let user = <%- JSON.stringify(user) %>;
localStorage.setItem('info', JSON.stringify({'user': user}));
</script>
<% } %>
check this once its worked for me,
<script>
let data =JSON.parse('<%- JSON.stringify(data) %>')
localStorage.setItem("data", JSON.stringify(data))
</script>
and for accessing,
<script>
let data = JSON.parse(localStorage.getItem("data"))
</script>

express + ejs login widget

I am trying to make easy widget for buttons login/logout.
laout.ejs
<% include ../shared/login_logout %>
login_logout.ejs
<% if ( !common.IsDefined(membershipHelper.GetCurrentUser(request , response)) ) { %>
<li class="pull-right">Login</li>
<% } else { %>
<li class="pull-right">Log Out</li>
<% } %>
membershipHelper.GetCurrentUser - this method checks request session for user_id and if it finds it returns user if it is found in db(mongoDB) else it returns null. As user is returned in callback function of User.findById ejs file receives "undefined" always. I thought to put this GetCurrentUser in the middleware but it look like I can't set null or undefined to locals variable
What can be solution for this problem?

Resources