1

I am building an angularJS based application and I am running passportjs on my nodeJS back-end. Authentication works but error handling is not a precise as I want it to be. For example when I am querying my mongoDB and something fails I do the following:

Node:

response.send(406, {error: "Email already in use"});

Angular:

settingsService.saveUserOnServer($scope.settings).then(
     function (user) {
        //Success
      },
      function (response) {
          console.log(response);
          var error = response.data.error;
          $cordovaToast.show(error, 'short', 'bottom');
      });

This will toast "Email already in use". I want to have the same functionality when using passportjs:

// if no user is found, return the message
if (!user)
   return done(null, false, {message: 'No user found'}); 

This is the response I get in angular:

Object {data: "Unauthorized", status: 401, headers: function, config: Object, statusText: "Unauthorized"}

How can I retrieve the 'No user found' message? Thanks in advance!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jdruwe
  • 3,450
  • 6
  • 36
  • 57
  • Please don't abuse HTTP status codes. 406 means "Not Acceptable" in the sense that the server is unable to fulfill the request based on the **"Accept" header** sent by the client, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. As for the problem itself, are you sure what is sent over the wire? Use a debugging proxy or network sniffer to inspect the actual response, maybe something interferes... – mnemosyn Nov 05 '14 at 15:47
  • I was looking for a correct status code but was enable to find a correct 1, isn't there a general one that is acceptable? – Jdruwe Nov 05 '14 at 16:24
  • Tricky indeed. In the case of "email already in use", one could choose HTTP 409 "Conflict", but it's really only correct if the email was in the URL, I think. Otherwise, there's WebDAV's pretty generic 422 "Unprocessable Entity" is a good default I think (server understood request but refused for semantic reasons). – mnemosyn Nov 05 '14 at 16:37
  • 1
    Thank you so much! I also found the answer for the main question. – Jdruwe Nov 05 '14 at 17:04

1 Answers1

0

Fixed it by using a custom callback:

app.post('/login', function (req, res, next) {
    passport.authenticate('local-login', function (err, user, info) {
        console.log(info);
        if (err) {
            return next(err);
        }

        if (!user) {
            res.send(401, info);
        }
        req.logIn(user, function (err) {
            if (err) {
                return next(err);
            }
            res.send(user);
        });
    })(req, res, next);
});

explanation

Community
  • 1
  • 1
Jdruwe
  • 3,450
  • 6
  • 36
  • 57