UNPKG

2.15 kBJavaScriptView Raw
1// use these ENV variables to skip the prompts:
2// - INSIGHTS_SUPERUSER_EMAIL
3// - INSIGHTS_SUPERUSER_PASSWORD
4
5process.env.NODE_ENV = 'production'
6
7const app = require('insights-api/lib/app').default
8const prompt = require('prompt-promise')
9const randomString = require('./lib/random-string')
10
11const azAZ09 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
12
13function validateEmail (email) {
14 var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
15 return re.test(email)
16}
17
18async function createSuperuser ({ login = true, exit = true } = {}) {
19 if (login) {
20 console.log('Creating a new superuser')
21 console.log('')
22 }
23
24 let email = process.env.INSIGHTS_SUPERUSER_EMAIL || ''
25 if (!login && email && !validateEmail(email)) {
26 email = 'root@localhost'
27 }
28
29 let repeat = !email || !validateEmail(email)
30
31 while (repeat) {
32 email = (await prompt('email: ')).trim()
33
34 if (email && validateEmail(email)) {
35 repeat = false
36 } else {
37 console.error('!! E-mail not valid! Please try again or hit CTRL+C to cancel')
38 console.log('')
39 }
40 }
41
42 let password = !login || process.env.INSIGHTS_SUPERUSER_PASSWORD || (await prompt.password('password (type or hit [enter] to autogenerate): '))
43 let passwordGenerated = false
44
45 if (!password) {
46 passwordGenerated = true
47 password = randomString(30, azAZ09)
48 }
49
50 try {
51 if (!login) {
52 await app.service('users').create({
53 email: email,
54 roles: ['superuser']
55 })
56 } else {
57 await app.service('users').create({
58 email: email,
59 password: password,
60 roles: ['superuser']
61 })
62
63 console.log('')
64 console.log('Superuser created!')
65 console.log(` email: ${email}`)
66 console.log(` password: ${passwordGenerated ? password : '<whatever you entered>'}`)
67 }
68 } catch (error) {
69 console.error('Could not create superuser! Exception:')
70 console.error(error)
71 process.exit(1)
72 }
73
74 if (exit) {
75 process.exit(0)
76 }
77}
78
79module.exports = createSuperuser