forked from hpcreery/homebridge-smartrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (75 loc) · 2.13 KB
/
server.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
const {
HomebridgePluginUiServer,
RequestError,
} = require('@homebridge/plugin-ui-utils');
const fs = require('fs');
const fsPromises = fs.promises;
const { SmartRentAuthClient } = require('../dist/lib/auth');
class PluginUiServer extends HomebridgePluginUiServer {
constructor() {
super();
this.sessionPath = `${this.homebridgeStoragePath}/smartrent/session.json`;
this.onRequest('/session', this.checkSession.bind(this));
this.onRequest('/logout', this.clearSession.bind(this));
this.onRequest('/login', this.login.bind(this));
this.ready();
}
async checkSession() {
try {
if (fs.existsSync(this.sessionPath)) {
return { code: 200 };
}
return { code: 404 };
} catch (error) {
throw new RequestError('Failed to check session', {
message: error.message,
});
}
}
async clearSession() {
try {
if ((await this.checkSession()).code === 200) {
await fsPromises.rm(this.sessionPath);
}
return { code: 200 };
} catch (error) {
throw new RequestError('Failed to delete auth token', {
message: error.message,
});
}
}
async login(payload) {
try {
const { email, password, tfaCode } = payload;
if (!email) {
console.error('Email required');
return { code: 401, message: 'Email required' };
}
if (!password) {
console.error('Password required');
return { code: 401, message: 'Password required' };
}
const authClient = new SmartRentAuthClient(this.homebridgeStoragePath);
const accessToken = await authClient.getAccessToken({
email,
password,
tfaCode,
});
if (accessToken) {
return { code: 200 };
}
if (authClient.isTfaSession) {
return {
code: 403,
message: tfaCode ? 'Invalid 2FA code' : '2FA code required',
};
}
return { code: 403, message: 'Invalid email or password' };
} catch (error) {
throw new RequestError('Failed to login to SmartRent', {
message: error.message,
});
}
}
}
(() => new PluginUiServer())();