Google Directory API user list request failing with 400 Invalid Input - google-apis-explorer

I'm trying to get a successful response when executing the request from https://developers.google.com/admin-sdk/directory/v1/reference/users/list?apix_params=%7B%22customer%22%3A%22my_customer%22%7D. I'm getting a 400 Invalid Input response.
With the client library(https://www.npmjs.com/package/googleapis, v47), when calling:
google.admin('directory_v1')
.users.list({
auth: oAuth2Client,
customer: 'my_customer',
orderBy: 'email',
maxResults: 500,
pageToken: null
}).then(...);
, I'm receiving a Request object in the success handler, instead of a valid response(response which should have had the shape described at the bottom of https://developers.google.com/admin-sdk/directory/v1/reference/users/list).
What am I doing wrong?

Turns out the issue was with the authentication process, using the google-auth-library.
I've resorted to something like this:
const {google} = require('googleapis');
const oAuthClient = await google.auth.getClient({keyFile: ..., scopes: [...]});
oAuthClient.credentials = await new google.auth.JWT(...).authorizeAsync();
const {data} = await google
.admin({version: 'directory_v1', auth: oAuthClient})
.users
.list({
customer: 'my_customer'
});

Related

InvalidToken: De-serialization error -- POSTMAN

I use fabric Kony and I have given to Postman Username pass of Fabric to authenticate
enter image description here
and entered this prerequest script:
const postRequest = {
url: 'https://sandbox-api.marqeta.com/v3/swagger.json',
method: 'POST',
timeout: 0,
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "password"},
{key:"username", value: "........."},
{key:"password", value: ".........."},
]}
};
pm.sendRequest(postRequest, function (err, res) {
var responseJson = res.json();
console.log(responseJson);
pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);
});
I'm not an user of POSTMAN, but I know a little of Kony Fabric.
If you hit the web url of a Kony Fabric you'll notice that the first call will generate an oauth_token (for example 0526b30c-6579-4965-a774-87224815ea3a) that will be used for further calls.
I think that you should catch this token before trying to connect to the Kony Fabric with a user's credentials.
Cordially,
Hervé N.

Angular failed post request with error 500

I am developing an ionic app that makes a rest call to a backend to send an email, when I make the rest call I get the following error, what can be due to (the rest call in postman works, I use chrome with the cors disabled)
Error:
POST http://172.16.50.92/send 500 (Internal Server Error)
Code Angular:
const params = {
'type': 'mail',
'attributes[to_recipients]': mail,
'attributes[body]': body,
'attributes[subject]': subject,
'attributes[attachments]': attachments
};
endpoint = url + '/send';
var headers_object = new HttpHeaders();
headers_object.append('contentType', 'application/json');
headers_object.append('Authorization', `Basic ${window.btoa(username + ':' + password)}`);
return this.http.post(endpoint, params, [headers_object]);
return this.http.post(endpoint, params, [headers_object]);
You put your headers into an array. But the signature is supposed to be
post(url: string, body: any, options: { headers: HttpHeaders })
for your usecase.
Please change to below and try again.
return this.http.post(endpoint, params, { headers: headers_object });

Textnow API Errors when logging in through a script

When trying to log into textnow through an API using the correct username and password, the following error occurs:
UnhandledPromiseRejectionWarning: Error: 401 Unauthorized
at _response.transport.request.then (E:\nodejs\node_modules\snekfetch\src\index.js:193:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:19732) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without
a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 2)
Here's a look at the code from the API that I'm using:
module.exports.textnowLogin = (email, password) => {
return new Promise((resolve, reject) => {
let json = { "password": password, "username": email };
let queryEndpoint = "sessions?client_type=TN_ANDROID";
let signature = md5(`${tnSignatureKey}POST${queryEndpoint}${JSON.stringify(json)}`);
snekfetch.post(`https://api.textnow.me/api2.0/${queryEndpoint}&signature=${signature}`)
.set("Content-Type", "application/json")
.send(json)
.then((result) => {
return resolve(result.body);
}).catch(reject);
});
};
Here's a look at how I use this method in my js file:
const textNow = require('textnow-api');
textNow.login(username, password).then(client => {
console.log(`Logged in as ${client.username}`);
});`
This definitely has to be a server side issue, no? Something must be going wrong on Textnow's end. What can I do to circumvent this?
EDIT: const snekfetch = require("snekfetch"),
md5 = require("md5"),
tnSignatureKey = "f8ab2ceca9163724b6d126aea9620339";
Where did this key originate from? Perhaps if a new one was generated then the authorization error would be solved?
As a side note, another potential issue could be the client_type being set to ANDROID, and I am trying to use an iOS account to login. However, whenever I try using an Android account to log in instead, I get a 400 Bad Request, like Textnow does not recognize the account's credentials.
There may be other errors in the code, but the first mistake is the creation of an extra promise. Here's a version of the code that solves that and should either work or be simpler to debug...
module.exports.textnowLogin = (email, password) => {
let json = { "password": password, "username": email };
let queryEndpoint = "sessions?client_type=TN_ANDROID";
let signature = md5(`${tnSignatureKey}POST${queryEndpoint}${JSON.stringify(json)}`);
let url = `https://api.textnow.me/api2.0/${queryEndpoint}&signature=${signature}`;
return snekfetch.post(url).set("Content-Type", "application/json").send(json).then(result => {
return result.body;
});
};

Empty body in supertest request with application/vnd

I'm having a lot of trouble sending a request body in a supertest post. I've read the solutions to other questions, which blame improper configuration of body-parser, but those answers are referring to a custom datatype. (res.body is empty in this test that uses supertest and Node.js). I configure body-parser like this:
var bodyParser = require('body-parser');
app.use(bodyParser.json({ limit: '50mb', type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
This solution to the post I've provided says "supertest uses this file to determine if you are sending json or not." My content type is actually listed there, so I don't see why this should be a problem.
I am attempting to post a request like so:
it ('creates user', function (done) {
var user = {
firstname: 'Joe',
lastname: 'JoeJoe',
email: 'joe#joe.com',
password: 'spartacus',
};
request(app)
.post('/api/users')
.send(user)
.expect(200)
.expect('Sent email to joe#joe.com', done)
});
});
And I import my app with this line:
var app = require('../server.js');
Where server.js configures my application entirely. Is this application type supported by supertest? Is there a way to force the user data to be noticed as part of req.body?
I believe the issue can be solved by setting the content-type header on your post request to application/vnd.api+json. You can do so in supertest/superagent as follows:
it ('creates user', function (done) {
var user = {
firstname: 'Joe',
lastname: 'JoeJoe',
email: 'joe#joe.com',
password: 'spartacus',
};
request(app)
.post('/api/users')
.set('Content-Type', 'application/vnd.api+json')
.send(user)
.expect(200)
.expect('Sent email to joe#joe.com', done)
});
});

Getting "Missing required parameter: scope" after a 401 using Google Javascript API

Using gapi.client.request, I can successfully retrieve from Drive.
However, if I invalidate the access token and try again, I get a 401 as expected, followed by a call to https://accounts.google.com/o/oauth2/auth?scope=&immediate=true&proxy=oauth2relay530384583&redirect_uri=postmessage&origin=http%3A%2F%2Fdev.myapp.co%3A9000&response_type=token&state=780297101%7C0.3257751071&authuser=0
which fails 400 "Missing required parameter: scope"
Looking at the URL, the scope is indeed empty, but why?
At the beginning of the authentication, I'm setting my scopes using an array thus ...
var scopes = [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile', "https://docs.googleusercontent.com/", "https://docs.google.com/feeds/",
"https://www.googleapis.com/auth/drive.install","https://www.googleapis.com/auth/tasks" ];
The code itself is ...
var request = gapi.client.request({
'path': '/drive/v2/files/'+qObject.id,
'method': 'GET',
'params': {'maxResults': '1'}
});
request.execute(function(resp) {
console.log(resp); // this get works as expected
});
// now invalidate the access token
var token=gapi.auth.getToken();
token.access_token = "foo";
gapi.auth.setToken(token);
request = gapi.client.request({
'path': '/drive/v2/files/'+qObject.id,
'method': 'GET',
'params': {'maxResults': '1'}
});
request.execute(function(resp) {
console.log(resp); // this fails with a 401 as expected, but fails to get a new token
});
According to the documentation, scope parameter should be "space delimited set of permissions", not array of permissions.