Google登录 - 注销刷新 [英] Google Sign In - Signing out on refresh

查看:92
本文介绍了Google登录 - 注销刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置:

.service('googleService', ['$q', function ($q) {
    var self = this;

    this.load = function(){
        var deferred = $q.defer();
        gapi.load('auth2', function(){
            var auth2 = gapi.auth2.init();
            auth2.then(function(){ deferred.resolve(); });
            addAuth2Functions(auth2);
        });
        return deferred.promise;
    };

    function addAuth2Functions(auth2) {

        self.isSignedIn = function(){
            return auth2.isSignedIn.get();
        }

        self.signOut = function(){
            var deferred = $q.defer();
            auth2.signOut().then(deferred.resolve, deferred.reject);
            return deferred.promise;
        };

        self.getProfile = function() {
            if(auth2.isSignedIn.get()) return { signed_in: true, access_token: auth2.currentUser.get().Zi.id_token,profile: auth2.currentUser.get().getBasicProfile() };
            else return { signed_in: false };
        }

    }

}])

.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise('/cloud');

    var guest = ['$q', '$rootScope', '$stateParams', 'googleService', function ($q, $rootScope, $stateParams, googleService) { 

        var deferred = $q.defer(); 

        googleService.load().then(function(){ 
            $q.when(googleService.isSignedIn()).then(function(r){ 
                if(r) deferred.reject(); 
                else deferred.resolve(); 
            }) 
        }); 

        return deferred.promise; 
    }];

    var authenticated = ['$q', '$rootScope', '$stateParams', 'googleService', function ($q, $rootScope, $stateParams, googleService) { 

        var deferred = $q.defer(); 

        googleService.load().then(function(){ 
            $q.when(googleService.getProfile()).then(function(p) { 
                if(p.signed_in) { 
                    deferred.resolve(); 
                    localStorage['access_token'] = p.access_token;
                    $rootScope.profile = p.profile; 
                } else deferred.reject(); 
            }) 
        }); 

        return deferred.promise; 
    }];

    $stateProvider

    .state('login', {
        url: '/',
        views: { 'main': { templateUrl: 'pages/templates/login.html', controller: 'login' } },
        resolve: { authenticated: guest }
    })

    .state('cloud', {
        url: '/cloud',
        views: { 'main': { templateUrl: 'pages/templates/cloud.html', controller: 'cloud' } },
        resolve: { authenticated: authenticated }
    })

})

.controller('login', ['$rootScope', '$scope', '$q', '$state', 'googleService', function ($rootScope, $scope, $q, $state, googleService) {
    $scope.options = { 'onsuccess': function(response) { $state.go('cloud'); } }
}])

.controller('cloud', ['$rootScope', '$scope', '$timeout', '$http', '$httpParamSerializerJQLike', function ($rootScope, $scope, $timeout, $http, $httpParamSerializerJQLike) { 

}]);

基本上发生的事情是,当我使用谷歌登录按钮登录时,它会登录并且 googleService.getProfile()表示我已登录。

Basically what is happening is, when I sign in using the google sign in button, it signs in and googleService.getProfile() says that I am signed in.

但是,如果我刷新页面, googleService.isSignedIn()返回false。

However, if I refresh the page, googleService.isSignedIn() returns false.

任何人都可以看到为什么它会返回false的问题?还有什么我需要做的才能确保谷歌记住我吗?

Can anyone see an issue in why it would be returning false? Is there something else I need to do to make sure google remembers me?

推荐答案

你的主要问题似乎是你是通过 googleService.load()一遍又一遍地调用 gapi.auth2.init()

Your main problem appears to be that you're calling gapi.auth2.init() over and over again via googleService.load().

我的建议是存储初始化承诺以便重复使用,而不是多次创建。

My suggestion is to store the initialisation promises for re-use instead of creating it many times.

你还需要添加一个条件来处理过期的访问令牌。

You'll also need to add a condition to handle an expired access token.

.service('googleService', ['$q', function ($q) {
    const auth2InitPromise = $q(function(resolve) {
        gapi.load('auth2', function() {
            var auth2 = gapi.auth2.init();
            auth2.then(function() {
                resolve();
            });
        })
    });

    this.isSignedIn = function() {
        return auth2InitPromise.then(function() {
            return gapi.auth2.getAuthInstance().isSignedIn.get();
        });
    };

    this.signOut = function() {
        return auth2InitPromise.then(function() {
            const auth2 = gapi.auth2.getAuthInstance();
            return $q(function(resolve, reject) {
                auth2.signOut().then(resolve, reject);
            });
        });
    };

    this.getProfile = function() {
        return this.isSignedIn().then(function(isSignedIn) {
            if (isSignedIn) {
                const currentUser = gapi.auth2.getAuthInstance().currentUser.get();
                const authResponse = currentUser.getAuthResponse();
                return $q.when(authResponse.expires_at > Date.now() ? authResponse : currentUser.reloadAuthResponse()).then(function(ar) {
                    return {
                        signed_in: true,
                        access_token: ar.id_token,
                        profile: currentUser.getBasicProfile()
                    }                        
                });
            } else {
                return { signed_in: false };
            }
        });
    };

}])

您的每种服务方法( isSignedIn signOut getProfile )现在返回一个只能解析一次的承诺 auth2 API已初始化,但现在只发生一次。

Each of your service's methods (isSignedIn, signOut and getProfile) now return a promise that only resolves once the auth2 API is initialised however this only ever happens once now.

例如

var authenticated = ['$q', '$rootScope', '$window', 'googleService', function ($q, $rootScope, $window, googleService) {
    return googleService.getProfile().then(function(p) {
        if (p.signed_in) {
            $window.localStorage.setItem('access_token', p.access_token);
            $rootScope.profile = p.profile;
            return true; // resolvers should always resolve with something   
        } else {
            return $q.reject();
        }
    });
}];

这篇关于Google登录 - 注销刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆