-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathnode_request_handler.ts
More file actions
153 lines (133 loc) · 5.79 KB
/
node_request_handler.ts
File metadata and controls
153 lines (133 loc) · 5.79 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as EventEmitter from 'events';
import * as Http from 'http';
import * as Url from 'url';
import {AppAuthError} from '../errors';
import {AuthorizationRequest} from '../authorization_request';
import {AuthorizationRequestHandler, AuthorizationRequestResponse} from '../authorization_request_handler';
import {AuthorizationError, AuthorizationResponse} from '../authorization_response';
import {AuthorizationServiceConfiguration} from '../authorization_service_configuration';
import {Crypto} from '../crypto_utils';
import {log} from '../logger';
import {BasicQueryStringUtils, QueryStringUtils} from '../query_string_utils';
import {NodeCrypto} from './crypto_utils';
// TypeScript typings for `opener` are not correct and do not export it as module
import opener = require('opener');
class ServerEventsEmitter extends EventEmitter {
static ON_START = 'start';
static ON_UNABLE_TO_START = 'unable_to_start';
static ON_AUTHORIZATION_RESPONSE = 'authorization_response';
}
export class NodeBasedHandler extends AuthorizationRequestHandler {
// the handle to the current authorization request
authorizationPromise: Promise<AuthorizationRequestResponse|null>|null = null;
constructor(
// default to port 8000
public httpServerPort = 8000,
utils: QueryStringUtils = new BasicQueryStringUtils(),
crypto: Crypto = new NodeCrypto()) {
super(utils, crypto);
}
performAuthorizationRequest(
configuration: AuthorizationServiceConfiguration,
request: AuthorizationRequest) {
// use opener to launch a web browser and start the authorization flow.
// start a web server to handle the authorization response.
const emitter = new ServerEventsEmitter();
const requestHandler = (httpRequest: Http.IncomingMessage, response: Http.ServerResponse) => {
if (!httpRequest.url) {
return;
}
const url = Url.parse(httpRequest.url);
const searchParams = new Url.URLSearchParams(url.query || '');
const state = searchParams.get('state') || undefined;
const code = searchParams.get('code');
const error = searchParams.get('error');
if (!state && !code && !error) {
// ignore irrelevant requests (e.g. favicon.ico)
return;
}
log('Handling Authorization Request ', searchParams, state, code, error);
let authorizationResponse: AuthorizationResponse|null = null;
let authorizationError: AuthorizationError|null = null;
if (error) {
log('error');
// get additional optional info.
const errorUri = searchParams.get('error_uri') || undefined;
const errorDescription = searchParams.get('error_description') || undefined;
authorizationError = new AuthorizationError(
{error: error, error_description: errorDescription, error_uri: errorUri, state: state});
} else {
authorizationResponse = new AuthorizationResponse({code: code!, state: state!});
}
const completeResponse = {
request,
response: authorizationResponse,
error: authorizationError
} as AuthorizationRequestResponse;
emitter.emit(ServerEventsEmitter.ON_AUTHORIZATION_RESPONSE, completeResponse);
response.end('Close your browser to continue');
};
this.authorizationPromise = new Promise<AuthorizationRequestResponse|null>((resolve, reject) => {
emitter.once(ServerEventsEmitter.ON_UNABLE_TO_START, (error) => reject(error));
emitter.once(ServerEventsEmitter.ON_AUTHORIZATION_RESPONSE, (result: any) => {
server.close();
// resolve pending promise
resolve(result as AuthorizationRequestResponse);
// complete authorization flow
this.completeAuthorizationRequestIfPossible()
.catch(error => {
log('Could not complete authorization request', error);
});
});
});
this.authorizationPromise.catch(error => {
log('Something bad happened ', error);
});
let server: Http.Server;
request.setupCodeVerifier()
.then(() => {
server = Http.createServer(requestHandler);
server.listen(this.httpServerPort, '127.0.0.1', () => {
const url = this.buildRequestUrl(configuration, request);
log('Making a request to ', request, url);
opener(url);
emitter.emit(ServerEventsEmitter.ON_START);
});
server.on('error', (error: Error) => {
emitter.emit(ServerEventsEmitter.ON_UNABLE_TO_START, error);
});
})
.catch((error) => {
emitter.emit(ServerEventsEmitter.ON_UNABLE_TO_START, error);
});
return new Promise<void>((resolve, reject) => {
emitter.once(ServerEventsEmitter.ON_UNABLE_TO_START, (error) => {
reject(new AppAuthError(
`Unable to create HTTP server at port ${this.httpServerPort}`,
{origError: error}
));
});
emitter.once(ServerEventsEmitter.ON_START, () => resolve());
});
}
protected completeAuthorizationRequest(): Promise<AuthorizationRequestResponse|null> {
if (!this.authorizationPromise) {
return Promise.reject(
'No pending authorization request. Call performAuthorizationRequest() ?');
}
return this.authorizationPromise;
}
}