angular.module('agileApp').service('UserAuthService', ['$rootScope', '$location', '$http', '$window', 'BackendService', '$interval', function($rootScope, $location, $http, $window, backendService, $interval) { var service = this; var isLoggedInState = false; var profile; var oauthtoken; //refresh every 45 minutes var refreshPromise = $interval(function() { if(isLoggedInState){ console.log("automatically refreshing"); gapi.auth.authorize({client_id: service.client_id, scope: service.scope, immediate: true }, function(oauth2) { $rootScope.$apply(function() { console.log("refreshed oauth2 per 45 minutes", oauth2); oauthtoken = oauth2; }); }); } }, 60*45*1000); this.client_id = '677067502417-4473u2kdf1vn6oknlq4u8denhsd54u0o.apps.googleusercontent.com'; this.scope = 'profile email'; this.isLoggedIn = function() { return isLoggedInState;} this.getProfile = function() { return profile;} this.getOauthToken = function() { return oauthtoken;} this.getProfileImage = function() { return profile.picture; } this.logout = function() { if(gapi.auth) { gapi.auth.signOut(); } if(oauthtoken) { $http.jsonp("https://accounts.google.com/o/oauth2/revoke?token=" + oauthtoken.access_token).then(function(response) { }, function(errorResponse) { //its always going to fail, no jsonp or cross origin calls for that endpoint }); isLoggedInState = false; $location.path('/'); $window.location.reload(); } $window.localStorage.clear(); isLoggedInState = false; $location.path('/'); } this.refreshToken = function(callback) { console.log(oauthtoken.expires_at); if(oauthtoken.expires_at * 1000 > new Date().getTime()) { console.log("token still good, not refreshing"); if(callback) { callback(); } return; } gapi.auth.authorize({client_id: service.client_id, scope: service.scope, immediate: true }, function(oauth2){ $rootScope.$apply(function() { console.log("refreshed oauth2", oauth2); oauthtoken = oauth2; if(callback) { callback(); } }); }); } this.startoauthSignin = function() { console.log(service.client_id); gapi.auth.authorize({ client_id: service.client_id, scope: service.scope, immediate: false }, function(oauth2){ $rootScope.$apply(function() { oauthtoken = oauth2; }); gapi.client.oauth2.userinfo.get().execute(function(resp) { if(resp){ console.log("profile:",resp); $rootScope.$apply(function() { profile = resp; if(profile && !profile.code && oauthtoken) { isLoggedInState = true; $location.path('/tasks') } else { service.logout(); }}); } }); }); } }])