如何在Mozilla Persona登录后更新登录用户

时间:2013-03-05 15:19:46

标签: javascript login angularjs mozilla browserid

我在项目中使用Mozilla Persona。我想在loggedInUser之后更新onlogin。但loggedInUser是传递给navigator.id.watch()的对象的属性。 navigator.id.watch()被调用一次(在AngularJS服务中)。 我应该再次调用它,传递整个对象吗?这似乎不对。我错了吗? = P

这是我的服务:

app.factory('persona', function ($rootScope, $http) {
navigator.id.watch({
    loggedInUser: null,
    onlogin: function onlogin(assertion) {
        console.log(this);
        $http.post('/signIn', { assertion: assertion })
            .then(function (data, status, headers, config) {
                $rootScope.$broadcast('signIn', data.data);
            }, function (data, status, headers, config) {
                $rootScope.$broadcast('signInError', data.data);
            });
    },
    onlogout: function onlogout(param) {
        $http.get('/signOut')
            .then(function (data, status, headers, config) {
                $rootScope.$broadcast('signOut', data.data);
            }, function (data, status, headers, config) {
                $rootScope.$broadcast('signOutError', data.data);
            });
    }
});

return {
    signIn: function signIn() {
        navigator.id.request();
    },
    signOut: function signOut() {
        navigator.id.logout();
    }
};
});

2 个答案:

答案 0 :(得分:3)

难道你不能让logsInUser成为全局或至少是“本地全局”,与navigator.id.watch方法的范围相同,就像MDN示例一样吗?

之后,您可以从Persona服务获取JSON响应,该服务包含一些数据,包括电子邮件。因此,您可以在AJAX响应上传递该数据并填充loggedInUser变量

https://developer.mozilla.org/en-US/docs/Persona/Quick_Setup#Step_3.3A_Watch_for_login_and_logout_actions

var currentUser = 'bob@example.com';

navigator.id.watch({
  loggedInUser: currentUser,
  onlogin: function(assertion) {
    $.ajax({ 
      type: 'POST',
      url: '/auth/login', // This is a URL on your website.
      data: {assertion: assertion},
      success: function(res, status, xhr) { window.location.reload(); },
      error: function(xhr, status, err) {
        navigator.id.logout();
        alert("Login failure: " + err);
      }
    });
  },
  onlogout: function() {
    $.ajax({
      type: 'POST',
      url: '/auth/logout', // This is a URL on your website.
      success: function(res, status, xhr) { window.location.reload(); },
      error: function(xhr, status, err) { alert("Logout failure: " + err); }
    });
  }
});

来自MDN的JSON响应示例:

{
  "status": "okay",
  "email": "bob@eyedee.me",
  "audience": "https://example.com:443",
  "expires": 1308859352261,
  "issuer": "eyedee.me"
}

答案 1 :(得分:0)

navigator.id.watch来电时,设置loggedInUser: localStorage.getItem('persona') || nullnull很重要),然后,当Persona登录成功时,执行localStorage.setItem('persona', theUserEmail),当失败时,执行localStorage.removeItem('persona')