UNPKG

2.81 kBJavaScriptView Raw
1/*
2 * Copyright 2019 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13const http = require('http');
14const EventEmitter = require('events');
15
16class 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 // just respond with a little hello world.
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 // read body
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 // assume json...
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
110module.exports = LoginServer;