All files / src AdminModule.ts

83.33% Statements 15/18
83.33% Branches 5/6
60% Functions 3/5
83.33% Lines 15/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 432x 2x 2x         2x   29x                 2x 2x       2x 2x 2x 2x   2x       2x 1x   1x              
import { Commun, SecurityUtils, UnauthorizedError } from '@commun/core'
import { AdminRouter } from './routers/AdminRouter'
import { AdminController } from './controllers/AdminController'
 
let firstRunCode: string | undefined
let serverStartTime: number
 
export const AdminModule = {
  async setup () {
    Commun.registerPlugin('admin', {
      controller: AdminController,
      router: AdminRouter,
      afterServerStart: () => this.prepareFirstRun(),
    })
  },
 
  async prepareFirstRun () {
    let dao
    try {
      dao = Commun.getEntityDao('users')
    } catch (e) {
      throw new Error('Admin plugin depends on users entity')
    }
    Eif (!await dao.getEstimatedCount()) {
      firstRunCode = SecurityUtils.generateRandomString(36)
      console.log(`    🔑 Register your first admin account: ${Commun.getOptions().endpoint}/dashboard/signup?code=${firstRunCode}`)
      console.log()
    }
    serverStartTime = new Date().getTime()
  },
 
  validateFirstRunCode (code: string) {
    if (!firstRunCode || code !== firstRunCode) {
      throw new UnauthorizedError()
    }
    return true
  },
 
  getServerStartTime () {
    return serverStartTime
  },
}