I am testing the new #c8y/client library for typescript.
I have a very simple code :
import {
Client
} from '#c8y/client';
//const baseUrl = 'https://bismark1.cumulocity.com/';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'bismark1';
const user = '...';
const password = '.....';
(async() => {
console.log('authentication to c8y server')
const client = await Client.authenticate({
user,
password,
tenant
}, baseUrl);
console.log('result from authetication', client)
const {
data,
paging
} = await client.inventory.list();
console.log('result from inventory ', data)
// data = first page of inventory
const nextPage = await paging.next();
// nextPage.data = second page of inventory
const managedObjId: number = 1;
(async() => {
const {
data,
res
} = await client.inventory.detail(managedObjId);
console.log(data)
})();
})();
When I run the .js compiled form the .ts file I get the response below :
authentication to c8y server
And then the execution stops.
The line
console.log('result from authetication', client)
is never called. Seems like something fails in the authentication process and not error is showed.
What I'm doing wrong ?
Thanks.
The first problem might be CORS. You need to enable it if you want to request from a different domain. Here is a guide how to do that in Cumulocity:
Under "Access control", administrators can enable cross-origin
resource sharing or "CORS" on the Cumulocity API.
The second problem could be that you are not running it from a local development server. I mostly use this http-server from npm to quickly test scripts. You can use it the following way:
$ npm install http-server -g
$ http-server
If that all is not helping you might try catch the client to see the error it is throwing:
try {
const client = await Client.authenticate({
user,
password,
tenant
}, baseUrl);
} catch(ex) {
console.log(ex);
}
The exeption might tell you more about what is wrong with your code or if there is a bug in the client.
Related
I am creating one app using react native expo, which allow end user to login by their google account , and then applicaton try to save the access_token so that server based applicatin can use this to send the email on their behalf ,
But when using google sing in , i am not getting refresh token and not able to send the email ,
Here is code example which i am using
I tried below method to get the access request
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId: "XXXXXXX",
androidClientId:"XXXXXXX",
iosClientId:"XXXXXXX"
});
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
const sendNotification=useNotification()
//console.log(sendNotification)
useEffect(() => {
if (response?.type === "success") {
const { id_token } = response.params;
const auth = getAuth();
const credential = GoogleAuthProvider.credential(id_token);
signInWithCredential(auth, credential);
let decoded = jwt_decode(id_token);
socialLogin(decoded)
}
}, [response]);
And on server using this code to sending email
const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./credentials.json');
// Replace with the code you received from Google
const code = 'XXXXXXX';
//const code="XXXXXXX"
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.getToken(code).then(({ tokens }) => {
console.log('first')
const tokenPath = path.join(__dirname, 'token.json');
fs.writeFileSync(tokenPath, JSON.stringify(tokens));
console.log('Access token and refresh token stored to token.json');
}).catch(err=>console.log(err));
async function signInWithGoogleAsync() {
try {
const result = await Google.logInAsync({
androidClientId: YOUR_CLIENT_ID_HERE,
scopes: ["profile", "email"],
});
if (result.type === "success") {
onSignIn(result);
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
}
Well, I tried to create an application with Google login. To use the Google Sign-In method in a React Native Expo app, you will need to perform the following steps:
Set up a project in the Google Cloud Console and obtain a configuration file for your app.
Install the expo-google-sign-in package in your React Native app.
Import the GoogleSignIn object from the expo-google-sign-in package and use the initAsync method to initialize the Google Sign-In process.
Use the GoogleSignIn.askForPlayServicesAsync method to check if the device has the required Google Play Services installed.
Use the GoogleSignIn.signInAsync method to prompt the user to sign in with their Google account.
Once the user has signed in, you can use the accessToken and refreshToken properties of the returned object to make authorized requests to the Google APIs.
The code lines for the above steps are:
import { GoogleSignIn } from 'expo-google-sign-in';
// Initialize the Google Sign-In process
await GoogleSignIn.initAsync({
// Your config. values
});
// Check if the device has the required Google Play Services installed
const isPlayServicesAvailable = await GoogleSignIn.askForPlayServicesAsync();
if (!isPlayServicesAvailable) {
console.error('Google Play services are not available on this device.');
return;
}
// Prompt the user to sign in with their Google account
const { accessToken, refreshToken } = await GoogleSignIn.signInAsync();
I am trying to connect to a Databricks SQL endpoint using NodeJS. I followed the instructions on the "Connection Details" tab of my SQL endpoint. As described, I am running Node version 14 or higher, and installed the connector npm package as follows:
npm i #databricks/sql
I used the code provided, included below (I made sure to use the correct host name and access token). I did not change the SQL code from the default (SELECT 1).
const { DBSQLClient } = require('#databricks/sql');
var token = "dapi_MY_ACCESS_TOKEN";
var server_hostname = "MY_HOSTNAME.cloud.databricks.com";
var http_path = "/sql/1.0/endpoints/a8e8b6cfcc6a190f";
const client = new DBSQLClient();
const utils = DBSQLClient.utils;
client.connect(
options = {
token: token,
host: server_hostname,
path: http_path
}).then(
async client => {
const session = await client.openSession();
const queryOperation = await session.executeStatement(
statement = "SELECT 1",
options = { runAsync: true });
await utils.waitUntilReady(
operation = queryOperation,
progress = false,
callback = () => {});
await utils.fetchAll(
operation = queryOperation
);
await queryOperation.close();
const result = utils.getResult(
operation = queryOperation
).getValue();
console.table(result);
await session.close();
client.close();
}).catch(error => {
console.log(error);
});
When I run the code, I get the following error message:
node read_databricks.cjs
TypeError: Cannot read properties of undefined (reading 'waitUntilReady')
at /Users/vijay.balasubramaniam/test/records-to-cards/read_databricks.cjs:23:19
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I also tried running the above code within the node REPL, but got the same results. Am I missing a step?
I ran into the same issue.
Delete your package-lock.json. Run npm install and make sure that in the package-lock.json file the version is pointing to beta.1 and not beta.2.
"node_modules/#databricks/sql": {
"version": "0.1.8-beta.1",
}
I am building a Next JS app that has Github Login through Auth0 and uses the Octokit to fetch user info / repos.
In order to get the IDP I had to setup a management api in auth0. https://community.auth0.com/t/can-i-get-the-github-access-token/47237 which I have setup in my NodeJs server to hide the management api token as : GET /getaccesstoken endpoint
On the client side : /chooserepo page, I have the following code :
const chooserepo = (props) => {
const octokit = new Octokit({
auth: props.accessToken,
});
async function run() {
const res = await octokit.request("GET /user");
console.log("authenticated as ", res.data);
}
run();
And
export const getServerSideProps = withPageAuthRequired({
async getServerSideProps({ req, params }) {
let { user } = getSession(req);
console.log("user from get session ", user);
let url = "http://localhost:4000/getaccesstoken/" + user.sub;
let data = await fetch(url);
let resData = await data.text();
return {
props: { accessToken: resData }, // will be passed to the page component as props
};
},
});
However, I keep getting Bad credentials error. If I directly put the access token in the Octokit it seems to work well, but doesn't work when it's fetching the access token from the server.
It seems like Octokit instance is created before server side props are sent. How do I fix it ?
I figured out the error by comparing the difference between the request headers when hardcoding and fetching access token from server. Turns out quotes and backslashes need to be replaced (and aren't visible when just console logging)
I have configured the NPM instagram-web-api package. I have instantiated the Instagram object and passed the correct credentials:
const Instagram = require('instagram-web-api');
const { igUsername, igPassword } = process.env
const ig = new Instagram({ username: igUsername, password: igPassword });
(async () => {
try {
await ig.login()
} catch (err) {
if (err.error && err.error.message === 'checkpoint_required') {
console.log(err.error);
const challengeUrl = err.error.checkpoint_url
await ig.updateChallenge({ challengeUrl, securityCode: 670381 })
}
}
const profile = await ig.getProfile()
})()
I am getting a 'checkpoint_required' error message and each time I start the server a Instagram verification code is sent to my email. I don't know where to enter that code or how to resolve this issue.
Having the same issue. I thing we need to call an extra api for the OTP validation in order to login.
Check this out - https://github.com/ohld/igbot/issues/630 for the solution or reference.
To give some context, I am a front end dev tasked with intergrating salesforce into a react app. This is a new learning curve for me as I am a SF newbie. I have been looking for a way to make intergration easier and I came across a video that showed how I can use a node packaged called JSforce to auth and fetch data from SF to my node express backend. I did as the video suggested but something appears to be not working as I am not console logging anything. Can anyone who has experience in using Jsforce take a look at my code below and let me know where I have gone wrong?
const express = require('express');
const app = express();
const port = 5000;
const jsforce = require('jsforce');
const username = 'blah';
const password = 'blah+ security token';
var conn = new jsforce.Connection({
// you can change loginUrl to connect to sandbox or prerelease env.
loginUrl: 'https://tahina-test2-dev-ed.my.salesforce.com/'
});
conn.login(username, password, function(err, userInfo) {
if (err) {
return console.error(err);
}
// Now you can get the access token and instance URL information.
// Save them to establish connection next time.
console.log(conn.accessToken);
console.log(conn.instanceUrl);
// logged in user property
console.log('User ID: ' + userInfo.id);
console.log('Org ID: ' + userInfo.organizationId);
// ...
conn.sobject('Account').retrieve('0012X000022HhE5QAK', function(err, account) {
if (err) {
return console.error(err);
}
console.log('Name : ' + account.Name);
// ...
});
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));