summaryrefslogtreecommitdiffstats
path: root/server/api/roles.js
blob: ba1c2a27ab57ba13ce9971fb0ec3dd86be12255b (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
/* global __appdir */
var path = require('path')
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'))

// Permission check middleware
router.all(['', '/:x'], async (req, res, next) => {
  switch (req.method) {
    case 'GET':
      if (!await req.user.hasPermission('roles.view')) return res.status(403).send({ error: 'Missing permission', permission: 'roles.view' })
      break

    case 'POST':
      if (!await req.user.hasPermission('roles.edit')) return res.status(403).send({ error: 'Missing permission', permission: 'roles.edit' })
      break

    default:
      return res.status(400).send()
  }

  next()
})

/*
   * /<ROLE_ID>
   *
   * @return: Returns the information about a role and it's permissions and groups.
   */
router.getAsync('/:id', async (req, res) => {
  // if (!await req.user.hasPermission('permissions.*')) return res.status(403).end()

  var role = await db.role.findOne({ where: { id: req.params.id }, include: ['permissions', 'groups'] })
  if (role) res.send(role)
  else res.status(404).end()
})

/*
   * @return: Returns a list of all roles in the database.
   */
router.getAsync('', async (req, res) => {
  // if (!await req.user.hasPermission('permissions.*')) return res.status(403).end()

  var roles = await db.role.findAll({ include: ['permissions', 'groups'] })
  if (roles) res.status(200).send(roles)
  else res.status(404).end()
})

/*
   * name: <ROLE_NAME>
   * descr: <ROLE_DESCRIPTION>
   * permissions: <PERMISSION_IDS>
   * groups: <GROUP_IDS>,
   * blacklist: <GROUP_IDS>
   *
   * Creates, updates or deletes a role.
   *
   */
router.postAsync(['', '/:id'], async (req, res) => {
  // if (!await req.user.hasPermission('permissions.editrole')) return res.status(403).end()

  // ?delete Delete the roles
  if (req.query.delete !== undefined && req.query.delete !== 'false') {
    const user = await db.user.findOne({ where: { id: req.user.id } })

    // Only need to log batch request if there is more than one event to delete.
    if (req.body.ids.length > 1) {
      await log({
        category: 'ROLE_BATCH_DELETE',
        description: 'Role batch deletion of ' + req.body.ids.length + ' roles initiated by user.',
        user,
        userId: req.user.id
      })
    }

    let deletionCounter = 0
    // Delete every event on its own, to get a better log
    for (let index in req.body.ids) {
      const role = await db.role.findOne({ where: { id: req.body.ids[index] } })
      const count = await db.role.destroy({ where: { id: req.body.ids[index] } })

      if (count !== 1) {
        await log({
          category: 'ERROR_ROLE_DELETE',
          description: '[' + role.id + '] ' + role.name + ': Role could not be deleted.\n' +
                       'ID: ' + role.id + '\n' +
                       'Name: ' + role.name + '\n' +
                       'Description: ' + role.descr + '\n',
          user,
          userId: req.user.id
        })
      } else {
        await log({
          category: 'ROLE_DELETE',
          description: '[' + role.id + '] ' + role.name + ': Role successfully deleted.\n' +
                       'ID: ' + role.id + '\n' +
                       'Name: ' + role.name + '\n' +
                       'Description: ' + role.descr + '\n',
          user,
          userId: req.user.id
        })
        deletionCounter++
      }
    }
    if (req.body.ids.length > 1) {
      log({
        category: 'ROLE_BATCH_DELETE',
        description: deletionCounter + '/' + req.body.ids.length + ' roles successfully deleted.',
        user,
        userId: req.user.id
      })
    }
    HttpResponse.successBatch('deleted', 'role', deletionCounter).send(res)

    // res.status(200).send('success')
  } else {
    var promises = []
    var roleDb
    if (req.params.id === undefined) {
      // Create new role
      roleDb = await db.role.create({ name: req.body.name, descr: req.body.description })
      promises.push(roleDb.addPermissions(req.body.permissions))
      promises.push(roleDb.addGroups(req.body.groups, { through: { blacklist: 0 } }))
      promises.push(roleDb.addGroups(req.body.blacklist, { through: { blacklist: 1 } }))
      await Promise.all(promises)
      log({
        category: 'ROLE_CREATE',
        description: '[' + roleDb.id + '] ' + roleDb.name + ': Event successfully created.\n' +
                     'ID: ' + roleDb.id + '\n' +
                     'Name: ' + roleDb.name + '\n' +
                     'Description: ' + roleDb.descr + '\n' +
                     'Permissions: ' + req.body.permissions + '\n' +
                     'Groups: ' + req.body.groups + '\n' +
                     'Blacklist: ' + req.body.blacklist,
        userId: req.user.id
      })
      res.send({ id: req.body.id })
    } else if (req.params.id > 0) {
      // Update existing role
      roleDb = await db.role.findOne({ where: { id: req.params.id } })
      if (roleDb !== null) {
        await roleDb.update({ name: req.body.name, descr: req.body.description })
        await roleDb.setPermissions(req.body.permissions)
        await roleDb.setGroups(req.body.groups, { through: { blacklist: 0 } })
        await roleDb.addGroups(req.body.blacklist, { through: { blacklist: 1 } })
        log({
          category: 'ROLE_EDIT',
          description: '[' + roleDb.id + '] ' + roleDb.name + ': Role successfully edited.\n' +
                       'ID: ' + roleDb.id + '\n' +
                       'Name: ' + roleDb.name + '\n' +
                       'Description: ' + roleDb.descr + '\n' +
                       'Permissions: ' + req.body.permissions + '\n' +
                       'Groups: ' + req.body.groups + '\n' +
                       'Blacklist: ' + req.body.blacklist,
          userId: req.user.id
        })
        res.send({ id: req.params.id })
      } else {
        res.status(404).end()
      }
    }
  }
})

module.exports.router = router