Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access Passport's req.user variable in client side javascript?

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

like image 228
user3473543 Avatar asked Jan 22 '15 19:01

user3473543


1 Answers

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);
    }
});
like image 197
Aviran Cohen Avatar answered Oct 11 '22 21:10

Aviran Cohen