nodejs googlephotos fails to upload with "Authentication session is not defined" - node.js

I've got some code based on the samples given at the googlephotos documentation. I basically just took the code provided as-is and modified it to fill in my client id, secrets, etc. generate a URL which I then paste into my brower, and after clicking through to authorize my app I copy the code it gives me and using it to construct a new Photos object.
I tried setting up my scopes as:
const scopes = [
Photos.Scopes.READ_ONLY,
Photos.Scopes.SHARING,
Photos.Scopes.APPEND_ONLY
];
But I also tried:
const scopes = [
Photos.Scopes.APPEND_ONLY
];
and
const scopes = [
Photos.Scopes.READ_AND_APPEND
];
I am able to to get back auth tokens which I can use to build a new Photos object. I try to upload something like this:
const response = await photos.mediaItems.upload("", "test.mp4", "/home/michael/test/test.mp4", "Test Upload");
I get this error along with a stack trace which seems useless:
(node:13122) UnhandledPromiseRejectionWarning: StatusCodeError: 401 - "{\n \"code\": 16,\n \"message\": \"Authentication session is not defined.\"\n}"
I have granted append permission, which is all that should be for this to have the proper authorization, yet it still fails! What am I doing wrong here?

The documentation isn't super-specific about exactly what "auth_token" you are supposed to pass, merely saying:
const photos = new Photos(your_google_auth_token);
without defining what your_google_auth_token is or where it comes from. Google's own documentation for the upload API just says oauth2-token which isn't helpful in getting to the bottom of what this value should be.
In the same code for getting the tokens it just says:
const {tokens} = await oauth2Client.getToken(code)
// The token from above can be used to initialize the photos library.
This error occurs when you naively plug the tokens you get into the constructor like so:
const photos = new Photos(auth_token)
Instead, what you need to do is plug the access_token field of the tokens like this:
const photos = new Photos(auth_token.access_token)

Related

Generate Authorization token for MuleSoft API in NetSuite

I am trying to call Mulesoft API endpoint from NetSuite user event script. I need to generate token to send it with API call.
Question:
should i create schedule script to generate the token and store it somewhere?
how often the token should be refreshed?
Postman token generation is working fine. I would love to know how should I setup this in NetSuite.
Postman:
Apologies in advance as I cannot comment, low Rep.
I haven't worked with Mulesoft or Oauth2, I mostly work on Oauth1.
According to your comments, it expires in 4 Hours. I suggest you store the generated Access Token in Script Parameter. NetSuite Script Parameter. You can call task.create to schedule a script to refresh the Access Token every 4 hours as stated on the notes on this page Referencing Script Parameters
EDIT: Had to confirm few things regarding Script Parameter. According to some articles, Script Parameter are global and can be called from different scripts (has to be set as company preference when creating parameter). So, scheduled script and storing it to a parameter and having your UE Script fetching the value of that parameter will work.
Adding this code sample to #Nukedd's answer.
Here's an example of storing/fetching access token in Cache.
const CACHE_NAME = 'MY_CACHE';
const ACCESS_TOKEN = 'MY_ACCESS_TOKEN';
const cache = require('N/cache');
// Storing access token to server cache
const storeAccesstoken = () => {
var myCache = cache.getCache({
name: CACHE_NAME,
scope: cache.Scope.PRIVATE
});
myCache.put({
key: ACCESS_TOKEN,
value: '12345accesstoken',
ttl: 14400
});
}
// Fetching access token from server cache
const getAccessToken = () => {
const myCache = cache.getCache({
name: CACHE_NAME
});
const myAccessToken = zipCache.get({
key: ACCESS_TOKEN,
loader: loaderFunction
});
return myAccessToken;
}
Please see the following:
N/cache Module
cache.Scope
Note: This is only supported by server scripts.

Concatenate strings in flutter adds ""

This is rather a silly question but I can't seem to figure it out. I'm building a flutter app that communicates to an API and in order for the user to be authenticated it sends an token.
Whenever the user logs in I save the token in the Shared Preferences and then when I make an request add the token to the headers or in this case I need it in the url.
However, whenever I concatenate the strings: the server url and the token it adds extra "" to the token. something like:
http://10.0.2.2:64342/chatHub?access_token="token-value"
instead of
http://10.0.2.2:64342/chatHub?access_token=token-value
here's the code:
var preferences = await SharedPreferences.getInstance();
token = preferences.getString(token_key);
var url = '$serverURl?access_token=$token';
As far as I understand your question, I would like to answer it.
That's not possible!
var serverURl = 'http://10.0.2.2:64342/chatHub';
var token = 'token-value';
var url = '$serverURl?access_token=$token';
print(url);
It just prints the correct one!
You can check the string that is stored in the SharedPreferences! That maybe with quotes.
Okay, I figured it out. Since I was sending only the token from the API. I was receiving it with the "" in it.
Instead I now send a json with the token, like: { "token": "token_value"} and then decode it to get the actual value. So when I store it the shared preferences it doesn't keep the "".
So in the backend:
return Ok(new {token = generatedToken});
and in dart
var tokenJson = json.decode(response.body);
var token = tokenJson['token'];
preferences.setString(token_key, token);
Thanks to everyone that helped :)

How do I enable devToken for a StreamChat?

I am trying to initialize a new chat using a devToken to allow client-side generated tokens by coding the following inside an async function:
let chatClient = await new StreamChat(apiKey);
await chatClient.updateAppSettings({
disable_auth_checks: true,
});
await chatClient.setUser(
{
id: 'user-0',
name: random-user-name,
},
chatClient.devToken('user-0'),
);
but am getting the error that "Both secret and user tokens are not set", despite using a devToken. The error stops the code from running once it hits
await chatClient.updateAppSettings({
disable_auth_checks: true,
});
, which is supposed to allow me to use the .devToken in place of a userToken.
So I added my secretKey to new StreamChat
let chatClient = await new StreamChat(apiKey, secretKey);
however, then I get the error "TypeError: Cannot read property 'sign' of null at JWTServerToken" right after that line runs.
And if I try to generate a userToken and replace chatClient.devToken('user-0') with userToken like this
let userToken = await chatClient.createToken("user-0");
I get the error "Error: tokens can only be created server-side using the API Secret", which is what I was trying to avoid.
Does anyone know how to correctly enable .devTokens so that the chatClient can be set without generating a token server-side?
Thanks!
This needs to be done via the dashboard. First, make sure your app is in development mode.
Then, navigate to the app's chat overview page and enable "Disable Auth Checks". Hit save.

Xero API 403 - AuthenticationUnsuccessful error

I am using the Xero Api with Nodejs and the xero-node library.
I have completed the oAuth flow and saved the token to the database. The issue i am now having is continually getting a 403 forbidden error when attempting to get anything from Xero be that Contacts, Accounts or Users. Sample code is below
I can get tenants ok without an issue however anything else doesn't work. I have checked the scopes to make sure when I am setting up the client they are correct which they are.
var getStuff = async(tokenSet) => {
await xero.setTokenSet(tokenSet);
const tenants = await xero.updateTenants();
const xeroTenantId = tenants[0].id // {String} Xero identifier for Tenant
const ifModifiedSince = new Date("2020-02-06T12:17:43.202-08:00");
const where = 'IsSubscriber==true'; // {String} Filter by an any element
const order = 'LastName ASC'; // {String} Order by an any element
console.log(tenants);
try {
const response = await xero.accountingApi.getUsers(xeroTenantId, ifModifiedSince, where, order);
console.log(response.body || response.response.statusCode)
}
catch (err) {
/// console.log(err);
console.log(`There was an ERROR! \n Status Code: ${err.response.statusCode}.`);
console.log(`ERROR: \n ${JSON.stringify(err.response.body, null, 2)}`);
}
}
Which scopes have been added to the access token you are passing through? You can decode your token here https://jwt.io/
Also - you need to pass the ‘tenant.tenantId’ to the function. I believe the tenant.id actually relates to the connection id which is coming back from the /connections endpoint.
My hunch is that is the issue. Also curious how that’s working, as updateTenants() should have the empty function call on the end. Is that working for you?

Firebase acces and id tokens

I'd like to know how to get both access and id tokens in Node.js SDK Firebase.
When I print user object after signUpWithEmailAndPassword, I see that accessToken is one the properties there, but then when i use method on user object called getIdToken, I get the same token I saw in users object. Why then it is not called getAccessToken???
What I want is return to the client object containing access, id, refresh tokens and expiration time.
P.S. I can't just say user.stsTokenManager.accessToken as it tells me that there is no already such property.
This is only an internal name. This "accessToken" is really the Firebase ID token. You should rely on the officially supported getIdToken to get that Firebase ID token. Firebase also recently added getIdTokenResult which provides the ID token and additional information like expiration time and other token related information without you having to parse it from the ID token. You can also get the refreshToken from the user via firebase.auth().currentUser.refreshToken.
const result = await getRedirectResult(auth);
if (result) {
const provider = new FacebookAuthProvider();
// This is the signed-in user
const user = result.user;
// This gives you a Access Token.
const credential = provider.credentialFromResult(auth, result);
const accessToken = credential.accessToken;
// this gives you the id token
const idToken = user.getIdToken();
}

Resources