Cloudrail - OneDrive API : Advanced search request fails - node.js

I'm using cloudrail Node.Js v2.17.3.
I have to do an advanced request on OneDrive API.
The authentication part and getting/storing credentials have succeeded.
Here is the request I have to do (according to OneDrive's doc):
/drive/root/search(q='IMG_001.jpg')
Of course, the file is present in my OneDrive account.
Here is the code :
const req = new cloudrail.types.AdvancedRequestSpecification("/drive/root/search(q='IMG_001.jpg')");
req.setMethod("GET");
req.setHeaders({"Content-Type": "application/json"});
service.advancedRequest(req, (err, res) => {
console.log(err, res);
});
Err.message says : "Invalid API or resource".
However, when I try the simple request "/drive/root/children", it works...
Thank you in advance.

Microsoft recently introduced their new Graph API which is used by all of the services as far as I know. So the documentation you are referring to is for the new API.
Try using '/drive/items/{the_folder_id or root}/view.search?q=txt' instead. You also might need to url encode the parameter. So the safest solution would probably be sth like that:
const url = "/drive/items/root/view.search?q=" + encodeURIComponent("[search query]");
const req = new cloudrail.types.AdvancedRequestSpecification(url);
req.setMethod("GET");
service.advancedRequest(req, (err, res) => {
console.log(err, res);
});

Related

Error 'Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup' on API call

Trying to make my expressJS app control users' google drive files. I've been utilizing the node 'googleapis' package. After following a slightly dated/incorrect article here, I've gotten the script to:
redirect a user to their authorization url
grab the 'code' from get parameter and then...
register it back as access tokens, which can then be used to...
create a registered 'auth' object
When I use this to create the drive object and try to get it to list files, I get the following error: 'Error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup'
This error has already popped up on SO question, and on github.
Following general advice, I re-enabled the drive api, re-downloaded access key. I've also tried replacing the sensitive drive scope a gmail scope, but that didn't work either. I'm not sure where else turn to start debugging at this point. I have a sneaking suspicion my entire auth object is being formed incorrectly but I can't find anything wrong.
This is the related piece of Express app code I'm using to create the authObject and then read drive files.
/**
* Google Utility class that packages different actions related to authentication
*/
class GoogleUtil {
constructor(secretFileName = 'client_secret.json') {
const secret = JSON.parse(fs.readFileSync(secretFileName)).web;
const { client_id, client_secret, redirect_uris } = secret;
this.client_id = client_id;
this.client_secret = client_secret;
this.redirect_uri = redirect_uris[0];
this.standardScope = [
'https://www.googleapis.com/auth/drive',
// 'https://www.googleapis.com/auth/gmail.readonly',
// 'https://www.googleapis.com/auth/userinfo.profile'
];
}
createConnection() {
return new google.auth.OAuth2(this.client_id, this.client_secret, this.redirect_uri); // form authObject
}
getConnectionUrl(auth) {
return auth.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: this.standardScope
});
}
async getAccessTokenFromCode(code) {
var auth = this.createConnection();
const data = await auth.getToken(code);
return data.tokens;
}
}
const g = new GoogleUtil();
/**
* BEGIN ROUTE DEFINITIONS
*/
// THIS IS FIRST STEP. FRONTEND WILL REDIRECT TO GIVEN URL
app.get('/api/googleLoginUrl', async (req, res) => {
const oAuth2Client = g.createConnection();
const url = g.getConnectionUrl(oAuth2Client);
res.json({ url });
});
// *****
// NOTE: THIS IS ROUTE THAT ATTEMPTS TO LIST FILES AND THROWS ERROR
// *****
app.get('/google-auth-redirect', async (req, res) => {
if (!req.query.code) return res.send('Malformed request');
const tokens = await g.getAccessTokenFromCode(req.query.code);
const auth = g.createConnection().setCredentials(tokens);
const drive = google.drive({ version: 'v3', auth: auth });
drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (err, resp) => {
if (err) return console.log('The API returned an error: ' + err);
console.log(resp);
});
res.redirect('/');
});
In the google developer console, clicking on 'create credentials' in the drive API overview informs me that my current credentials are compatible. The project scopes do include ' ../auth/drive'.
I'd want it to be able to list files from an authenticated user's account.
I think this might be related to how you are asking for permissions. If you are using your application to manipulate user's drive files you need a couple of things:
Check you have the correct access scopes setup.
Check you authentication parameter/Oauth screen is setup with said scopes.
You might want to read some documentation regarding authorizing users
Hope this helps! ;)

Simple Express JS API token

I'm wonder how I can implement a simple API auth token without need for users? I just want one token that I can authenticate by adding it as a parameter when I call my API.
All the current examples on Google seem to be over engineered for my needs. I have some data stored in MongoDB and I simply serve this data like so:
app.get("/", (req, res) => {
Car.find((err, cars) => {
if(err){
throw err;
}
res.json({"cars": cars});
});
});
Is it possible to add some simple middleware that checks my environment file for an element with the name of api_token. Then check that the api_token in my env file matches the parameter that has been passed as a URL query.
Is there a way to do this? I'm aware that you can't use URL queries on a GET route so I am unsure how this would work.
Sure, use middleware: https://expressjs.com/en/guide/using-middleware.html
For your case, it can be as simple as the following:
// checkForApiToken.js
module.exports = (req, res, next) => {
const apiToken = req.header("api-token");
if (process.env.API_TOKEN !== apiToken) {
next(new Error("Unauthorized."));
return;
}
next();
}
The logic is simple:
Retrieve API-TOKEN value from the header.
Check it matches what I've defined in my env.
Does not match, throw an error by passing an error object into the next function.
Matches so I call next() with no error to proceed to the next request handler.
You would then use it like so:
app.get("/", checkForApiToken, async (req, res) => {
const cars = await Car.find().exec();
res.json({ cars });
});
Remember, Tokens are responsible for at least 2 API security mandatory things, authenticate and authorize. You don't need to authenticate users, but you need to be sure that the token you received is a Token and not a "HEADER".
If you use a static token,or anything else, first time i get your token your security is down. You need to specify AT LEAST when this token will die, and if it is a valid one based on some random assignment. You can't check for it's presence, you need to check if it is valid.
Javascript has an amazing convention background, whenever you have the opportunity, follow the convention. It is easier as it seems to implement a JWT based.
Just follow this : https://github.com/auth0/node-jsonwebtoken
and implement it in your middleware as you wishh.
Easily as this /
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'secret');
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
You can always redo the concepts by using a "Web HEADER" and calling it a "TOKEN". But as i said, it is a "Web Header" not an "WEB TOKEN".

linked in data scraper in node.js

In my code linkedInProfile is not a function that error display in console how to solve that error???
var linkedInProfile = require('linkedin-public-profile');
app.get('/api/webapi/:version/users', function(req,res){
var url = 'https://www.linkedin.com/in/bansridamani/';
linkedInProfile(url).then(profile => {
console.log(profile);
});
var request = require('request-promise');
request(url)
.then(html => linkedInProfile(html))
.then(profile => {
console.log(profile);
});
});
Actually, you are using dead repo for scraping public data of linkedin profiles linkedin-public-profile.
And please check the api documentations of linkedin REST API to here.
Also check the linkedin API console to here for testing.
Hope this will help you!

Get Facebook Auth token from Azure Easy API

Easy API are very poorly documented, I'm trying to get the Facebook Auth token from a user authenticated against it through Azure, I've created an API with the following GET:
module.exports = {
"get": function (req, res, next) {
res.json(req.user.getIdentity("facebook"));
}
};
However azure responds with "cannot read property 'getIdentity' from undefined". If user is undefined in res, where can I get it from?
Easy APIs is documented in the Azure Mobile Apps Node.js SDK HOWTO and within the API docs. You can find the HOWTO here: https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-node-backend-how-to-use-server-sdk/
As to the specific question, getIdentity() is a Promise-based mechanism. In addition, you need to access the user object through the azureMobile property. Something like:
module.exports = {
"get": function (req, res, next) {
req.azureMobile.user.getIdentity("facebook").then((data) => {
res.status(200).type('application/json').json(data);
}).catch((error) => {
res.status(500).send(JSON.stringify(error));
});
}
};

Node.js OAuth2: Get Google+ activities

From today I'm not able to retrieve my Google+ activities by placing a GET request to this url:
https://www.googleapis.com/plus/v1/people/me/activities/public?key={API_KEY}
I'm getting a 401 error. So I tried to sign the request using the node.js oauth2 library, including a pre-generated user token, but I'm getting the same error. The js code for my test script is:
var OAuth2 = require('oauth').OAuth2,
GOOGLEPLUS_APP_ID = {APP_ID},
GOOGLEPLUS_APP_SECRET = {APP_SECRET},
accessToken = {USER_TOKEN};
var _oauth2 = new OAuth2(GOOGLEPLUS_APP_ID, GOOGLEPLUS_APP_SECRET, '',
'https://accounts.google.com/o/oauth2/auth',
'https://accounts.google.com/o/oauth2/token');
_oauth2.get('https://www.googleapis.com/plus/v1/people/me/activities/public?key={API_KEY}',
accessToken, function (err, body, res) {
if (err) {
console.log('error:');
console.log(err);
}
else console.log(body);
});
I placed the same request to get the basic user info (url: https://www.googleapis.com/oauth2/v1/userinfo) and works OK.
Can you please assist me with this?
Thank you.
If you have the access token already you should be able to use {?|&}access_token=X to get the result, example below.
var accessToken = 'XYZ';
require('http').get('https://www.googleapis.com/plus/v1/people/me/activities/public?access_token=' + accessToken, function(result){
//Use result here!
});
More information can be found within the Google+ API (Common Parameters) section

Resources