Skip to content

Instantly share code, notes, and snippets.

@Purush0th
Created December 26, 2023 17:25
Show Gist options
  • Save Purush0th/a8f41a2ae0feed56cf98389ab3534779 to your computer and use it in GitHub Desktop.
Save Purush0th/a8f41a2ae0feed56cf98389ab3534779 to your computer and use it in GitHub Desktop.
Superset Guest Token Generation - Node.js
var express = require('express');
const axios = require('axios');
var https = require('https');
var router = express.Router();
var supersetBaseUrl = 'http://localhost:8088/api/v1';
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
})
axios.defaults.httpsAgent = httpsAgent
// eslint-disable-next-line no-console
console.log(process.env.NODE_ENV, `RejectUnauthorized is disabled.`)
/* GET home page. */
router.post('/guest-token', async (req, res) => {
let user = req.body.user;
let dashboardId = req.body.dashboard_id;
let tokenResponse = await getAppToken();
let csrfTokenResponse = await getCsrfToken();
var csrfToken = csrfTokenResponse[0].result;
var sessionCookie = csrfTokenResponse[1];
let guestTokenResponse = await getGuestToken(user, dashboardId, tokenResponse.access_token, csrfToken, sessionCookie);
res.send(guestTokenResponse);
});
async function getAppToken() {
let data = JSON.stringify({
"password": "admin",
"provider": "db",
"refresh": true,
"username": "admin"
});
let config = {
method: 'post',
url: `${supersetBaseUrl}/security/login`,
headers: {
'Content-Type': 'application/json'
},
data: data
};
var response = await axios.request(config);
return response.data;
}
async function getCsrfToken() {
let config = {
method: 'get',
url: `${supersetBaseUrl}/security/csrf_token/`
};
var response = await axios.request(config);
console.log(response.headers);
const cookieName = "session";
const sessionCookie = (response.headers['set-cookie'])
.find(cookie => cookie.includes(cookieName))
?.match(new RegExp(`^${cookieName}=(.+?);`))
?.[1];
return [response.data, sessionCookie];
}
async function getGuestToken(user, dashboardId, appToken, csrfToken, sessionCookie) {
console.log(sessionCookie, csrfToken);
try {
let data = JSON.stringify({
"user": user,
"resources": [
{
"type": "dashboard",
"id": dashboardId
}
],
"rls": []
});
let config = {
method: 'post',
url: `${supersetBaseUrl}/security/guest_token/`,
headers: {
'X-CSRFToken': csrfToken,
'Authorization': 'Bearer ' + appToken,
'Content-Type': 'application/json',
'Cookie': 'session=' + sessionCookie
},
withCredentials: true,
data: data
};
var response = await axios.request(config);
return response.data;
} catch (error) {
return "";
}
}
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment