summaryrefslogtreecommitdiffstats
path: root/server/api/setup.js
blob: 228229a955dfce1ecdeb2d834dbe84189c091e7f (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
/* global __appdir */
const path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
var express = require('express')
const { decorateApp } = require('@awaitjs/express')
var noAuthRouter = decorateApp(express.Router())
var authentication = require(path.join(__appdir, 'lib', 'authentication'))

// Setup method for checking if setup is possible.
noAuthRouter.get('/status', (req, res) => {
  db.user.findAll().then(users => {
    if (users.length > 0) res.status(403).send({ error: 'USERTABLE_NOT_EMPTY', message: 'The user table is not empty, unauthorized creation is forbidden.' })
    else res.send()
  })
})

// Setup method for creating the initial root account.
noAuthRouter.postAsync('/', async (req, res) => {
  const body = req.body
  const users = await db.user.findAll()
  if (users.length > 0) res.status(403).send({ error: 'USERTABLE_NOT_EMPTY', message: 'The user table is not empty, unauthorized creation is forbidden.' })
  else {
    const result = await authentication.signup(body)
    const code = result.code
    delete result.code
    if (result.error) return res.status(code).send(result)

    const user = await db.user.findOne({ where: { id: result.id } })
    const roleDb = await db.role.create({ name: user.username, descr: 'Superadmin' })
    const permission = await db.permission.findOne({ where: { name: 'superadmin' } })
    await roleDb.addPermissions(permission.id)
    await user.addRoles(roleDb.id)
    res.send()
  }
})

module.exports.noAuthRouter = noAuthRouter