首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于Protractor的Google认证

基于Protractor的Google认证
EN

Stack Overflow用户
提问于 2017-04-26 16:22:34
回答 1查看 1.3K关注 0票数 1

我只能追踪到this link来解决我的问题。我试图使用量角器运行e2e测试。这是我的第一次尝试,我喜欢它。但是,我的项目需要Google身份验证,然后一旦经过认证,我将其与我的数据库进行比较,以确保用户在项目中。我无法从堆栈溢出帖子中知道如何调用Google页面对象,demee在最后一个答案中提到了这个对象。另外,第一个人说要查找元素by.id('Email')和by.id('Passwd')可能是个问题,因为我的google正在另一个窗口出现。所以我不知道怎么用量角器打电话。下面是我在gapi加载之后初始化$window后的一些代码:

代码语言:javascript
复制
.controller('ContainerController', ['$scope', '$rootScope', '$state','$window', '$location','employeeFactory', 'employeeTestFactory', function ($scope, $rootScope, $state, $window,$location, employeeFactory, employeeTestFactory) {
        $rootScope.callRequests=function(){};
        $rootScope.callInfo=function(){};
        if(typeof $rootScope.gapi !== "undefined")gapi.load('client:auth2', initClient);
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
            if(typeof $rootScope.gapi === "undefined") return;
            gapi.load('client:auth2', initClient);
        })
        $scope.$state = $state;
        $window.initGapi = function() {
            gapi.load('client:auth2', initClient);
            $rootScope.gapi = gapi;
        }
        $rootScope.calculateUsed = function(val){
            $rootScope.employee.timePending = $rootScope.employee.timePending = 0;
            var newTimeUsed = 0;
            angular.forEach(val, function(key, value){
                var td = key.timeDuration;
                if(key.timeState === "pending"){
                    $rootScope.employee.timePending += Number(td);
                }else{
                    newTimeUsed += Number(td);
                }
            });
            $rootScope.employee.totalTimeUsed = newTimeUsed;
        }

        $scope.employeeType = $rootScope.email = "";
        function initClient() {
            gapi.client.init({
                apiKey: 'AIzaSyDaMf0eviuFygt1hzwQz03a2k2lrLDnpIc',
                discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
                clientId: '977491754644-954b83j2evmq65v6kchq4dsd9j0ud4vg.apps.googleusercontent.com',
                scope: 'profile'
            }).then(function () {                    gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);                    updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
                $scope.employee = [];
            });
        }

        function updateSigninStatus(isSignedIn) {
            if (isSignedIn) {
                getEmailAddress();
            }else{
                $state.go('app');
            }
        }

        $scope.handleSignInClick = function(event) {
            if(!gapi.auth2.getAuthInstance().isSignedIn.get()){
                gapi.auth2.getAuthInstance().signIn();
            }
        }

        $scope.handleSignOutClick = function(event) {
            if(gapi.auth2.getAuthInstance().isSignedIn.get()){
                gapi.auth2.getAuthInstance().signOut();
            }
        }

        function getEmailAddress() {
            gapi.client.people.people.get({
                resourceName: 'people/me'
            }).then(function(response) {

                $rootScope.email = response.result.emailAddresses[0].value;
                $rootScope.callRequests();
                $rootScope.callInfo();
        //Here is where I compare google to my db and route users back to main if not in db                employeeTestFactory.get($rootScope.email).then(function(message) {
                    if(typeof message.employeeid === "undefined"){
                        $state.go('app');
                    }else if($location.path() === "/"){
                        $state.go('app.employee');
                        $rootScope.employee = message;

                    }else{
                        $rootScope.employee = message;

                    }
                });

            }, function(reason) {
                console.log('Error: ' + reason.result.error.message);
            });
        }
    }])

    .controller('LoginController', ['$scope', '$state', '$window', '$http','$rootScope', '$timeout', 'GooglePlus', 'gapiService', function ($scope, $state, $window, $http, $rootScope, $timeout, GooglePlus, gapiService) {

        $scope.$state = $state;
        $scope.callme = function(){
            $scope.handleSignInClick();
        }


        // if it could not be loaded, try the rest of
        // the options. if it was, return it.

        var url;
        var windowThatWasOpened;

        $http.get("url").then(function(response) {
            url = response.data;
        });

        $scope.login = function() {
            windowThatWasOpened = $window.open(url, "Please sign in with Google", "width=500px,height=700px");
        }


        window.onmessage = function(e) {

            if(windowThatWasOpened) windowThatWasOpened.close();
            var urlWithCode = e.data;

            var idx = urlWithCode.lastIndexOf("code=");
            if(idx === -1) return;
            var code = urlWithCode.substring(idx + 5).replace("#","");

            $http.get("token?code=" + code).then(function(response) {
                var userurl = 'https://www.googleapis.com/plus/v1/people/me?access_token='+response.data.access_token;
                $http.get(userurl).then(function(response) {
                    console.log("user info: "+JSON.stringify(response.data));
                })
            });


        } 
    }]) 

下面是我试图用以下代码导航到google的代码:

代码语言:javascript
复制
describe('Protractor Demo App', function() {
  it('should have a title', function() {
    browser.get('http://localhost:9000/');

    element(by.id('gLogin')).click().then(function(){
      Google.loginToGoogle();
    });

    expect(browser.getTitle()).toEqual('TrinityIT Time Off Tracking');

     browser.sleep(5000);
  });
});

这是我的conf文件:

代码语言:javascript
复制
exports.config = {
  framework: 'jasmine',
  specs: ['googlePage.js','spec.js'],
  onPrepare: function () {
    global.isAngularSite = function (flag) {
      console.log('Switching to ' + (flag ? 'Asynchronous' : 'Synchronous') + ' mode.')
      browser.ignoreSynchronization = !flag;
    },
      global.BROWSER_WAIT = 5000;
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-27 08:43:39

假设您希望做的是测试您的应用程序,而不是测试OAuth对话,那么有一个更简单的方法。

首先是一个OAuth刷新器,完成所有OAuth内容的全部目的是,您最终可以在Google中包含一个访问令牌,该令牌可以作为一个“授权:无记名xxxxx”HTTP头(例如。驱动器、YouTube、日历等)请求。所以,如果你有一个访问令牌,你可以绕过所有的OAuth内容,你的应用程序将是活跃的,并能够接受测试。

因此,您需要的是一种自动获取访问令牌的方法。这很简单。在某个地方,无论是在应用程序代码中还是在Protractor序言脚本中,您都需要摄入一个刷新令牌,并使用它生成一个可供应用程序使用的访问令牌。

我使用的是一个文件refreshtoken.js,出于安全原因,我不会将它签入git。refreshtoken.js

代码语言:javascript
复制
var refreshtoken="1x97e978a7a0977...";
var client_id="423432423@gfgfd";

如果您查看How do I authorise an app (web or installed) without user intervention? (canonical ?)的答案,您将看到获取刷新令牌的步骤,在底部将看到一些JavaScript,以演示如何使用刷新令牌来获取访问令牌。这看起来可能是很多步骤,但你只做过一次,所以并不是太繁琐。

这种方法绕过了OAuth,如果要测试的是特定的OAuth,也不是答案。然而,它确实允许您以更健壮的方式测试应用程序。它还具有用于Karma单元测试和量角器e2e测试的优点。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43639694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档