1

login api:

    api.post('/login', function(req, res) {

    User.findOne({ 
        username: req.body.username
    }).select('password').exec(function(err, user) {

        if(err) throw err;

        if(!user) {
            res.send({ message: "User doesn't exist."});
        } else if(user) {

            var validPassword = user.comparePassword(req.body.password);

            if(!validPassword) {
                res.send({ message: "Invalid password."});
            } else {

                /////// token

                var token = createToken(user);
                res.json({
                    success: true,
                    message: "Successfully logged in.",
                    token: token
                });
            }
        }
    });
});

middleware:

api.use(function(req, res, next) {

    console.log("somebody just came to our app.");

    var token = req.body.token || req.param('token') || req.headers['x-access-token'];

    // check if token exists

    if(token) {
        jsonwebtoken.verify(token, secretKey, function(err, decoded) {
            if(err) {
                res.status(403).send({ success: false, message: "failed to authenticate user."});
            } else {

                req.decoded = decoded;
                next();
            }
        });
    } else {
        res.status(403).send({ success: false, message: "no token provided."});
    }
});

authService:

authFactory.login = function(username, password) {

    return $http.post('/api/login', {
        username: username,
        password: password
    })
    .success(function(data) {
        AuthToken.setToken(data.token);
        return data;

    })
}

authFactory.isLoggedIn = function() {
    if(AuthToken.getToken())
        return true;
    else
        return false;
}

Now, if my user is logged in and he tries to access: localhost:3000/login , then he should be redirected to localhost:3000/

only after he logs out, he should be able to access the login page (similar to facebook).

How to do this?

2 Answers 2

0

1

In login API store user info in respond object(res).

2

app.get('/',function(req,res){
  if(req.user){
    res.redirect('/login');
  } else {
    res.render('home');
  }
});

RECOMMENDED:PASSPORT and its Local-Strategy.

4
  • can you give me a working code for the solution? @virattara thanks in advance
    – kRAk3N
    Jul 2, 2016 at 17:30
  • Code for passport? Jul 2, 2016 at 17:35
  • i am not using passport.. could you provide me a working example as i'm new to this. thanks
    – kRAk3N
    Jul 2, 2016 at 17:37
  • 1
    Sorry bro I can provide you assistance in understanding passport. I have used it but the code is quite messy, it's part of a project. Feel free to ask questions otherwise. Jul 2, 2016 at 17:48
0
exports.loginPage = (req, res) => {
  if(req.session.user){
    res.redirect("/");
  } else {
    res.render("loginPage");
  }
};

On your login route, add the logic inside the middleware function. You could the same on the registration page as well.

exports.registrationPage = (req, res) => {
      if(req.session.user){
        res.redirect("/");
      } else {
        res.render("registrationPage");
    }
};

The key takeaway is this: if you want a user not to see a page on your site, go to the page's route, add the if/else logic.

Hope that helps, cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.