I try to use google.adwords api, but it seems not there.
code:
import { Router } from "express";
import { google } from "googleapis";
function adwords() {
const router = Router();
router.get("/adwords", (req, res) => {
const googleAdwords = google.adwords;
});
return router;
}
export { adwords };
But I found google adwords scope (https://www.googleapis.com/auth/adwords) at here
https://developers.google.com/adwords/api/docs/guides/authentication#scope
How can I use google adwords API using google-api-nodejs-client?
The Adwords API is not supported by google-api-nodejs-client, see this list of supported ones for reference.
You can find the list of official client libraries for the Google Adwords API here. Unfortunately, JS does not have a Google-maintained client library at the moment.
Related
I'm successfully using the Cognito federated sign in with the hosted ui in my react app. This login flow redirects to a login url in my application. My intent is to fetch the Auth.currentAuthenticatedUser() in a useEffect hook when the auth_code appears on the request (for now just looking to see if the search component has any value) and then to redirect to another route.
The problem I'm having is that the https://foo-api.auth.us-east-1.amazoncognito.com/oauth2/token call that Amplify makes behind the scenes doesn't return until after the Auth.currentAuthenticatedUser promise resolves with a failure.
My naive workaround/solution was to wrap that call in a timer, see below. This works fine, but seems brittle and wrong-headed (even if I handle the possibility of infinite calls).
import React, { useEffect } from "react";
import {useLocation, useHistory} from "react-router-dom"
import Auth from "#aws-amplify/auth";
import { CognitoHostedUIIdentityProvider } from "#aws-amplify/auth/lib-esm/types";
const App = () => {
useAuthentication();
function useAuthentication() {
const location = useLocation()
const history = useHistory()
useEffect(_ => {
if(location.search) {
const interval = setInterval(() => {
Auth.currentAuthenticatedUser()
.then(_=> history.push('/'))
.catch(console.log)
}, 1000)
return _ => clearInterval(interval)
}
}, [location]);
}
return (
<div className="App">
<button
type="button"
onClick={() =>
Auth.federatedSignIn({
provider: CognitoHostedUIIdentityProvider.Cognito
})
}
>
Federated sign in
</button>
</div>
);
};
export default App;
This seems almost like an Amplify bug, at least when I'm trying to use it like this. I see that this issue comes up here: AWS Cognito hosted UI and Amplify Auth with authorization code OAuth flow. But I'm not using any other Amplify components like Hub.
Is there a better, more idiomatic way to handle this situation?
I want to use Google OAuth 2.0 with my React/Next.js app. I've set up my OAuth Client IDs on the Google Developer console, and set up a route in my server.js node file. When I try to GET request https://localhost:3000/auth/google I get the Next js 404 Not Found page. It's obviously looking for a page called auth in my Next js pages directory. Tried using the next/Router, wrapping my button in an anchor element, fetch API GET requesting https://localhost:3000/auth/google, all failed.
I've managed to successfully implement passport user authentication, salting, hashing and sessions but it's just the Oauth that's giving me trouble.
If it were a standard node application https://localhost:3000/auth/google would redirect to the interface where users could login with their google credentials.
I've tried search the nextjs examples github for implementations of oauth but there doesn't seem to be any. Anyone know how I can use OAuth 2.0 with Next JS?
Route
server.get("/auth/google", (req, res) =>{
passport.authenticate("google", { scope: ['profile']});
})
Button that's supposed to take me to the google login/register page
<button className="btn btn-block btn-social btn-google" style={{'color': '#fff'}} onClick={() => Router.push("/auth/google")}>
<FontAwesomeIcon icon={faGoogle} className="google-social-button" /> Sign Up with Google
</button>
You can simply try this,
const app = next({ dev });
const server = express()
server.get('/auth/google/callback*',
passport.authenticate('google'),
(req, res) => {
res.redirect('/dashboard');
});
server.get('/auth/google*', (req, res) => {
return app.render(req, res, req.path, req.query)
});
server.get('/api/logout', (req, res) => {
req.logout();
res.send(req.user);
})
server.get('/api/current_user', (req, res) => {
res.send(req.user);
});
server.get('*', (req, res) => {
return handle(req, res)
});
Just make sure the google reqs are above the server.get('*') route as it catches all requests.
More help: https://github.com/zeit/next.js/blob/canary/examples/custom-server-express/server.js
Not sure if you're still looking for an answer here, but if are, you can do something like the following under the latest Next.js version (9+), https://nextjs.org/blog/next-9#api-routes
//--- PART 1: DEFINE YOUR GOOGLE OAUTH STRATEGY ALA PASSPORT
// This would be in its own passport.js file (the filename doesn't matter), the key thing being that you define your Google Strategy
import passport from 'passport'
import {
Strategy as GoogleStrategy,
} from 'passport-google-oauth20'
passport.use(new GoogleStrategy({
...getGoogleKeySecret(), // a utility for grabbing your secret keys
callbackURL: `/api/authorize/google/callback`,
passReqToCallback: true, // http://www.passportjs.org/docs/authorize/
}, async function(req, accessToken, refreshToken, profile, done) {
// Do any user lookup/mapping you need here
return done(null, profile)
}))
//--- PART 2: DEFINE THE END-POINT
// This would be in your pages/api/auth/google.js file
import nextConnect from 'next-connect'
import middleware from '../any/custom/middleware/stuff/you/may/have'
const handler = nextConnect()
handler.use(middleware)
handler.get(passport.authenticate("google", {
scope: ['profile', 'email', 'openid'], // tailer the scope to fit your needs
}))
export default handler
To try it out, direct a user to /api/auth/google via your UI or hit the URL directly, and you should be taken through the Google OAuth 2.0 flow.
Hope this helps - good luck!
I need to call Graph API from spfx webpart.
Previously we used the following method:
import { MSGraphClient } from '#microsoft/sp-client-preview';
But later we got to know that MSGraphClient is depreciated now in sp-client-preview.
I checked the following method which is mentioned in Microsoft docs also.
import { MSGraphClient } from '#microsoft/sp-http';
But it is giving an error as following:
Module '"d:/O365/upload-onedrive/node_modules/#microsoft/sp-http/dist/index-internal"' has no exported member 'MSGraphClient'
SPFx version we are using now is 1.6
Is there any way call Graph API from spfx now?
Of course we can use Graph in SPFx.
Graph+adal+SPFx steps:
Create an application in Azure portal. Click the manifest, then change "oauth2AllowImplicitFlow" value to true
Go to Settings->Required Permissions->ADD->Select an API->Microsoft Graph, select the permission and then Grant Permissions.
Build HelloWorld SPFx project : https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part
Add and IAdalConfig.ts and WebPartAuthenticationContext.js patch files
Tips: If you have no adal module in node_modules/#types folder, you'd better manually install the module using the command : npm install #types/adal#1.0.29
Add the following code to render()
// Make an AJAX request to the Graph API and print the response as JSON.
var getToken;
var getCurrentUser = function (access_token) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Do something with the response
getToken=JSON.stringify(JSON.parse(xhr.responseText), null, ' ');
console.log('get Graph APi information=='+getToken);
} else {
// TODO: Do something with the error (or non-200 responses)
// console.log(' error');
}
};
xhr.send();
There is actually no reason to create any applications in the Azure side, it's all automatic and taken care of by SharePoint. See following documentation for details. We did change the API structure slightly between preview and GA, but the basics have remained the same with MSGraphClient usage and no reason for any manual access token handling.
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-msgraph
Below code creates a google sheet on My Drive but what if I had to place this to a folder on team drive?
I would like to modify createNewSpreadSheet function in such a way that it uploads file to specified folder of team drive.
function createNewSpreadSheet(auth) {
const sheets = google.sheets({version: 'v4', auth});
const resource = {
properties: {
title:'SampleSheet'
},
};
sheets.spreadsheets.create({
resource,
fields: 'spreadsheetId',
}, (err, spreadsheet) =>{
if (err) {
// Handle error.
console.log(err);
} else {
console.log('spreadsheet::',spreadsheet.data.spreadsheetId);
}
});
}
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), createNewSpreadSheet);
});
You may check this blog on how to import/upload files to Team Drives folders.
Uploading files to a Team Drives folder is also identical to to uploading to a normal Drive folder, and also done with DRIVE.files().create(). Importing is slightly different than uploading because you're uploading a file and converting it to a G Suite/Google Apps document format, i.e., uploading CSV as a Google Sheet, or plain text or Microsoft Word® file as Google Docs. In the sample app, we tackle the former:
def import_csv_to_td_folder(folder_id, fn, mimeType):
body = {'name': fn, 'mimeType': mimeType, 'parents': [folder_id]}
return DRIVE.files().create(body=body, media_body=fn+'.csv',
supportsTeamDrives=True, fields='id').execute().get('id')
The secret to importing is the MIMEtype. That tells Drive whether you want conversion to a G Suite/Google Apps format (or not). The same is true for exporting. The import and export MIMEtypes supported by the Google Drive API can be found in my SO answer here.
I'm using the Google Sheets API v4 in Android.
https://developers.google.com/sheets/api/quickstart/android
I need to know when the last modification to the sheet was made (including by user); I need this guy:
I'd like to do something like this:
Spreadsheet spreadsheet = sheetsService.spreadsheets().get(spreadsheetId).setIncludeGridData(true).execute();
Date date = spreadsheet.getProperties().getLastEditDate();
But, of course, no such getLastEditDate() property method exists. Is there a parameter or another API method to call to get this data?
Even better would be to get the modified date for each cell... but I'd settle for the date of the entire spreadsheet or sheet.
This is not available in the Sheets API, but you may be able to use the Drive API's files.get method, which includes a 'modifiedTime' in the response. (Note that by default it will not include the modified time, you have to explicitly ask for it in the 'fields' parameter.)
It looks like this cannot be done with Sheets API v4.
However...it does look like it can be done with the compatible Google Drive API v3.
Note: the best part about this solution was that I could use the same method of authentication and credential gathering for both APIs. E.g., once I had the code for getting the credentials, I could use it for both API's interchangeably and consecutively.
Here's what I did:
Added this to my build.gradle (shown below my Sheets API declaration)
compile('com.google.apis:google-api-services-sheets:v4-rev468-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev69-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
I was already using the EasyPermissions method for getting account and credentials. Great example here.
Then...
import com.google.api.services.drive.Drive;
...
protected Drive driveService = new Drive.Builder(transport, jsonFactory, credential)
.setApplicationName("My Application Name")
.build();
... async:
private DateTime getSheetInformation() throws IOException {
String spreadsheetId = settings.getSpreadsheetId();
Drive.Files.Get fileRequest = driveService.files().get(spreadsheetId).setFields("id, modifiedTime");
File file = fileRequest.execute();
if (file != null) {
return file.getModifiedTime();
}
return null;
}
The sheets api v3 will be deprecated in March 2020, when that happens, your best bet is to use the drive API.
https://developers.google.com/drive/api/v3/reference/files/list
you can pass