1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const http = require('http');
|
14 | const EventEmitter = require('events');
|
15 |
|
16 | class LoginServer extends EventEmitter {
|
17 | constructor() {
|
18 | super();
|
19 | this._log = null;
|
20 | this._srv = null;
|
21 | this._token = null;
|
22 | this._isClosing = null;
|
23 | this._origin = null;
|
24 | }
|
25 |
|
26 | withLogger(value) {
|
27 | this._log = value;
|
28 | return this;
|
29 | }
|
30 |
|
31 | withOrigin(value) {
|
32 | this._origin = value;
|
33 | return this;
|
34 | }
|
35 |
|
36 | get log() {
|
37 | return this._log;
|
38 | }
|
39 |
|
40 | async waitForToken() {
|
41 | if (this._token) {
|
42 | return this._token;
|
43 | }
|
44 | return new Promise((resolve) => {
|
45 | this.on('token', resolve);
|
46 | });
|
47 | }
|
48 |
|
49 | get port() {
|
50 | return this._srv ? this._srv.address().port : 0;
|
51 | }
|
52 |
|
53 | async stop() {
|
54 | if (this._srv) {
|
55 | return new Promise((resolve) => {
|
56 | this._srv.close(resolve);
|
57 | this._srv = null;
|
58 | });
|
59 | }
|
60 | return Promise.resolve();
|
61 | }
|
62 |
|
63 | async start() {
|
64 | return new Promise((resolve, reject) => {
|
65 | this._srv = http.createServer((req, res) => {
|
66 | this.log.debug(req.headers);
|
67 | this.log.debug(req.method);
|
68 |
|
69 | if (req.method === 'GET') {
|
70 |
|
71 | res.end('Hello, world.');
|
72 | return;
|
73 | }
|
74 | if (req.method === 'OPTIONS') {
|
75 | res.writeHead(200, {
|
76 | 'Access-Control-Allow-Origin': this._origin,
|
77 | 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
|
78 | 'Access-Control-Allow-Headers': 'Content-Type',
|
79 | });
|
80 | res.end();
|
81 | return;
|
82 | }
|
83 |
|
84 |
|
85 | let body = '';
|
86 | req.on('data', (chunk) => {
|
87 | body += chunk.toString();
|
88 | });
|
89 | req.on('end', () => {
|
90 | res.end();
|
91 | this.log.debug('got body', body);
|
92 |
|
93 | const data = JSON.parse(body);
|
94 | if (data.token) {
|
95 | this.emit('token', data.token);
|
96 | }
|
97 | });
|
98 | req.on('error', reject);
|
99 | }).listen({
|
100 | port: 0,
|
101 | host: '127.0.0.1',
|
102 | }, () => {
|
103 | this.log.debug(`server started on ${JSON.stringify(this._srv.address())}`);
|
104 | resolve();
|
105 | });
|
106 | });
|
107 | }
|
108 | }
|
109 |
|
110 | module.exports = LoginServer;
|