-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathtokenapp.js
103 lines (91 loc) · 3.43 KB
/
tokenapp.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const { RingRestClient } = require('../node_modules/@tsightler/ring-client-api/lib/api/rest-client')
const debug = require('debug')('ring-mqtt')
const express = require('express')
const bodyParser = require("body-parser")
class TokenApp {
constructor() {
this.app = express()
this.listener = false
// Helper property to pass values between main code and web server
this.token = {
connected: '',
generatedInternal: '',
generatedListener: function(val) {},
set generated(val) {
this.generatedInternal = val;
this.generatedListener(val);
},
get generated() {
return this.generatedInternal;
},
registerListener: function(listener) {
this.generatedListener = listener;
}
}
}
// Super simple web service to acquire refresh tokens
async start(runMode) {
if (this.listener) {
return
}
const webdir = __dirname+'/../web'
let restClient
this.listener = this.app.listen(55123, () => {
if (runMode !== 'addon') {
debug('Use http://<host_ip_address>:55123/ to generate a valid token.')
}
})
this.app.use(bodyParser.urlencoded({ extended: false }))
this.app.get('/', (req, res) => {
if (!this.token.connected) {
res.sendFile('account.html', {root: webdir})
} else {
res.sendFile('connected.html', {root: webdir})
}
})
this.app.get(/.*force-token-generation$/, (req, res) => {
res.sendFile('account.html', {root: webdir})
})
this.app.post(/.*submit-account$/, async (req, res) => {
const email = req.body.email
const password = req.body.password
restClient = await new RingRestClient({ email, password })
// Check if the user/password was accepted
try {
await restClient.getCurrentAuth()
} catch(error) {
if (restClient.using2fa) {
debug('Username/Password was accepted, waiting for 2FA code to be entered.')
res.sendFile('code.html', {root: webdir})
} else {
res.cookie('error', error.message, { maxAge: 1000, encode: String })
res.sendFile('account.html', {root: webdir})
}
}
})
this.app.post(/.*submit-code$/, async (req, res) => {
let generatedToken
const code = req.body.code
try {
generatedToken = await restClient.getAuth(code)
} catch(_) {
generatedToken = ''
const errormsg = 'The 2FA code was not accepted, please verify the code and try again.'
debug(errormsg)
res.cookie('error', errormsg, { maxAge: 1000, encode: String })
res.sendFile('code.html', {root: webdir})
}
if (generatedToken) {
res.sendFile('restart.html', {root: webdir})
this.token.generated = generatedToken.refresh_token
}
})
}
async stop() {
if (this.listener) {
await this.listener.close()
this.listener = false
}
}
}
module.exports = new TokenApp()