Sunday 19 March 2017

Pass session to Angular from Node

Im creating a single page app. I have a sign in form in angular:

<div ng-controller="loginCtrl">
    <form>
        <input type="text" ng-model="user.username">
        <input type="password" ng-model="user.password">
        <button ng-click="senduser(user)">Login</button>
    </form>
</div>

Controller:

MyApp.controller("loginCtrl", function($scope, $http){
    $scope.senduser = function(user){
       $http.post("/login", user).then(function(response){
            if(response){
                console.log(response);
            } else {
                console.log("No Data");
            }
        });
      }
});

I can get the user authenticated by using PassportJS:

passport.use(new LocalStrategy(function (username, password, done) {
    User.findOne({username: username}, function (err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false);}
        if (user.password != password) { return done(null, false); }

        return done(null, user);
    });
  }
));

And the node route:

app.post("/login", passport.authenticate('local', {
    failureRedirect : '/login',
    successRedirect: '/loginsuccess'
}));

app.get('/login', function(req, res){
    res.send("Try again")
});

app.get('/loginsuccess', function(req, res){
    res.send("You are Authenticated : ");
});

So far everything works. I want to redirect the successRedirect and failureRedirect to same path \ but only have the session for the user who is authenticated. So based on the authentication, certain fields will be visible on the \ page.

How do I do that ?



via Somename

No comments:

Post a Comment