summaryrefslogtreecommitdiffstats
path: root/server/lib/external-backends/backends/idoit-backend.js
blob: d95618dcfc04e3828738468df6e8f4f076d0bc99 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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