I have Passport authentication set up on my simple Express app and it works fine, and I have it displaying req.user on my index page like this:
<% if (!isAuthenticated) { %>
<a id="signIn" href="/login">Sign In</a>
<% } else { %>
<h3 id="welcomeMsg"><%=user.id%></h3>
<h2 id="userBalance"><%=user.balance%></h2>
<a href="/logout">Log Out</a>
<% } %>
In index.js:
app.get('/', function(req, res){
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
What I want to do is confirm the username of who's signed in, in a client side js file in my public directory. What would be the simplest and most straightforward way to make that variable available in that file?
Thank you
Since the passport.js
mantains a session by using a cookie,
you can add a simple route in your application that provides the current logged user data in json format:
app.get('/api/user_data', function(req, res) {
if (req.user === undefined) {
// The user is not logged in
res.json({});
} else {
res.json({
username: req.user
});
}
});
and access it with your client side javascript using jQuery.getJSON() or any other method that can GET request a json content.
Example with jQuery.getJSON():
$.getJSON("api/user_data", function(data) {
// Make sure the data contains the username as expected before using it
if (data.hasOwnProperty('username')) {
console.log('Usrename: ' + data.username);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With