summaryrefslogtreecommitdiffstats
path: root/server/lib/permissions/index.js
blob: a0af9d4648c415dd38292264817c46e38f199a4a (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
/* global __appdir */
const path = require('path')
var permissions = require(path.join(__appdir, 'lib', 'permissions', 'permissions'))
var db = require(path.join(__appdir, 'lib', 'sequelize'))

updatePermissionDatabase()

/*
   * Update the permission-Database accordingly to the permission.json
   */
function updatePermissionDatabase () {
  var permissionNames = []

  // Insert / Update entries in Database which are in the permission.json
  permissions.forEach(function (permission) {
    permissionNames.push(permission.name)
    upsert(db.permission, { name: permission.name, descr: permission.descr, groupdependent: permission.groupdependent }, { name: permission.name })
  })

  // Delete entries from Database which are not in the permission.json
  db.permission.destroy(
    { where: { [db.Op.not]: { name: permissionNames } } }
  )
}

/*
   * model: <DB_MODEL>
   * newItem: <DB_OBJECT>
   * where: <DB_WHERECLAUSE>
   *
   * Updates or inserts the given newItem in the given model according to
   * the where-clause.
   */
function upsert (model, newItem, where) {
  return model
    .findOne({ where: where })
    .then(function (foundItem) {
      if (!foundItem) {
        return model
          .create(newItem)
          .then(function (item) { return { item: item, created: true } })
      }

      return model
        .update(newItem, { where: where })
        .then(function (item) { return { item: item, created: false } })
    })
}