仅在前一个函数失败时执行函数

时间:2017-01-17 15:49:43

标签: javascript angularjs node.js

所以,我一直在为我的应用程序登录facebook登录,这里有一个问题。 该怎么办?

1 - 在Facebook上验证(完成) 2 - 从facebook检索usar数据(DONE) 3 - 检查用户是否存在    - 如果他这样做,他将使用电子邮件和fb令牌登录。    - 如果他没有,系统将注册他的数据并自动登录。

问题是: 我有这里的方法,验证和注册。 我该怎么办? 调用Authenticate,如果发生错误,我需要调用authenticate并注册。 我该怎么做?

在NodeJS中注册

api.register= function(req, res) {
    if (req.body.password!==null) {
            var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(9));
            req.body.password= hash;
            console.log('Default Login');
    }
    if(req.body.tokenFB!==null){
        var tokenHash = bcrypt.hashSync(req.body.tokenFB, bcrypt.genSaltSync(9));
        req.body.tokenFB = tokenHash;
        console.log('Login with facebook');
    }
    userModel.create(req.body)
        .then(function(user){
            res.json(user);
            console.log('We have a new user! =)');
        }, function(error){
            res.status(500).json(error);
        });
};

在NodeJS中进行身份验证

api.authenticate= function(req, res) {
        var email = req.body.email;
        console.log(req.body);
        userModel.findOne({"email":email})
        .then(function(user){
            if (user == null) {
                res.status(404).json();
            }
            else {
                if (req.body.password!==null && bcrypt.compareSync(req.body.password, user.password)) {
                    //user found
                    console.log('default user')
                    var token = jwt.sign({email:user.email}, app.get('secret'), {
                        expiresIn: 84600
                    });

                    res.set('x-access-token', token);
                    res.json(user);
                } else if (req.body.tokenFB!==null && bcrypt.compareSync(req.body.tokenFB, user.tokenFB)){
                    console.log('facebook user')
                    var token = jwt.sign({email:user.email}, app.get('secret'), {
                        expiresIn: 84600
                    });

                    res.set('x-access-token', token);
                    res.json(user);

                }
                else {
                    res.status(404).json();
                }
            }
        }, function(error){
            res.status(404).json(error);
        });
};

在AngularJS中登录Facebook If部分显然不起作用,因为我正在尝试并展示我想要做的事情

$scope.FBLogin = function (){
  firebase.auth().signInWithPopup(provider).then(function(result) {

    var token = result.credential.accessToken;
    var user = result.user;

    $http.get('https://graph.facebook.com/v2.5/me?   access_token='+token+'&fields=id,name,first_name,last_name,email')
    .success(function(jsonService){
       $scope.user.firstName= jsonService.first_name;
       $scope.user.lastName = jsonService.last_name
       $scope.user.email = jsonService.email;
       $scope.user.password=null;
       $scope.user.tokenFB=token;
       $scope.user=true;
       console.log($scope.user);

       if($scope.authenticate()){
         console.log("Logged in with Facebook! :)")
       } else {
         $scope.checkingUser=false;
         $scope.Register();
         $scope.Authenticate();
        };
    });

  }).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // The email of the user's account used.
    var email = error.email;
    // The firebase.auth.AuthCredential type that was used.
    var credential = error.credential;
  // ...
  });
};

那么,有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

所以......我用promises解决了我的问题。 这就是我所做的。

在NodeJS中注册

api.register = function(req, res) {
    if (req.body.password!==null) {
            var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(9));
            req.body.password = hash;
            console.log('Default Login');
    }
    if (req.body.idFb!==null) {
            var idFbHash = bcrypt.hashSync(req.body.idFb, bcrypt.genSaltSync(9));
            req.body.idFb = idFbHash;
            console.log('Login with FB');
    }
    userModel.create(req.body)
        .then(function(user){

            console.log('We have a new account!');
             return res.json(user);
        }, function(error){
            return res.status(500).json(error);
        });
};

在NodeJS中进行身份验证

api.authenticate = function(req, res) {
        var email = req.body.email;
        userModel.findOne({"email":email})
        .then(function(user){
            console.log(user);
            if (user == null) {
                console.log('The user does not exist')
                return res.status(404).json();
            }
            else {
                console.log('User found')
                if (req.body.password!==null && bcrypt.compareSync(req.body.password, user.password)){
                    //user found
                    console.log('Default user')
                    var token = jwt.sign({email:user.email}, app.get('secret'), {
                        expiresIn: 84600
                    });
                    res.set('x-access-token', token);
                    return res.json(user);


                } else if (req.body.tokenFB!==null && bcrypt.compareSync(req.body.idFb, user.idFb) ){
                    console.log('Facebook user')
                    var token = jwt.sign({email:user.email}, app.get('secret'), {
                        expiresIn: 84600
                    });

                    res.set('x-access-token', token);
                    return res.json(user);


                }
                else {
                    return res.status(404).json();
                }
            }
        }, function(error){
            return res.status(404).json(error);
        });
};

在AngularJS中进行身份验证

const authenticate = function ($scope){
 return new Promise((resolve, reject) => {
   if ($scope.user.email == null) {
     console.log('Email was not received');
     var alertPopup = $ionicPopup.alert({
       title: 'We could not log you in',
       template: 'Please, verify your data!'
     });
     $scope.user.password = "";

     // "Return"
     reject(false);
   } else if($scope.user.tokenFB == null && $scope.user.password == null){
     console.log("No password or Facebook token")
     var alertPopup = $ionicPopup.alert({
       title: 'We could not log you in',
       template: 'Please, verify your data!'
     });

     // "Return"
     reject(false)
   } else {
     $http.post(serveradress.url+'/authenticate/', $scope.user).success(function(user){


       $localStorage.user=user;
       //$scope.isLoggedIn=true;
       $scope.user = user;
       $scope.user.password = "";
       UserService.setUser(user);
       window.location = '#/timeline';
       $scope.hide();
       //teste aidax
       ax.ready(function() {
         ax.toggle_debug();
       });
       ax.goal('login', true, false, {
         email: user.email
       });
       ax.identify(user.email);



       resolve(true)
     }).error(function(erro){

       if($scope.checkingUser){
         console.log("User does not exist")
       } else {
         $scope.hide();
         console.log("tá entrando aqui!")
         var alertPopup = $ionicPopup.alert({
           title: 'We could not log you in',
           template: 'Please, verify your data!'
         });
         console.log(erro);
       }

       // "Return"
       reject(false);
     });
   }
 })
};

在AngularJS中登录Facebook

$scope.FBLogin = function (){
firebase.auth().signInWithPopup(provider).then(function(result) {
  $scope.user.tokenFB = result.credential.accessToken;
  $scope.user.password = null;
  $scope.user.email = result.user.email;
  $scope.user.idFb = result.user.providerData[0].uid;
  $scope.checkingUser=true;



authenticate($scope).then(function(userExists){
  console.log("Welcome facebook user!")
})
.catch(function(failure){
  console.log("Ops, you don't have an account yet, let me solve this!")
  RegisterFB($scope).then(function(userRegistered){

    $scope.checkingUser=false;
    console.log("Done, now you have an account!");
    authenticate($scope).then(function(userExists){
  console.log("Welcome facebook user!")
})
  })
  .catch(function(failure){
    console.log("Sorry, an error occured")
    console.log(failure)

  })
});