Tuesday, 14 March 2017

Authenticating user in Angular JS using $http request

I have the code for backend for login/logout and authenticate, but i need help in authenticating user on Angular Front End.

Server Side code: Login

// controller that handles user login request
users.auth = function (req, res) {

    if(!req.body.username || !req.body.password)
    {
        res.status(400);
        res.send({status:'error',error:'Username or password is missing.'});    
    }

    var user = userModel.authUser(req.body.username, req.body.password);

    user.then(function(users){
        res.send(users);    
    }, function(){
        res.send({status:'error',error:'Error occured while fetching data from database.'});
    });

};

Server Side code: Logout

// controller that handles user logout request
users.logout = function (req, res) {

    var sessionId = req.query.sessionId;

    var user = userModel.logout(sessionId);

    res.send({status:'success'});   


};


module.exports = users;

Helper that handles Authentication:

var helpers = {};

    //Function that checks if the request is authenticated or not.

        helpers.isAuthenticated = function(req, res, next){

            if(!req.query.sessionId){
                res.status(401);
                res.send({status:'error',error:'Not Authorized.'});
            }
            else{
                var user = Users.getBySessionId(req.query.sessionId);   
                user.then(function(dbuser){
                    if(dbuser){
                        next();
                    }else{
                        res.status(401);
                        res.send({status:'error',error:'Not Authorized.'});     
                    }   
                });

            }
        }

Now i need to authenticate user on front to display my content. How can I connect user authentication to front end using REST API call in angular js. I am newbie to angular.

Thanks in advance



via user3374600

No comments:

Post a Comment