restrict login page access if user isLoggedin using node and express
<p>login api:</p>

<pre><code>    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
                });
            }
        }
    });
});
</code></pre>

<p>middleware:</p>

<pre><code>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."});
    }
});
</code></pre>

<p>authService: </p>

<pre><code>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;
}
</code></pre>

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

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

<p>How to do this? </p>