Hi team,
When I try to run my Genesys application in localhost, I am getting
[GET /oauth2/callback?code=Dc1cIaG_lOE_9xR9lehH0NGPEJV6sA02lyYYO_Kvuf0]
Session exists
oauth callback
Dc1cIaG_lOE_9xR9lehH0NGPEJV6sA02lyYYO_Kvuf0
AxiosError: getaddrinfo ENOTFOUND login.usw2.pure.cloud
at AxiosError.from (D:\Login_Genesys\node_modules\axios\dist\node\axios.cjs:836:14)
at RedirectableRequest.handleRequestError (D:\Login_Genesys\node_modules\axios\dist\node\axios.cjs:3010:25)
at RedirectableRequest.emit (node:events:513:28)
at eventHandlers.<computed> (D:\Login_Genesys\node_modules\follow-redirects\index.js:14:24)
at ClientRequest.emit (node:events:513:28)
at TLSSocket.socketErrorListener (node:_http_client:502:9)
at TLSSocket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
hostname: 'login.usw2.pure.cloud',
syscall: 'getaddrinfo',
code: 'ENOTFOUND',
errno: -3008,
cause: Error: getaddrinfo ENOTFOUND login.usw2.pure.cloud
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:107:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'login.usw2.pure.cloud'
}
}
I am running my application in localhost 8085. When I try this in my chrome its giving above error.
My pure cloud instance is US west, so I am using usw2.pure.cloud as my environment here. Plese find below my application.
// >> START oauth-auth-code Authorization code grant login without a client library
const http = require('http');
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const cookieParser = require('cookie-parser');
const axios = require('axios');
const { URLSearchParams } = require('url');
require('dotenv').config();
const app = express();
const platformClient = require("purecloud-platform-client-v2");
var WebSocketClient = require('websocket').client;
const client = platformClient.ApiClient.instance;
client.setEnvironment(platformClient.PureCloudRegionHosts['us_west_2']); // Genesys Cloud region
let apiInstance = new platformClient.ArchitectApi();
// OAuth Code Authorization Credentials
const clientId = process.env.GENESYS_CLOUD_CLIENT_ID;
const clientSecret = process.env.GENESYS_CLOUD_CLIENT_SECRET;
const environment = process.env.GENESYS_CLOUD_ENVIRONMENT; // eg. 'mypurecloud.com'
const PORT = '8085';
console.log("client", clientId);
console.log("client secret", clientSecret);
console.log("environment", environment);
// >> START oauth-auth-code-step-2
/**
* This function is used as an express middleware and will be invoked in
* every HTTP request that hits the webserver. If there is no session with
* Genesys Cloud, redirect the user to the Genesys Cloud login page.
*/
const authvalidation = function (req, res, next) {
console.log(`\n[${req.method} ${req.url}]`);
// If we don't have a session then redirect them to the login page
if ((req.cookies && !(req.cookies.session && sessionMap[req.cookies.session])) &&
req.url.indexOf('oauth') == -1) {
//redirect the user to authorize with Genesys Cloud
var redirectUri = `https://login.${environment}/oauth/authorize?` +
'response_type=code' +
'&client_id=' + clientId +
`&redirect_uri=http://localhost:${PORT}/oauth2/callback`;
console.log('redirecting to ' + redirectUri);
res.redirect(redirectUri);
return;
}
console.log('Session exists')
next();
// if we do have a session, just pass along to the next http handler
};
const queueCheck= function(req, res, neext) {
}
// >> END oauth-auth-code-step-2
// Registration of express middlewares
app.use(express.json());
app.use(cookieParser());
app.use(authvalidation);
app.use(express.static(__dirname));
var sessionMap = {};
// >> START oauth-auth-code-step-3
//this route handles the oauth callback
app.get('/oauth2/callback', async function (req, res) {
// The authorization page has called this callback and now we need to get the bearer token
console.log('oauth callback')
console.log(req.query.code)
const authCode = req.query.code;
const params = new URLSearchParams();
params.append('grant_type', 'authorization_code');
params.append('code', authCode);
params.append('redirect_uri', `http://localhost:${PORT}/oauth2/callback`);
axios({
url: `https://login.${environment}/oauth/token`,
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(clientId + ':' + clientSecret).toString('base64')}`
},
params: params
})
.then(response => {
const tokenData = response.data;
console.log('got token data back: ')
console.log(tokenData);
var sessionId = uuidv4();
// Store the session id as a key in the session map, the value is the bearer token for Genesys Cloud.
// We want to keep that secure so won't send that back to the client
sessionMap[sessionId] = tokenData.access_token;
client.setAccessToken(tokenData.access_token);
// Send the session id back as a cookie
res.cookie('session', sessionId);
res.redirect(`https://apps.usw2.pure.cloud`);
getUserDetails(tokenData.access_token);
})
.catch(e => console.error(e));
function getUserDetails(token) {
axios({
url: `https://api.${environment}/api/v2/users/me`,
method: 'get',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
})
.then(response => {
const user = response.data.email;
updateDataTable(user, token);
console.log('Got response for /users/me');
console.log(user);
})
.catch(e => console.error(e));
}
function updateDataTable(email, access_token) {
let datatableId = "5d9ea952-f03b-4de0-8c72-b17adaf9fa22"; // String | id of datatable
let rowId = email; // String | the key for the row
console.log("email", email);
console.log("access token", access_token);
let opts = {
body: {
"Key": email,
"access_token": access_token
}
};
// Update a row entry
apiInstance.putFlowsDatatableRow(datatableId, rowId, opts)
.then((data) => {
console.log(`putFlowsDatatableRow success! data: ${JSON.stringify(data, null, 2)}`);
})
.catch((err) => {
console.log("There was a failure calling putFlowsDatatableRow");
console.error(err);
});
}
});
var httpServer = http.createServer(app);
httpServer.listen(PORT);
console.log(`Server ready: http://localhost:${PORT}`);
// >> END oauth-auth-code-step-1
// >> END oauth-auth-code