0

I am wondering how I can pass variables from Node / Express to my AngularJS front end. In particular, if I am using Express (Passport) for authentication, how can I pass the user name and information to display in the corner of my app, alongside the "Logout" button?

Here is my code for authentication routes. Should I be using URL variables for this? Or should I try to somehow implement a separate end-point that would pass this small bit of info?

Just to clarify, once the user logs in and is directed to "/" AngularJS front-end takes over and does the routing within itself.

var express = require('express');
var router = express.Router();

module.exports = function(passport){

    var isAuthenticated = function (req, res, next) {
            // if user is authenticated in the session, call the next() to call the next request handler 
            // Passport adds this method to request object. A middleware is allowed to add properties to
            // request and response objects
            if (req.isAuthenticated()){
                //console.log(next());
                return next();
            }
            // if the user is not authenticated then redirect him to the login page
            res.redirect('/login');
    }


    /* GET login page. */
    router.get('/login', function(req, res) {
        // Display the Login page with any flash message, if any
        res.render('login', { message: req.flash('message') });
    });

    /* Handle Login POST */
    router.post('/login', passport.authenticate('login', {
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash : true  
    }));

    /* GET Registration Page */
    router.get('/signup', function(req, res){
        res.render('register',{message: req.flash('message')});
    });

    /* Handle Registration POST */
    router.post('/signup', passport.authenticate('signup', {
        successRedirect: '/',
        failureRedirect: '/signup',
        failureFlash : true  
    }));

    /* GET Home Page when logged in */
    router.get('/', isAuthenticated, function(req, res){
        res.render('index', { user: req.user });
    });

    /* Handle Logout */
    router.get('/signout', function(req, res) {
        req.logout();
        res.redirect('/login');
    });

    return router;
}

3 Answers 3

3

Short answer: Yes as you are using Express you should create a separate end-point to retrieve user data from your Angular app.

As another answer already states this user data should be stored in req.user.

So your end-point could look like this:

var express = require('express');
var isAuthenticated = require('path/to/exported/middleware').isAuthenticated;
var router = express.Router();

router.get('/user', isAuthenticated, function(req, res) {
    var data = {
        name: req.user.name,
        email: req.user.email,
        /* ... */
    };

    res.send({
        data: data
    });
});

module.exports = router;

Do not send the whole req.user object but select the properties you actually want to display.

Sign up to request clarification or add additional context in comments.

7 Comments

Do I need to protect this end-point somehow? That is, what if someone navigates to it directly?
Everyone navigating to it will only receive his/her user information. The req.user object is populated for each request using the user's session data so it is not possible to access the user data of other users this way.
I get it. However, if a user is not logged in, it still stays protected.
If a user is not logged in req.user will be empty. To avoid this you could add your isAuthenticated middleware, I will update my answer.
Got it. I just tried it out. It seems to work. By the way, do you know if it is possible to customize which fields passport uses for authentication? That is, can I eliminate username and just stick with email?
|
2

I think that the best practice is to implement an api that returns all the data you need with an ajax request. But if you don't want to the all that work, you can add an hidden input element to your page and set his value with a json string that later can be parsed to js an object in your client side.

1 Comment

This approach can easily cause issues. A user can change the value of the input in the DOM (via DevTools) and then when the js script executes it will pure the hijacked data.
2

I'm pretty sure with passport, that the user information is in the request object.

Meaning, you should be able to access through req.user.name , etc.

You could then send it to angular in response " res.send({currentUser: req.user})" when needed, or possibly in your login and store it in rootscope or localStorage / cookie

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.