Connect to google search console API from Node.js - javascript

I am trying to get data from google search console https://www.googleapis.com/webmasters/v3/sites but from Node backend not the front end, I have created OAuth 2.0 Client IDs and API key on the google api console. But I can find the way to connect.
I am following this guide https://googleapis.dev/nodejs/googleapis/latest/searchconsole/index.html
I just want to be able to make read requests from node.
I tried this
import { google } from 'googleapis'
const auth = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
google.options({ auth })
const searchconsole = google.webmasters({ version: 'v3', auth })
const sites = await searchconsole.sites.list({})
console.log(sites)
I get this error even thou all the credentials are correct
'Error: No access, refresh token, API key or refresh handler callback is set.'

According to the comments, seems you already got the authorization pieces working, now, if you want to list the sites to get search analytics data for each owned site by the authorizing user, you can do something like the following code:
Use Google Search Console API                                                                                
Run in Fusebit
const webmasters = googleClient.webmasters('v3');
// List the owned sites
const sites = await webmasters.sites.list({});
const sitesAnalytics = [];
for await (const site of sites.data.siteEntry) {
const response = await webmasters.searchanalytics.query({
siteUrl: site.siteUrl,
requestBody: {
startDate: '2021-01-01',
endDate: new Date().toISOString().split('T')[0],
},
});
sitesAnalytics.push({ site, analytics: response.data});
}
console.log = `Got a successful response from Google Search Console: ${JSON.stringify(sitesAnalytics)}`;

Related

endpoints_resolution_error in msal react

I was trying to acquire token from our Microsoft tenant. I have no knowledge about the Azure AD or whatsoever, because I only tasked to develop front end for our Microsoft Dynamics App in React. I only got some of the credential like tenant id, client id, client secret and resource.
I used MSAL Node library and function ConfidentialClientApplication() to acquire the token
But when I check it in the Ms. Edge's console log it throw an error
{"errorCode":"endpoints_resolution_error","errorMessage":"Error: could
not resolve endpoints. Please check network and try again. Detail:
ClientAuthError: openid_config_error: Could not retrieve endpoints.
Check your authority and verify the .well-known/openid-configuration
endpoint returns the required endpoints. Attempted to retrieve
endpoints from: verify
url","subError":"","name":"ClientAuthError","correlationId":""}
When I click the veryfy url (Cannot show you the url because it might contain sensitive information)
It shows all the metadata of the open id so I thought maybe it's normal.
But why is the error endpoints_resolution_error throwed when everything is normal?
Here is some snapshot of my code
const config = {
auth: {
clientId: clientID
authority: "https://login.microsoftonline.com/{tenantID}/",
clientSecret: clientSecret,
knownAuthorities: ["login.microsoftonline.com"],
protocolMode: "OIDC"
}
};
// Create msal application object
const cca = new msal.ConfidentialClientApplication(config);
// With client credentials flows permissions need to be granted in the portal by a tenant administrator.
// The scope is always in the format "<resource>/.default"
const clientCredentialRequest = {
scopes: ["resource/.default"], // replace with your resource
};
cca.acquireTokenByClientCredential(clientCredentialRequest).then((response) => {
console.log("Response: ", response);
}).catch((error) => {
console.log(JSON.stringify(error));
});
I've tried changing the authority and the protocol mode several times, but same result

How do I register new vapidKeys outside FCM console UI

Update
As Gerardo pointed out, vapidKey != FCM Token.
I finally got things going, though im unsure if this is the best way to do it.
This was what i needed to generate a NEW token:
try{
if(currentToken) await deleteToken(messaging,currentToken)
if(Notification.permission !== 'granted') await Notification.requestPermission();
currentToken = await getToken(messaging,vapidKey);
$.ajax({
type:"GET",
url:"/fcm/register-token",
data:{token:currentToken},
success:(saved)=>{
if(saved) console.log(saved,' New token registered ',currentToken)
else console.log('Unable to save token!')
}
})
}
catch(e){console.log(e)}
Question
I am testing FCM for push notifications in javascript. I have a single "Web Push Certificate" (vapidKey) generated manually in the FCM console UI. This works for sending a test notification to a single token, but i am unclear on how any additional users would be able to register a new key with FCM.
I must be misunderstanding something fundamental here, and am not even sure what to be searching for.
// TODO: Find out how to generate new registration token as needed
const vapidKey = {vapidKey:"BLgq_6FY0suqAy9llMyYX03o9K9n4FHba1gCnPz6KmG9oh6K8v3Ws4SIG9KTILfN0_8np9PfT5bPqgTDXfCA9dc"};
async function fcm_init(){
try{
// TODO: user interaction for notification permission
await Notification.requestPermission()
const currentToken = await getToken(messaging,vapidKey);
// TODO: Send token to server to save in tbl_fcm
console.log(currentToken);
}
catch(err){
console.log(err);
}
}fcm_init()
In this example, the vapidKey is hard-coded, but how would i go about getting a different key for each user in the app without manually doing so in the FCM Console UI?
This is where i have generated the key to get a token for a user. This is what im trying to avoid doing manually for each user on the system.
The vapidKey is needed for identifying the app (not the user). This is mentioned in the second screenshot "Firebase Cloud Messaging can use Application Identity key pairs to connect with external push services".
With this information, your app can generate an FCM Token (or registration token) in the client:
const currentToken = await getToken(messaging,vapidKey);
You can use these FCM tokens to send messages to a specific device. These FCM Tokens identify the device (user) and they will be different for each one.
Check this example on how you would send a message from the back end to a specific device using it's FCM token (registration token).

Google sheets API JavaScript: Access sheet with auth

I'm able to access a public google sheet from within my react app but am now trying access the sheet with credentials. I found a tutorial that walks me thru setting up credentials but the code isn't working for me.
const {google} = require('googleapis');
const keys = require('./interstitials-key.json');
const client = new google.auth.JWT(
keys.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/spreadsheets']
);
client.authorize(function(err, tokens){
if(err){
console.log(err);
return;
}
else{
console.log('connected');
}
});
I'm getting this error:
"TypeError: Expected input to be a Function or Object, got undefined"
This is a known issue, you'll find reference over here:
https://github.com/googleapis/google-api-nodejs-client/issues/1614
I've reproduced it, certainly it's not fixed, you'll face this error as soon as you call the library
const {google} = require('googleapis');
Some of the resources used on the library are not available on the client side, so, it's not possible to call it from the React side, so you either use it on the server side or you have to use the google javascript client api.

Setting a reminder with Slack API

I'm having trouble using the reminder method to set a reminder using the Slack API.
https://api.slack.com/methods/reminders.add
I want to set a reminder for various people in our workspace. My understanding of the Slack API docs is that a workspace token is needed for permission, which I have created. See https://api.slack.com/docs/token-types#workspace
In POSTing the reminder request, I always get the error { ok: false, error: 'user_not_specified' }. I have specified a user as part of the payload, as well as text, time and the bearer token.
Strange, because the docs say that user is optional. Removing the user from the payload results in the same error.
I'm getting the same error in both Postman and in a simple snippet using the Node Slack API library:
const { WebClient} = require('#slack/client');
const token = process.env.SLACK_TOKEN || require('./.config').SLACK_API_TOKEN;
const web = new WebClient(token);
web.reminders.add({text: 'clean up duty', time: 'in 1 minute', user: 'U0FKQ3N94'})
.then((res) => {
console.log(res);
})
.catch(console.error);
Any idea what I am doing wrong?

Google Drive API Error Daily Limit for Unauthenticated Use Exceeded

Im getting error on using Google API.
having right to connect with Google Drive and add new sheet and insert data into it.
It was working till yesterday but when i run the application today.
Im getting error :
Error appears after users given token and tried to access the DRIVE API to get all the files
domain: "usageLimits"
extendedHelp: "https://code.google.com/apis/console"
message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
reason: "dailyLimitExceededUnreg"
I have not changed any settings.
Following API are enables for my application access token. Do i have to add / enable more API to make it work.
I was using NodeJS to download a file, but was forgetting to pass the auth.
Initially I was using:
function downloadFiles() {
const service = google.drive('v3');
const dest = fs.createWriteStream('/tmp/foo.csv');
const fileId = '12345_ID_GOES_HERE';
service.files.export({
fileId: fileId,
mimeType: 'text/csv'
});
}
afterwards, I added an auth argument to the function, and passed it to the export method as well:
function downloadFiles(auth) {
const service = google.drive('v3');
const dest = fs.createWriteStream('/tmp/foo.csv');
const fileId = '12345_ID_GOES_HERE';
service.files.export({
auth: auth,
fileId: fileId,
mimeType: 'text/csv'
})
}
I am getting auth by creating an instance of google-auth-library
The problem was while getting access token. I was not providing correct scopes.
When i changed the scope to
https://spreadsheets.google.com/feeds https://docs.google.com/feeds
https://www.googleapis.com/auth/drive.file
it worked fine

Categories

Resources