Authentication issue with simple upload on Google Drive API - javascript

I'm trying to upload a file to my Google Drive file space, and I'm using the following code:
var httpRequest = new XMLHttpRequest();
var url_goto = "https://www.googleapis.com/upload/drive/v2/files?uploadType=media";
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState==4 && httpRequest.status==200) {
Firebug.Console.log(httpRequest.responseText);
} else if (httpRequest.readyState==4 && httpRequest.status==401) {
Firebug.Console.log(httpRequest.responseText);
} else {
Firebug.Console.log('Other status: ' + httpRequest.readyState + ', ' + httpRequest.status);
}
};
var s = 'Test string';
httpRequest.open('POST', url_goto, true);
httpRequest.setRequestHeader('Content-Type', 'text/plain');
httpRequest.setRequestHeader('Content-Length', s.length);
httpRequest.setRequestHeader('Authorization', 'MY_AUTH_KEY');
httpRequest.send(s);
The problem is that I've the following output:
"Other status: 1, 0"
"Other status: 1, 0"
"Other status: 2, 401"
"Other status: 3, 401"
...and an exception is thrown:
"{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}"
Can anybody help me to understand why authentication is not working?
I'm using the API Key retrieved from my Google APIs Console, under section Simple API Access.
Thanks!

If you are using oauth2 token then you must specify the Bear along with auth token in Authorization header like
httpRequest.setRequestHeader("Authorization", "Bearer MY_AUTH_KEY");

Related

How to solve "There was a problem with the requested skill's response" in Alexa Developer Console

I'm trying to build a simple app for Alexa where user says the invocation name (voice control unity) and then say the utterance (temp world) described in custom intent (TempIntent) to get the output using buildSpeechletResponse i.e(temp request).
But I'm getting "There was a problem with the requested skill's response" error in Test tab in Alexa Developer Console.
I've already tried changing the intent name, invocation name, function name but nothing is working.
//This is index.js file lambda function
function onLaunch(launchRequest, session, response)
{
var output = 'Welcome to Temp World';
var reprompt = 'Type temp world';
response(session.attributes,
buildSpeechletResponseWithoutCard(output, reprompt,false));
console.log("onLaunch requestId=" + launchRequest.requestId
+ ", sessionId=" + session.sessionId);
}
function onIntent(intent, session, response) {
console.log("onIntent requestId=" + intent.requestId
+ ", sessionId=" + session.sessionId);
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
if(intentName == 'TempIntent') {
handleTempRequest();
}
else {
throw "Invalid intent";
}
}
function handleTempRequest()
{
buildSpeechletResponse("", "welcome to temp world", "", true);
}
function buildSpeechletResponse(title, output, repromptText,
shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
card: {
type: "Simple",
title: title,
content: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
I expected the output to be "welcome to temp world" but the JSON output is null.
JSON Input is
"request": {
"type": "SessionEndedRequest",
"requestId": "amzn1.echo-api.request.c78c093c-eb05-4eaa-8f23-16037059e61f",
"timestamp": "2019-05-09T12:23:34Z",
"locale": "en-US",
"reason": "ERROR",
"error": {
"type": "INVALID_RESPONSE",
"message": "An exception occurred while dispatching the request to the skill."
}
}
Image showing Alexa conversation
Check the version of node.js you are using.
In the lambda function click on the test tab and test every intent, there you will find the problem.

Google API Batch returns 401

Doing two or more requests in one batch at once leads to a 401 for each request.
const batch = gapi.client.newBatch();
batch.add(gapi.client.drive.files.list());
batch.add(gapi.client.drive.files.list());
batch.then((e) => {
console.log(e);
});
The error is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Using only one batch.add works perfectly fine. It doesn't make any sense to me.
Why? What do I do wrong?
Directly from the documentation handle errors
401: Invalid Credentials
Invalid authorization header. The access token you're using is either expired or invalid.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Suggested action: Refresh the access token using the long-lived refresh token. If this fails, direct the user through the OAuth flow, as described in Authorizing Your App with Google Drive.
Batch documentation.
var searchRequest = function(name) {
return gapi.client.request({
'path': 'plus/v1/people',
'params': {'query': name}
});
};
var searchAlvin = searchRequest('Alvin');
var searchSimon = searchRequest('Simon');
// Adding just the request
batch.add(searchAlvin);
// Adding the request with an ID
batch.add(searchSimon, {'id': 'searchSimon'});

In Google Directory API, how do I add a user using javascript?

I have the Google Directory API Javascript quickstart working. This part of the code lists the first 10 users in the directory:
gapi.client.directory.users.list({
'customer': 'my_customer',
'maxResults': 10,
'orderBy': 'email'
}).then(function(response) {
var users = response.result.users;
appendPre('Users:');
appendPre('test')
if (users && users.length > 0) {
for (i = 0; i < users.length; i++) {
var user = users[i];
appendPre('-' + user.primaryEmail + ' (' + user.name.fullName + ')');
}
} else {
appendPre('No users found.');
}
});
I want to add a user to the directory. It looks like this is done using users: insert. So after removing the 'readonly' part from the scope, I replace the above code snippet with this:
var user = {
"password": "Testpass123",
"primaryEmail": "albert.smith#mydomain.com",
"name": {
"givenName": "albert",
"familyName": "smith"
}
};
gapi.client.directory.users.insert(user);
Obviously this does not work, but I am unsure what I am missing. There is a "Try this API" tool on the users:insert reference page, and when I plug in the properties of 'user' in the "request body" field, it adds the user.
I'm not sure how to make a request body though, and I can't find a solution in the docs. The users:list method does not need a request body. I tried something like this, which also didn't work:
gapi.client.request({
'path': 'https://www.googleapis.com/admin/directory/v1/users',
'method': 'POST',
'body': user
});
Hoping someone can give me at least a general idea of what to do. I'm pretty new at this.
Try this dummy data derived from Apps Script's Admin SDK Add user and replace with your correct details:
sample request body:
var user = {
primaryEmail: 'liz#example.com',
name: {
givenName: 'Elizabeth',
familyName: 'Smith'
},
// Generate a random password string.
password: Math.random().toString(36)
};
Try wrapping the user object in a resource object like:
var user = {
resource: {
"password": "Testpass123",
"primaryEmail": "albert.smith#mydomain.com",
"name": {
"givenName": "albert",
"familyName": "smith"
}
}
}
I can't find a reference for this anymore so maybe someone else can post but it is working for me.
Based on https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/insert :
function execute() {
return gapi.client.directory.users.insert({
"resource": {
"name": {
"familyName": "Shmoger",
"givenName": "Joey"
},
"password": "ShmoeyJoey!",
"primaryEmail": "shmogerjoe#grower.com"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}

JavaScript Send JSON to Google API

I am new to the Google API (Calendar V3) and I have the authorization through obtaining a token working. I am using a get request to get the users calendar_Id in which I want to send in a POST request in order to add an event to the calendar.
Here is what I am working with:
var json_body = {
"end": {
"date": "2013-09-06"
},
"start": {
"date": "2013-09-06"
},
"summary": "test event 1"
};
var json_string = JSON.stringify(json_body);
http.setRequestHeader("Content-Type", "application/json");
http.setRequestHeader("Authorization","Bearer " + access_key);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert("in here");
alert(http.responseText);
}
}
http.send(json_string);
The response I am getting is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
I know that the access_key authorization header is correct since it is not giving me the authorization error. I have ran this JSON structure in Googles API Explorer tool and it adds an element to my calendar correctly. I am assuming that the way I am building my JSON is incorrect. Any ideas?
Thank you in advance.
EDIT:
I found the correct solution. I was mis-using a parameter in the url request. The code above works in case anyone stumbles upon this for reference in the future.

Facebook Graph API returns object with missing data

I'm currently trying to get the total number of "likes" from a post. If I query the post via the Graph API Exporer, the data is there under likes.data.count. From my javascript application, the returned object only contains "id" and "created_time".
I have checked using the access token debugger and I have permissions to access user_likes and friends_likes so I am really at a loss to what's missing. However, I do suspect that this is a permissions issue. Does anyone know why I can't get the likes count on a post?
My query looks like this:
FB.api(postid + "?fields=likes",
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured' + response.error);
} else {
alert("got response: " + JSON.stringify(response));
likecount = response.likes.data.count;
alert('likecount: ' + likecount);
}
});
And my initialization code looks like this:
FB.init({ appId: '373915339387251',
status: true,
cookie: true,
xfbml: true,
oauth: true});
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me,user_likes,friends_likes'});
}
An example of response data received is this (Extracted from here):
"likes": {
"data": [
{
"name": "Mia Lusiana",
"id": "100003399221230"
},
{
"name": "Habeeb Quazi",
"id": "525927716"
},
{
"name": "Mert Vrss",
"id": "100002500864051"
},
{
"name": "Nav",
"id": "100000757486687"
}
],
"count": 8145
as you can see, count is inside likes, not inside data, so it must be this way:
likecount = response.likes.count;
data contains people that liked the post.

Categories

Resources