.service('googleLogin', ['$http', '$rootScope', function ($http, $rootScope) {
var clientId = '{MY CLIENT KEY}',
apiKey = '{MY API KEY}',
scopes = 'https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds',
domain = '{MY COMPANY DOMAIN}';
this.handleClientLoad = function () {
// Step 2: Reference the API key
gapi.client.setApiKey(apiKey);
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
};
this.checkAuth = function() {
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true, hd: domain }, this.handleAuthResult );
};
this.handleAuthResult = function(authResult) {
if (authResult && !authResult.error) {
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function (resp) {
console.log(userEmail);
});
});
}
};
this.handleAuthClick = function (event) {
// Step 3: get authorization to use private data
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false, hd: domain }, this.handleAuthResult );
return false;
};
}]);
$scope.login = function () {
googleLogin.handleAuthClick();
};
.service('googleLogin', ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
var clientId = '{MY CLIENT ID}',
apiKey = '{MY API KEY}',
scopes = 'https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds',
domain = '{MY COMPANY DOMAIN}',
userEmail,
deferred = $q.defer();
this.login = function () {
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false, hd: domain }, this.handleAuthResult);
return deferred.promise;
}
this.handleClientLoad = function () {
gapi.client.setApiKey(apiKey);
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
};
this.checkAuth = function() {
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true, hd: domain }, this.handleAuthResult );
};
this.handleAuthResult = function(authResult) {
if (authResult && !authResult.error) {
var data = {};
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function (resp) {
$rootScope.$apply(function () {
data.email = resp.email;
});
});
});
deferred.resolve(data);
} else {
deferred.reject('error');
}
};
this.handleAuthClick = function (event) {
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false, hd: domain }, this.handleAuthResult );
return false;
};
}]);
var promise = googleLogin.login();
promise.then(function (data) {
console.log(data.email);
}, function (reason) {
console.log('Failed: ' + reason);
});
Right now I'm working on an AngularJS/RequireJS project, using the Google API Javascript Client for authentication/user info. I'm using the Google API for users to login, and then get their email address/contacts. I'm currently doing this in a service...