summaryrefslogtreecommitdiffstats
path: root/server/api/ipxeconfigs.js
blob: 3c6f6ebed6952f4aebe1ff285f4c7e256b4fa542 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/* global __appdir */
var path = require('path')
var Sequelize = require('sequelize')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
var express = require('express')
const { decorateApp } = require('@awaitjs/express')
var router = decorateApp(express.Router())
const HttpResponse = require(path.join(__appdir, 'lib', 'httpresponse'))
const log = require(path.join(__appdir, 'lib', 'log'))

// ############################################################################
// ###########################  GET requests  #################################

router.getAsync('', async (req, res) => {
  const configs = await db.config.findAll({
    include: [{ association: 'groups', attributes: [] }, { association: 'clients', attributes: [] }],
    attributes: {
      include: [
        [Sequelize.fn('COUNT', Sequelize.col('groups.id')), 'groupCount'],
        [Sequelize.fn('COUNT', Sequelize.col('clients.id')), 'clientCount']
      ]
    },
    group: ['id']
  })
  res.status(200).send(configs)
})

router.getAsync('/:id', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  const config = await db.config.findOne({ where: { id: req.params.id }, include: ['groups', 'clients'] })
  if (config) res.status(200).send(config)
  else HttpResponse.notFound(req.params.id).send(res)
})

router.getAsync('/:id/entries', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  const config = await db.config.findOne({
    where: { id: req.params.id },
    include: ['entries'],
    order: [[db.config.associations.entries, db.config.associations.entries.through, 'sortValue', 'ASC']]
  })
  if (config) res.status(200).send(config.entries)
  else HttpResponse.notFound(req.params.id).send(res)
})

router.getAsync('/:id/groups', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  const config = await db.config.findOne({ where: { id: req.params.id }, include: ['groups'] })
  if (config) res.status(200).send(config.groups)
  else HttpResponse.notFound(req.params.id).send(res)
})

router.getAsync('/:id/clients', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  const config = await db.config.findOne({ where: { id: req.params.id }, include: ['clients'] })
  if (config) res.status(200).send(config.clients)
  else HttpResponse.notFound(req.params.id).send(res)
})

// ############################################################################
// ##########################  POST requests  #################################

router.postAsync(['', '/:id'], async (req, res) => {
  if (req.query.delete !== undefined && req.query.delete !== 'false') {
    if (!Array.isArray(req.body.ids)) return HttpResponse.invalidBodyValue('ids', 'an array').send(res)

    const user = await db.user.findOne({ where: { id: req.user.id } })
    // Only need to log batch request if there is more than one ipxeconfig to delete.
    if (req.body.ids.length > 1) {
      await log({
        category: 'IPXECONFIG_BATCH_DELETE',
        description: 'Batch deletion of ' + req.body.ids.length + ' ipxe configs initiated by user.',
        user,
        userId: req.user.id
      })
    }

    let deletionCounter = 0
    // Delete every config on its own, to get a better log
    for (let index in req.body.ids) {
      const config = await db.config.findOne({ where: { id: req.body.ids[index] } })
      const count = await db.config.destroy({ where: { id: req.body.ids[index] } })
      if (count !== 1) {
        await log({
          category: 'ERROR_IPXECONFIG_DELETE',
          description: '[' + config.id + '] ' + config.name + ': Ipxe config could not be deleted.\n' +
                       'ID: ' + config.id + '\n' +
                       'Name: ' + config.name + '\n' +
                       'Description: ' + config.description + '\n' +
                       'Default Entry: ' + config.defaultEntry + '\n' +
                       'Timeout: ' + config.timeout + '\n' +
                       'Default Config: ' + config.isDefault,
          user,
          userId: req.user.id
        })
      } else {
        await log({
          category: 'IPXECONFIG_DELETE',
          description: '[' + config.id + '] ' + config.name + ': Ipxe config successfully deleted.\n' +
                       'ID: ' + config.id + '\n' +
                       'Name: ' + config.name + '\n' +
                       'Description: ' + config.description + '\n' +
                       'Default Entry: ' + config.defaultEntry + '\n' +
                       'Timeout: ' + config.timeout + '\n' +
                       'Default Config: ' + config.isDefault,
          user,
          userId: req.user.id
        })
        deletionCounter++
      }
    }
    if (req.body.ids.length > 1) {
      log({
        category: 'IPXECONFIG_BATCH_DELETE',
        description: deletionCounter + '/' + req.body.ids.length + ' ipxe configs successfully deleted.',
        user,
        userId: req.user.id
      })
    }

    HttpResponse.successBatch('deleted', 'ipxe config', deletionCounter).send(res)
  } else {
    let config
    let action = 'updated'
    if (req.params.id === undefined) {
      config = await db.config.create(req.body.data)
      log({
        category: 'IPXECONFIG_CREATE',
        description: '[' + config.id + '] ' + config.name + ': Ipxe config successfully created.\n' +
                     'ID: ' + config.id + '\n' +
                     'Name: ' + config.name + '\n' +
                     'Description: ' + config.description + '\n' +
                     'Default Entry: ' + config.defaultEntry + '\n' +
                     'Timeout: ' + config.timeout + '\n' +
                     'Default Config: ' + config.isDefault,
        userId: req.user.id
      })
      action = 'created'
    } else if (req.params.id > 0) {
      config = await db.config.findOne({ where: { id: req.params.id } })
      if (!config) return HttpResponse.notFound(req.params.id).send(res)
      else {
        await config.update(req.body.data)
        log({
          category: 'IPXECONFIG_EDIT',
          description: '[' + config.id + '] ' + config.name + ': Ipxe config successfully edited.\n' +
                       'ID: ' + config.id + '\n' +
                       'Name: ' + config.name + '\n' +
                       'Description: ' + config.description + '\n' +
                       'Default Entry: ' + config.defaultEntry + '\n' +
                       'Timeout: ' + config.timeout + '\n' +
                       'Default Config: ' + config.isDefault,
          userId: req.user.id
        })
      }
    } else {
      return HttpResponse.invalidId().send(res)
    }
    await config.setEntries([])
    if (req.body.entries.length > 0) {
      const promises = []
      req.body.entries.forEach((entry, index) => {
        promises.push(config.addEntry(entry.id, { through: { sortValue: index, customName: entry.customName, keyBind: entry.keyBind } }))
      })
      await Promise.all(promises)
    }
    HttpResponse.success(action, 'ipxe entry', config.id).send(res)
  }
})

// ############################################################################
// ###########################  PUT requests  #################################

router.putAsync('/:id/groups', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  if (!Array.isArray(req.body.ids)) return HttpResponse.invalidBodyValue('ids', 'an array').send(res)
  const config = await db.config.findOne({ where: { id: req.params.id } })
  if (config) {
    await config.setGroups(req.body.ids)
    HttpResponse.success('set', 'clients of ipxe config', config.id).send(res)
    log({
      category: 'IPXECONFIG_SET_GROUPS',
      description: '[' + config.id + '] ' + config.name + ': ' + req.body.ids.length + ' groups successfully set.\n' +
                   'ID: ' + config.id + '\n' +
                   'Name: ' + config.name + '\n' +
                   'Description: ' + config.description + '\n' +
                   'Default Entry: ' + config.defaultEntry + '\n' +
                   'Timeout: ' + config.timeout + '\n' +
                   'Default Config: ' + config.isDefault + '\n' +
                   'Groups: ' + req.body.ids,
      userId: req.user.id
    })
  } else {
    HttpResponse.notFound(req.params.id).send(res)
  }
})

router.putAsync('/:id/clients', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  if (!Array.isArray(req.body.ids)) return HttpResponse.invalidBodyValue('ids', 'an array').send(res)
  const config = await db.config.findOne({ where: { id: req.params.id } })
  if (config) {
    await config.setClients(req.body.ids)
    log({
      category: 'IPXECONFIG_SET_CLIENTS',
      description: '[' + config.id + '] ' + config.name + ': ' + req.body.ids.length + ' clients successfully set.\n' +
                   'ID: ' + config.id + '\n' +
                   'Name: ' + config.name + '\n' +
                   'Description: ' + config.description + '\n' +
                   'Default Entry: ' + config.defaultEntry + '\n' +
                   'Timeout: ' + config.timeout + '\n' +
                   'Default Config: ' + config.isDefault + '\n' +
                   'Clients: ' + req.body.ids,
      userId: req.user.id
    })
    HttpResponse.success('set', 'clients of ipxe config', config.id).send(res)
  } else {
    HttpResponse.notFound(req.params.id).send(res)
  }
})

router.putAsync('/:id/default', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  const config = await db.config.findOne({ where: { id: req.params.id } })
  const oldDefault = await db.config.findOne({ where: { isDefault: true } })
  if (config) {
    await db.config.update({ isDefault: false }, { where: { isDefault: true } })
    await config.update({ isDefault: true })
    log({
      category: 'IPXECONFIG_SET_DEFAULT',
      description: '[' + config.id + '] ' + config.name + ': Config successfully set as default.\n' +
                   'Old Default: [' + oldDefault.id + '] ' + oldDefault.name + '\n' +
                   'New Default: [' + config.id + '] ' + config.name,
      userId: req.user.id
    })
    HttpResponse.success('set as default:', 'config', config.id).send(res)
  } else {
    HttpResponse.notFound(req.params.id).send(res)
  }
})

// ############################################################################
// ##########################  DELETE requests  ###############################

router.deleteAsync('/:id', async (req, res) => {
  if (!(req.params.id > 0)) return HttpResponse.invalidId().send(res)
  const config = await db.config.findOne({ where: { id: req.params.id } })
  const count = await db.config.destroy({ where: { id: req.params.id } })

  if (count) {
    log({
      category: 'IPXECONFIG_DELETE',
      description: '[' + config.id + '] ' + config.name + ': Ipxe config successfully deleted.\n' +
                   'ID: ' + config.id + '\n' +
                   'Name: ' + config.name + '\n' +
                   'Description: ' + config.description + '\n' +
                   'Default Entry: ' + config.defaultEntry + '\n' +
                   'Timeout: ' + config.timeout + '\n' +
                   'Default Config: ' + config.isDefault,
      userId: req.user.id
    })
    HttpResponse.success('deleted', 'config', req.params.id).send(res)
  } else HttpResponse.notFound(req.params.id).send(res)
})

// ############################################################################
// ############################################################################

module.exports.router = router