Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Code Block
languagejs
linenumberstrue
collapsetrue
const http = require('http');

let accessToken = '';
const hostname = 'localhost';
const port = 4446;

/**
 * Function to sign in with user credentials
 * @param {string} user - User Account
 * @param {string} password - Password
 */
function signIn(user, password) {
    const authString = `${user}:${password}`;
    const base64AuthString = Buffer.from(authString, 'utf-8').toString('base64');
    const path = '/joc/api/authentication/login';
    const headers = {
        'Authorization': 'Basic ' + base64AuthString
    };

    postApi(path, headers);
}

/**
 * Function to retrieve JOC Cockpit permissions
 * @param {string} token - Access token
 */
function getJocCockpitPermissions(token) {
    const path = '/joc/api/authentication/joc_cockpit_permissions';
    let headers;
    if (token !== '') {
        headers = {
            'X-Access-Token': token
        };
        postApi(path, headers);
    }
}

/**
 * Function to sign out
 * @param {string} token - Access token
 */
function signOut(token) {
    const path = '/joc/api/authentication/logout';
    let headers;
    if (token !== '') {
        headers = {
            'X-Access-Token': token
        };
        postApi(path, headers);
    }
}

/**
 * Function to send a POST request to the API
 * @param {string} path - API path
 * @param {object} headers - Request headers
 */
function postApi(path, headers) {
    const options = {
        hostname: hostname,
        port: port,
        path: path,
        method: 'POST',
        headers: headers
    };

    const req = http.request(options, (res) => {
        let data = '';
        res.on('data', (chunk) => {
            data += chunk;
        });
        console.log(res.statusCode);

        res.on('end', () => {
            console.log(data, 'dta');
            let response = JSON.parse(data);
            if (response.accessToken && response.accessToken !== undefined) {
                accessToken = response.accessToken;
                getJocCockpitPermissions(accessToken);
            }
        });
    });

    req.on('error', (error) => {
        console.error(error);
    });

    req.end();
}

// Call the signIn function with the provided user account and password
signIn('root', 'root');

// Call the signOut function to log out and to invalidate the access token
if (accessToken) {
	signOut(accessToken);
}