1 | function register (options) {
|
2 | const chalk = require('chalk')
|
3 | const request = require('superagent')
|
4 | const path = require('path')
|
5 | const arc = require('arc-bookiza')
|
6 | const osHomeDir = require('os').homedir()
|
7 | const fs = require('fs')
|
8 | const co = require('co')
|
9 | const prompt = require('co-prompt')
|
10 |
|
11 | let username = options.username
|
12 | let password = options.password
|
13 |
|
14 | co(function * () {
|
15 | if (username === undefined) {
|
16 | username = yield prompt('username: ')
|
17 | }
|
18 | if (password === undefined) {
|
19 | password = yield prompt.password('password: ')
|
20 | }
|
21 | }).then(() => {
|
22 |
|
23 |
|
24 | let location = path.join(__dirname, '..', '.bookizarc')
|
25 |
|
26 | arc.read(location)
|
27 | .then((data) => {
|
28 | let bookizArc = JSON.parse(data)
|
29 |
|
30 | let url = bookizArc.urls.registrationURL
|
31 | let method = 'post'
|
32 |
|
33 |
|
34 | request[method](url)
|
35 | .send()
|
36 | .auth(username, password)
|
37 | .set('Accept', 'application/json')
|
38 | .end((err, res) => {
|
39 | if (!err && res.ok) {
|
40 | bookizArc.token = res.body.key
|
41 | bookizArc.username = res.body.username
|
42 | bookizArc.email = res.body.email
|
43 |
|
44 | fs.writeFileSync(path.join(osHomeDir, '.', '.bookizarc'), JSON.stringify(bookizArc, null, 2))
|
45 |
|
46 | console.log(chalk.bold.cyan('Registration successful'))
|
47 | process.exit(0)
|
48 | }
|
49 |
|
50 | let errorMessage
|
51 |
|
52 | if (res && res.status === 401) {
|
53 | errorMessage = 'Authentication failed! Bad username/password?'
|
54 | } else if (err) {
|
55 | errorMessage = err
|
56 | } else {
|
57 | errorMessage = res.text
|
58 | }
|
59 | console.error(chalk.red(errorMessage))
|
60 | process.exit(1)
|
61 | })
|
62 | }).catch((err) => {
|
63 | console.error(`Couldn't read BookizArc: ${err}`)
|
64 | })
|
65 | }).catch((err) => {
|
66 | console.error(err)
|
67 | })
|
68 | }
|
69 |
|
70 | module.exports.register = register
|