Google Auth stopped working after 2 years - javascript

I've got the following code snippet:
// Google functions
var clientId = 'clientid';
var apiKey = 'apikey';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
// Step 2: Reference the API key
gapi.client.setApiKey(apiKey);
gapi.client.load('calendar', 'v3', function () {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
console.error(authResult.error);
if (authResult && !authResult.error) {
if (!$('#authWait').is(':visible')) {
$('#start').on("click", function () {
$('#main').hide();
$('#wizard').removeClass("hidden");
});
} else {
$('#authWait').addClass("hidden");
$('#wizard').removeClass("hidden");
}
fillCalendarList();
ga('send', 'event', 'weergaveResultaat', 'action');
} else {
$('#start').on("click", function () {
$('#main').hide();
$('#authWait').removeClass("hidden");
handleAuthClick();
})
}
}
I've replaced the clientid and apikey. The exact snippet above has been working for 2 years in the exact same configuration. As of yesterday however I'm getting back 'immediate failed' right after the handleAuthResult.
I couldn't find any details of changes Google made since yesterday. I've tried switching immediate to false, but that didn't solve anything.
After the immediate failed I get 'Uncaught TypeError: Cannot set property 'apiVersion' of undefined'.
Anyone know what is causing this?

Related

VueJS this.progress is undefined inside window function

I'm using a Facebook login and I'm showing progress loading for the user until I get a response back from Facebook for authentication.
But I used to hide the progress bar like this.progress = false but this variable is undefined inside the window function.
My code :
initFacebook() {
this.progress=true
window.fbAsyncInit = function() {
window.FB.init({
appId: "MY-APP-ID", //You will need to change this
cookie: true, // This is important, it's not enabled by default
version: "v2.6",
status: false,
});
window.FB.login(function(response) {
if (response.status === 'connected'){
window.FB.api('/me?fields=id,name,email', function(response) {
console.log( response) // it will not be null ;)
})
} else {
console.log("User cancelled login or did not fully authorize.")
}
},
{scope: 'public_profile,email'}
);
this.progress = false
console.warn(this.progress)
};
},
I'm unable to set this.progress = false after getting all responses from Facebook.
I get an error while I console.log(this.progress) variable.
Error :
Login.vue?7463:175 undefined
How can I set this.progress variable to false once the authentication checks are complete?
Try converting all function() calls into arrow function calls () =>
The problem is that a function() will break the global vue scope. So vue this is not available within a function() call, but it is available within an arrow function () => {}
In a block scope (function() { syntax), this is bound to the nested scope and not vue's this instance. If you want to keep vues this inside of a function, use an arrow function (ES6) or you can have const that = this and defer the global this to that in a regular function() { if you prefer it this way.
Try using this code converted with arrow functions and see if it works:
initFacebook() {
this.progress=true
window.fbAsyncInit = () => {
window.FB.init({
appId: "MY-APP-ID", //You will need to change this
cookie: true, // This is important, it's not enabled by default
version: "v2.6",
status: false,
});
window.FB.login((response) => {
if (response.status === 'connected'){
window.FB.api('/me?fields=id,name,email', (response) => {
console.log( response) // it will not be null ;)
})
} else {
console.log("User cancelled login or did not fully authorize.")
}
},
{scope: 'public_profile,email'});
this.progress = false
console.warn(this.progress)
};
},
I know this because I just had the same problem :-) see here:
Nuxt plugin cannot access Vue's 'this' instance in function blocks

method().bind(this) + Angular4 getting Cannot read property 'myFun' of undefined

I'm integrating Google picker API in my application. I'm following the official documentation Google Picker API
I have successfully done my job, but after adding below code I am unable to use class methods and variables. Getting Cannot read property of undefined error
gapi.load('auth', {'callback': this.onAuthApiLoad.bind(a)});
Complete code is:
onApiLoad() {
var a= this;
gapi.load('auth', {'callback': this.onAuthApiLoad.bind(a)});
gapi.load('picker');
}
onAuthApiLoad() {
gapi.auth.authorize(
{
'client_id': this.clientId,
'scope': this.scope,
'immediate': false
},
this.handleAuthResult);
}
handleAuthResult(authResult) {
if (authResult && !authResult.error) {
if (authResult.access_token) {
var pickerBuilder = new google.picker.PickerBuilder();
var picker = pickerBuilder.
enableFeature(google.picker.Feature.NAV_HIDDEN).
setOAuthToken(authResult.access_token).
addView(google.picker.ViewId.DOCS).
setCallback(this.myFun).
build();
picker.setVisible(true);
}
}
}
myFun(e){
}
I have added below line to handle auth request
this.handleAuthResult.bind(this)

AngularJS tutorial Thinkster.io chapter 7

UPDATE: The tutorial was updated and the following question really no longer applies
Learning about AngularJS from the site thinkster.io (free ebook). But at the moment i'm stuck at chapter 7 - Creating your own user data using firebase. This is an tutorial about angularjs that works with firebase.
I have wrote all the code according to the site, but i'm getting these console errors when I want to register a user. It will create the user (in firebase -simplelogin), but not the user object (in firebase - data).:
TypeError: undefined is not a function
at Object.User.create (http://localhost:9000/scripts/services/user.js:46:19)
at http://localhost:9000/scripts/controllers/auth.js:32:22
etc.
This is the code (same as the site), the error is in the create() function and talks about the users.$save() function, snippet of User.create():
users.$save(username).then(function () {
setCurrentUser(username);
});
Complete code of user.js:
news.factory("User", function ($firebase, FIREBASE_URL, $rootScope, $log) {
var reference, users, User;
reference = new Firebase(FIREBASE_URL + "users");
users = $firebase(reference);
function setCurrentUser(username) {
$rootScope.currentUser = User.findByUsername(username);
}
$rootScope.$on("$firebaseSimpleLogin:login", function (event, authUser) {
var query = $firebase(reference.startAt(authUser.uid).endAt(authUser.uid));
query.$on("loaded", function () {
setCurrentUser(query.$getIndex()[0]);
});
});
$rootScope.$on("$firebaseSimpleLogin:logout", function () {
delete $rootScope.currentUser;
});
User = {
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username,
"$priority": authUser.uid
};
$log.debug(users);
users.$save(username).then(function () {
setCurrentUser(username);
});
},
findByUsername: function (username) {
if (username) {
return users.$child(username);
}
},
getCurrent: function () {
return $rootScope.currentUser;
},
signedIn: function () {
return $rootScope.currentUser !== undefined;
}
};
return User;
});
Edit 1:
Registering a user now works, got it working (saving in firebase, simple login and data):
users = $firebase(reference).$asObject();
Notice the users.save() function:
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username,
$priority: authUser.uid
};
$log.debug(users);
users.$save().then(function () {
setCurrentUser(users);
});
},
findByUsername: function (users) {
if (users) {
return users;
}
},
Edit 2:
Now I get an error at the log in of the user (see below), when I want to log in, I get an error on this this function, query.$on():
TypeError: undefined is not a function
at http://localhost:9000/scripts/services/user.js:26:19
$rootScope.$on("$firebaseSimpleLogin:login", function (event, authUser) {
var query = $firebase(reference.startAt(authUser.uid).endAt(authUser.uid));
query.$on("loaded", function () {
setCurrentUser(query.$getIndex()[0]);
});
});
What is wrong now?
This is an answer on edit 2: I have used firebase(ref), query.$loaded and searched for the right object, that's it. Maybe someone have an different answer, please post them :).
I have finally completed chapter 07!
In general (solution for Edit 2):
$rootScope.$on("$firebaseSimpleLogin:login", function (event, authUser) {
var query = $firebase(reference).$asObject();
query.$loaded(function (result) {
angular.forEach(result, function (key) {
if (key.md5_hash === authUser.md5_hash) {
setCurrentUser(key);
}
});
});
});
This is not the ideal solution, but the free ebook (atm of writing) is far from ideal. Then again, these kind of situations helps you to understand a little bit more about the firebase api and how it works with angular. But can be frustrated at times, when you just want to go through the tutorial ;).
Note! I have saved the User object and pass the User object to the findUsername() and setCurrentUser() functions instead of just the user.username.
You can also use the native array function, like some().
I think your system uses the newer version of Angularfire (version>= 0.8). Which means for running through loops that are arrays ...you need to attach .$asArray() at the end of the user definition field. Check the updates of Firebase.

Google app engine authorization returning null

I have the following code, which I am using successfully in another program
index.html
Eat Fresh
</html>
init.js
function init() {
CLIENT_ID = "927885761089.apps.googleusercontent.com"
SCOPES = ["https://www.googleapis.com/auth/userinfo.email"]
gapi.client.load('oauth2', 'v2', signin)
}
function signin() {
gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: true}, userAuthed)
}
function userAuthed() {
console.log(gapi.auth.getToken())
console.log(gapi.auth.getToken().accessToken)
gapi.client.oauth2.userinfo.get().execute(function(resp) {
checkEmail(resp)
})
}
function checkEmail(user) {
var validEmail = (whiteList.indexOf(user.email) !== -1)
if (!user.code && validEmail) {
startApp()
} else {
displayError(user.email)
}
}
gapi.auth.getToken() is returning null and to my knowledge that means that my I am not logged in. I don't know how to refresh the login or force a log out. Any help would be appreciated.
Changing the the following
gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: false}, userAuthed)
will prompt the user to give permission to the app, thus allowing for an authorized access token and for the remainder of the code to work.

#me called by anonymous error when using google plus api inside a gwt project

I'm using the google api javascript client to get information about the user profile inside a gwt project hosted in google app engine.
In localhost, the data is being retrieved correctly. I get a json with the google plus profile. When I deploy to appengine, the response is 401, "#me called by anonymous".
Here is my Code:
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
$(function() {
auth();
});
var API_KEY = "***************************************";
var CLIENT_ID = "************.apps.googleusercontent.com";
var scopes = 'https://www.googleapis.com/auth/plus.me';
function auth() {
var config = {
'client_id' : CLIENT_ID,
'scope' : scopes,
'key' : API_KEY,
};
gapi.client.load('plus', 'v1', function() {
api.client.setApiKey(API_KEY);
gapi.auth.authorize(config, function() {
var request = gapi.client.plus.people.get({
'userId' : 'me',
});
request.execute(function(resp) {
console.log(resp);
});
});
});
}
</script>
What i tried:
call to api.client.setApiKey at the begining.
create a new google api access with the google api console
update:
This is the complete response error message:
{
"error": {
"code": 401,
"message": "me called by anonymous",
"data": [
{
"domain": "global",
"reason": "authError",
"message": "me called by anonymous",
"locationType": "header",
"location": "Authorization"
}
]
},
"id": "gapiRpc"
}
There are other messages that may be related:
This is one of them:
Skipping duplicate osapi method definition chili.people.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition pos.plusones.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition chili.activities.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition googleapis.newHttpRequest on transport googleapis; others may exist, but suppressing warnings
this is the other:
Invalid auth token. 1025***** vs 140186****
I could finally resolve the issue with the following settings or steps:
1) In the google apis console, I left the Redirect URIs section empty and completed the JavaScript origins section with the url of my site, repeating it with the https protocol:
JavaScript origins:
http://example.com
https://example.com
I put the script that loads the api before the end body tag:
<script src="https://apis.google.com/js/client.js"></script>
This script comes inside the body, before the api script:
<script type="text/javascript">
var API_KEY = "***************************************";
var CLIENT_ID = "************.apps.googleusercontent.com";
var scopes = 'https://www.googleapis.com/auth/plus.me';
function auth() {
var scopes = 'https://www.googleapis.com/auth/plus.me';
gapi.client.setApiKey(API_KEY);
window.setTimeout(checkAuth, 1000);
function checkAuth() {
gapi.auth.authorize({
client_id : CLIENT_ID,
scope : scopes,
immediate : false
}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
makeApiCall();
} else {
checkAuth();
}
}
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
$("#image").attr("src", resp.image.url);
});
});
}
}
</script>
Then I call the function auth() when the user clicks to see his picture.

Categories

Resources