var ExternalBackends = require('../external-backends.js') var axios = require('axios') class IdoitBackend extends ExternalBackends { getCredentials () { // I do it only needs the API-key. return [ { type: 'text', id: 1, name: 'API url', icon: 'link' }, { type: 'password', id: 2, name: 'API token', icon: 'vpn_key', show: false }, { type: 'switch', id: 3, name: 'Login', icon: 'lock_open', elements: [ { type: 'text', id: 4, name: 'username', icon: 'person_outline' }, { type: 'password', id: 5, name: 'password', icon: 'lock', show: false } ] } ] } async checkConnection (backend) { const credentials = JSON.parse(backend.credentials) const url = credentials.find(x => x.id === 1).value const apiKey = credentials.find(x => x.id === 2).value const body = { 'version': '2.0', 'method': 'idoit.login', 'params': { 'apikey': apiKey, 'language': 'en' }, 'id': 1 } var config = { timeout: 30000, headers: { 'Content-Type': 'application/json' } } // Optional credentials const login = credentials.find(x => x.id === 3) if (login.value) { config.headers['X-RPC-Auth-Username'] = login.elements.find(x => x.id === 4).value config.headers['X-RPC-Auth-Password'] = login.elements.find(x => x.id === 5).value } // Make a login request and see if we are authenticated. var response = await axios.post(url, body, config) .then(response => { return response }) .catch(error => { console.log(error) return error.response ? error.response : { status: 900, statusText: 'Request failed timeout' } }) // Axios error handling if (response.status !== 200) { return { success: false, error: response.status, msg: response.statusText } } // iDoIT error handling. if (response.data.result) { return { success: true } } else if (response.data.error) { return { success: false, error: response.data.error.message, msg: response.data.error.data.error } } else { return { success: false, msg: 'UNNOWN ERROR' } } } } module.exports = IdoitBackend