0

I am currently trying to display a error message if a user inputs a wrong username or password. The tricky part is that I am not using EJS or Handlebars, or any kind of template engine but raw HTML with Bootstrap.

I saw one other good question Good Similar Question of how to pass values from Nodejs to Angular. Sadly this didn't seem to help.

Here is my NodeJS + Passport User Authentication function:

 function isLoggedIn(req, res, next) {
        console.log('here is Authenticated', req.isAuthenticated());
        if (req.isAuthenticated()){
           return next();
        }else{
           res.json({"message": "Failed login. Wrong Username or Password"});
            res.redirect('/login');
            console.log("NO PERMISSION HAS BEEN GIVEN");
        }
    }

So my Idea was to send the message as an JSON object and get it with Angular:

 var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope, $http) {

            $http.get("/login").then(function(data){
                $scope.message = data;
                    console.log("message loaded" + data);
                });            
            });

and of course I am trying to display the message with {{message}}.

Sadly this method is not working, I am trying a second way which involves using ng-show.

Can I pass a NodeJS function to a ng-show? Something similar to:

<div class="alert alert-danger" ng-show="isAuthenticated = true">
                 <p> Failed login message </p>
</div>

If not, how can I display a failed login message to a static html file without using jade, handlebars or any other template engine?

Community
  • 1
  • 1
ZombieChowder
  • 1,187
  • 12
  • 36
  • Please explain what exactly is not working. A problem with your first approach, I don't understand why you are doing `res.redirect('/login');` if you simply want to send a JSON response. What does `console.log("message loaded" + data);` give you? – John May 11 '17 at 11:20
  • @undefined it doesn't console log anything. I am doing it so when the user is not being able to log it, it's redirected to the same page. I'm might not be right tho... "What is not working?" Me displaying an error "Wrong Name/Password" message on the initial login page. – ZombieChowder May 11 '17 at 11:25
  • The console will be cleared if you are redirecting. Put an alert instead stringify the `data` or remove redirection. – John May 11 '17 at 11:28
  • @undefined removed the redirection, it still doesn't print anything as it goes in the **else** part of the loop. – ZombieChowder May 11 '17 at 11:35
  • Are you calling `return next();` ? Did you check the response in network tab of your browser? I don't see any else in `$http.get` callback which one are you talking about? – John May 11 '17 at 11:52
  • I figured it out: `passport.authenticate('local', { failureFlash: true , badRequestMessage : 'Missing username or password.',failureRedirect: '/login' }),` The only thing left now is to display the message without using a templating engine. Is that possible at all? – ZombieChowder May 11 '17 at 12:36
  • Yes, you are almost on the right track. It will be a bit difficult to show it after the redirect. You will have to retain a value somewhere (in a service) in angular side check it and show the message in that case. But I don't see what's the point of redirecting to the same page? – John May 11 '17 at 12:41
  • @undefined otherwise I receive an "401" status **Unauthorised**. How can I retain the value? Using `http.get`? – ZombieChowder May 11 '17 at 12:44

1 Answers1

0

A couple things here that may help:

Firstly, you should avoid sending multiple responses for a request, so you should remove res.redirect('/login');.

Your res.json({"message": "Failed login. Wrong Username or Password"}); ends the response so the redirect never runs and redirecting would defeat the purpose of you displaying a error message for the user. Further, you should also send the proper status code to the client (401 Unauthorized in this case) to let it know that the request was not successful. For example:

function isLoggedIn(req, res, next) {
    console.log('here is Authenticated', req.isAuthenticated());
    if (req.isAuthenticated()){
       return next();
    } else{
       res.status(401).json({"message": "Failed login. Wrong Username or Password"});
    }
}

On the client side, $http returns a response object with a .data property that contains the payload of the response you sent from the server. You need to use that to access the JSON that has the message for the failed login. Also note that you're sending an object to the client, so you'll need to access the actual text of the string via res.data.message.

Also note that with $http, only a response with a status code in the 200 range is considered successful. So if the login fails, you can handle the failed login in an error handler. This way your UI can decide what to do based on whether the login was successful or not. For example:

 var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope, $http) {

     $http.get("/login").then(function(res){
        // Do stuff if login is successful
     })
     .catch(function(res) {
       $scope.message = res.data.message;
     })
Ian
  • 480
  • 5
  • 8