Hi team,
I have created my own Genesys login application using authorization code grant type method. When I run my application, it will redirect me to Genesys page where I give my Genesys credentials. Then after login, I am giving url for redirecting the users to Genesys page. But its not going to that page, instead its going to maintanace page and its showing "App initialization error" with reload option. When I click reload then its going to Genesys page. So I need to skip this maintanance page.
My Application running in local server
I am giving my Genesys credentials
After that Genesys lands me in maintanace page
Javascript code:
// >> 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/directory/#access_token=${tokenData.access_token}&expires_in=${tokenData.expires_in}&state={%23%2F}&token_type=${tokenData.token_type}`);
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
Thanks,
Magudeeswaran