glpi-client
Version:
GLPI API Client written in Typescript
63 lines (62 loc) • 2.88 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const GlpiSocket_1 = require("./GlpiSocket");
const GlpiAPI_1 = require("./GlpiAPI");
class GlpiClient {
constructor(url) {
this.httpDefaults = {};
this.url = url;
}
initSession(auth, relogin = false) {
return __awaiter(this, void 0, void 0, function* () {
let authorization = '';
if (auth.user) {
const b64 = Buffer.from(`${auth.user.username}:${auth.user.password}`).toString('base64');
authorization = 'Basic ' + b64;
}
else {
authorization = 'user_token ' + auth.userToken;
}
const socket = new GlpiSocket_1.GlpiSocket(this.url, {
'Authorization': authorization,
'App-Token': auth.appToken,
});
const response = yield socket.call('GET', 'initSession');
const authenticatedSocket = new GlpiSocket_1.GlpiSocket(this.url, {
'App-Token': auth.appToken,
'Session-Token': response.data.session_token,
});
const api = new GlpiAPI_1.GlpiAPI(authenticatedSocket);
if (relogin)
this.ajustRelogin(api, auth);
return api;
});
}
ajustRelogin(api, auth) {
const http = api.getHttpSocket();
const interceptor = http.interceptors.response.use(undefined, (error) => __awaiter(this, void 0, void 0, function* () {
const status = error.response ? error.response.status : 0;
if (status === 401) {
const client = new GlpiClient(this.url);
const newApi = yield client.initSession(auth);
const originalHttp = api.getHttpSocket();
const newHttp = newApi.getHttpSocket();
Object.assign(originalHttp.defaults, newHttp.defaults);
Object.assign(this.httpDefaults, originalHttp.defaults);
Object.assign(error.config, this.httpDefaults);
return api.getHttpSocket().request(error.config);
}
throw error;
}));
api.setReloginInterceptor(interceptor);
}
}
exports.GlpiClient = GlpiClient;