UNPKG

3 kBJavaScriptView Raw
1#! /usr/bin/env node
2
3'use strict'
4
5const path = require('path')
6
7let Connection
8let config
9
10try {
11 Connection = require('@dadi/api').Connection
12 config = require('@dadi/api').Config
13} catch (err) {
14 Connection = require(path.join(__dirname, '/../dadi/lib/model/connection'))
15 config = require(path.join(__dirname, '/../config'))
16}
17
18const clientCollectionName = config.get('auth.clientCollection')
19const dbOptions = { override: true, database: config.get('auth.database'), collection: clientCollectionName }
20const connection = Connection(dbOptions, config.get('auth.datastore'))
21
22const prompt = require('cli-prompt')
23
24let connected = false
25
26// Temporarily restore original console
27delete console.log
28
29connection.on('connect', db => {
30 if (connected) return
31
32 connected = true
33
34 setTimeout(() => {
35 console.log()
36 console.log('==================================')
37 console.log(' DADI API Client Record Generator ')
38 console.log('==================================')
39 console.log()
40
41 prompt.multi([
42 {
43 label: '-> Client identifier',
44 key: 'clientId',
45 default: 'api-client'
46 },
47 {
48 label: '-> Secret access key',
49 key: 'secret',
50 default: 'client-secret'
51 },
52 {
53 label: '-> Access type (admin, user)',
54 key: 'accessType',
55 default: 'user'
56 },
57 {
58 label: '(!) Is this ok?',
59 key: 'confirm',
60 type: 'boolean'
61 }
62 ], options => {
63 if (options.confirm) {
64 delete options.confirm
65
66 // check for an existing client account
67 db.find({
68 query: {
69 clientId: options.clientId
70 },
71 collection: clientCollectionName,
72 schema: getSchema().fields,
73 settings: getSchema().settings
74 }).then(existingClients => {
75 if (existingClients.results.length > 0) {
76 console.log(`(x) The identifier ${options.clientId} already exists. Exiting...`)
77 return
78 }
79
80 console.log(options)
81
82 db.insert({
83 data: options,
84 collection: clientCollectionName,
85 schema: getSchema().fields,
86 settings: getSchema().settings
87 }).then(result => {
88 console.log()
89 console.log('(*) Client created successfully:')
90 console.log()
91 console.log(options)
92 console.log()
93
94 process.exit(0)
95 }).catch((err) => {
96 throw err
97 })
98 })
99 } else {
100 process.exit(0)
101 }
102 })
103 }, 1000)
104})
105
106function getSchema () {
107 return {
108 fields: {
109 token: {
110 type: 'String',
111 required: true
112 },
113 tokenExpire: {
114 type: 'Number',
115 required: true
116 },
117 created: {
118 type: 'DateTime',
119 required: true
120 },
121 value: {
122 type: 'Object',
123 required: false
124 }
125 },
126 settings: {
127 cache: false
128 }
129 }
130}