Reputation: 2144
I'm using passportjs for authentication in my MEAN app.
I'm just confused about how can I identify that user is logged in or not on page refresh. Currently I'm storing user data in $rootScope, so it is working if I do not reload. But when I reload page $rootScope gets cleared so in this situation how can I get user information.
A cookie is set by passport, What is the purpose of that and can I use that cookie to authenticate, and if yes, how ?
Upvotes: 0
Views: 180
Reputation: 5704
You can setup a route /user
and from angular check if a user is logged in
app.get('/user', function(req, res, next){
if(req.user) return res.json(req.user);
res.json({error: 'not logged in});
});
or inject user to page when you render it
app.get('/', function(req, res, next){
res.locals.user = req.user || null;
res.render('index');
});
and in the view (i use handlebars)
<html>
<head>
<script>
{{#if user}}
var user = {
username: {{user.name}},
email: {{user.email}}
}
{{/if}}
</script>
</head>
<body>
</body>
</html>
and then in your controller check if the user object exists, inject $window as dependency
if($window.user) {
$rootScope.user = $window.user;
}
Upvotes: 1