user3655672 user3655672 - 3 months ago 35
reST (reStructuredText) Question

MEAN + Passportjs (Facebook) - How do I handle the passport callback with angular without redirects by the server

I am in the midst of building a sample authentication app using the MEAN Stack + Passport (for facebook). I would like the server to not be coded for a particular type of client (angular in this instance). I want the passport module to return the status and the data and let the client decide what has to be done in each case?

// facebook -------------------------------

// send to facebook to do the authentication
app.get('/auth/facebook',
passport.authenticate('facebook', { scope : 'email' })
);

// handle callback
app.get('/auth/facebook/callback', function(req, res) {

passport.authenticate('facebook', function(err, user, info) {

if (err) { return res.json(err) }
else if (user.error) { return res.json({ error: user.error }) }
else { return res.json({ redirect: '/profile', user: user }) }

})(req, res);

});


I am not sure how should I handle the callback in angular since there is no success handler on this route since facebook is calling that endpoint and not angular.

Thanks a lot for your help in advance.

Answer

you can use the stateChangeStart if you are using ui-router:

Assuming the page where the user will sign in with Facebook is called /singin with a state of singin, you can trigger this event and handle the next state :

$rootScope.$on('$stateChangeStart', (event, next, params, fromState) => {
                    Auth.promise.then(() => {
                        // Look for a redirection state and default to homepage
                        if ($rootScope.isLoggedIn && fromState === "singin") return $state.go("whatever")
                    })
                })

also to prevent any default redirection when this condition is true, you can use :

event.preventDefault()

so you code will looks like this :

$rootScope.$on('$stateChangeStart', (event, next, params, fromState) => {
            event.preventDefault()
                    Auth.promise.then(() => {
                        // Look for a redirection state and default to homepage
                        if ($rootScope.isLoggedIn && fromState === "singin") return $state.go("whatever")
                    })
                })
Comments