/* 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