Node JS for Google Mirror API - javascript

I am trying to implement the Oauth using Node JS for Glass Mirror API amd found this useful. In the "app.js" file, we need to provide the credentials of the project created in the Google developer console.
I have the client ID, client secret but am not able to define what should my callback URL be? What should be in the callback URL script? Logically I understand that there should be a program that accepts the token and runs the further steps.
But how to write one? kindly help.
Thanks in advance

base on the sample code from your link, the callback URL will be
// running in localhost
http://localhost/oauth2callback
// or running on your server
http://yourdomain.com/oauth2callback
when the google redirect to oauth2callback, your server code will run to redirect back to index page
grabToken(req.query.code, failure, function () {
res.redirect('/');
});

Related

Is there any way to save a full XHR payload in a cypress run?

We have our cypress suite working fine locally in every machine, environment, location.
We've configured it to work with a Bitbucket pipeline but there is a specific step that consistently fails because of the API call it makes. This API call is made to an external service and we are adding params in the payload that are dynamically built with the request.
Our suspicion is that there are some of these params that are not built correctly when running it from the pipeline (may be related to location, agent, etc) because we are getting "Unauthorized".
So the issue is that we don't have any way to debug this API call from the pipeline and it is the only place where it fails.
So, do you have any suggestions on how to save the XHR Payload in a step in Cypress?
Store it in a mocha report.
Send it via email.
Maybe add it to a log.
Save it as an artifact.
I'm sorry I'm just clueless how to approach this as I'm not an expert in neither cypress nor bitbucket pipelines.
More specifically, I need to debug this call:
As I understand, your external API call URL is known, right? If so, I would suggest for debugging purpose to route this call, then display it out in the cypress running logs, so you will be able to compare the request payloads:
cy.route({ method: 'POST', url: `/ps/users`}).as('routedRequest');
...
cy.get('#routedRequest').then((xhr) => {
cy.log(JSON.stringify(xhr.request))
});

facebook graph api node.js invalid appsecret_proof

this is my first post so please go easy on me!
I am a beginning developer working with javascript and node.js. I am trying to make a basic request from a node js file to facebook's graph API. I have signed up for their developer service using my facebook account, and I have installed the node package for FB found here (https://www.npmjs.com/package/fb). It looks official enough.
Everything seems to be working, except I am getting a response to my GET request with a message saying my appsecret_proof is invalid.
Here is the code I am using (be advised the sensitive info is just keyboard mashing).
let https = require("https");
var FB = require('fb');
FB.options({
version: 'v2.11',
appId: 484592542348233,
appSecret: '389fa3ha3fukzf83a3r8a3f3aa3a3'
});
FB.setAccessToken('f8af89a3f98a3f89a3f87af8afnafmdasfasedfaskjefzev8zv9z390fz39fznabacbkcbalanaa3fla398fa3lfa3flka3flina3fk3anflka3fnalifn3laifnka3fnaelfafi3eifafnaifla3nfia3nfa3ifla');
console.log(FB.options());
FB.api('/me',
'GET',
{
"fields": "id,name"
},
function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res);
console.log(res.id);
console.log(res.name);
}
);
The error I am getting reads:
{ message: 'Invalid appsecret_proof provided in the API argument',
type: 'GraphMethodException',
code: 100,
fbtrace_id: 'H3pDC0OPZdK' }
I have reset my appSecret and accessToken on the developer page and tried them immediately after resetting them. I get the same error, so I don't think that stale credentials are the issue. My
console.log(FB.options())
returns an appropriate looking object that also contains a long hash for appSecretProof as expected. I have also tried this code with a number of version numbers in the options (v2.4, v2.5, v2.11, and without any version key). Facebook's documentation on this strikes me as somewhat unclear. I think I should be using v2.5 of the SDK (which the node package is meant to mimic) and making requests to v2.11 of the graph API, but ??? In any case, that wouldn't seem to explain the issue I'm having. I get a perfectly good response that says my appSecretProof is invalid when I don't specify any version number at all.
The node package for fb should be generating this appSecretProof for me, and it looks like it is doing that. My other info and syntax all seem correct according to the package documentation. What am I missing here? Thank you all so much in advance.
looks like you have required the appsecret_proof for 2 factor authorization in the advance setting in your app.
Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the client. An access token can also be stolen by malicious software on a person's computer or a man in the middle attack. Then that access token can be used from an entirely different system that's not the client and not your server, generating spam or stealing data.
You can prevent this by adding the appsecret_proof parameter to every API call from a server and enabling the setting to require proof on all calls. This prevents bad guys from making API calls with your access tokens from their servers. If you're using the official PHP SDK, the appsecret_proof parameter is automatically added.
Please refer the below url to generate the valid appsecret_proof,and add it to each api call
https://developers.facebook.com/docs/graph-api/securing-requests
I had to deal with the same issue while working with passport-facebook-token,
I finally released that the problem had nothing to have with the logic of my codebase or the app configuration.
I had this error just because I was adding intentionally an authorization Header to the request. so if you are using postman or some other http client just make sure that the request does not contain any authorization Header.

Google api php client code not return refresh token

I have been trying to get refresh token from google api using javascript google client " code " that google return from client side. It returns me the code which i send to the server side. Now from server side i am sending the code to get the refresh token and access token using using google-api-php-client with this call :
https://www.googleapis.com/oauth2/v4/token
While i use the same code from google playground i get the response with refresh token as well but i do not get it from my own server..
This is the code
public function getRefreshToken($code)
{
$client = new Google_Client();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$client->setRedirectUri('postmessage');
$client->setScopes(config('services.google.scopes'));
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
dd($client->authenticate($code));
dd($client->getRefreshToken());
return ;
}
I have set access type to offline as mentioned in some answers but still i get the response with our refresh token.. this is the response
access_token :"xxxxxxxxxxxxxxxxxxxxxx"
created:1510242052
expires_in:3598
id_token:"xxxxxxxx"
token_type:"Bearer"
Your php code looks fine to me. I suspect your front end javascript, specifically the link to google that it builds, may be to blame. Whether the authorization_code produces a refresh token when redeemed is partially dependent on what parameters are included in the initial link to Google.
As detailed in this answer, the javascript client library uses "client side flow". Normally in a front end app you'd specify response_type=token, but if you specify response_type=code, instead, you'll get a code back. But when redeemed, that code will not produce a refresh token.
For example, a link built by a front end javascript library might look like this:
https://accounts.google.com/o/oauth2/v2/auth?client_id=7xxxxxxxxxxx-xxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://localhost:8080/oauth2callback.php&response_type=code&scope=profile
Your back end can redeem the code that comes back, but the response will not include a refresh token. This is by design.
One way to get a code that is eligible for refresh tokens, would be to use the back end PHP client library to build the link, rather than the javascript client library. $client->createAuthUrl() will build a link like this:
https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=7xxxxxxxxxx-hxxxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2callback.php&state&scope=profile&approval_prompt=force
This toy example builds the link this way and does receive refresh tokens.
Note the addition of access_type=offine and approval_prompt=force. After successful authentication, the redirect in this case includes a code that does provide a refresh token when redeemed.
The OAuth 2.0 playground builds an initial link that contains access_type=offline and prompt=consent, which also creates a code that is redeemable for a refresh token.
If this isn't helpful, perhaps you could update the question with the link to google that your front end is building? (With client id redacted, of course)

Google Drive API - download file issue (javascript, php)

I am trying to download a file from Google Drive to my harddrive. The entire authentication is done in JavaScript and I am receiving a response from the server:
request = gapi.client.drive.files.get({'fileId': id});
request.execute(function(resp) { ........ }
I have the correct scope in order to be allowed to download files:
https://www.googleapis.com/auth/drive
Also the request above is returning me a downloadUrl.
I am trying to send the downloadUrl to PHP, but the download process is failing with a 401 error.
Any suggestion? I have tried to download the file directly in Javascript, but I didn't find a good solution yet.
Thanks and let me know if you have any question.
It is my first question here since this one is killing me :D
Is this a public file or a private file? Are you sending the right auth token to GDrive within PHP? Are there any other warnings/errors along with the 401?
401 with the GDrive API means that you are providing invalid credentials. You must not be supplying the right auth within PHP, or at least not the same auth as you did with JS.
Thank you everyone for your help. This topic help me a lot :
Newbie Google Drive API (PHP) confusion - what guide/library to use?
The problem was indeed auth in PHP, or better, the lack of it.

Socket.io - server down handling

I am trying to write simple app that serves data using socket.io and node.js on server side. I would like to inform user if server is down (e.g. server serves webpage to the client and before any refresh server is halted). For now it results in browser giving following error:
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1409325689935-6 net::ERR_CONNECTION_REFUSED
I wasn't able to catch that event using socket.on('error'(...)) event and I would like to display some message as long as client fails to connect to server. Any ideas would be appreciated :) Code initializing socket is provided below:
socket = io.connect(document.domain, {
'sync disconnect on unload' : false
});
Couldn't you just check if the server serves you the .js file by doing something like this?
<script type="text/javascript" onload="loaded()" src="get_socket.js"></script>
function loaded(){
//this will only execute if the server is up
}
I have successfully used this following code for not only socket.io but any .js you wish to load, execute, or both. Please forgive me as I have long forgotten where I originally got this from, most likely this very website.
Please note that I have only tailored the loadAndExecute function to handle inability to load your file, via callback.
var load,execute,loadAndExecute;
load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},
execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},
loadAndExecute=function(a,b,c){return load(a,function(){return execute(b)},function(){return c();})};
Use as such:
loadAndExecute("domain.com:80/socket.io/socket.io.js", function() {
//it loaded, put main code here
},
function(){
//failed to load, put error display code here
});
Hopefully this can help someone like it helped me so many times.

Categories