[api] Implement page.authenticate method (#729)

This patch implements `page.authenticate` which should cover all
cases of HTTP authentication.

Fixes #426.
This commit is contained in:
Andrey Lushnikov
2017-09-11 16:32:13 -07:00
committed by GitHub
parent 0bea42bd8c
commit 0db6165d73
5 changed files with 134 additions and 12 deletions

View File

@@ -73,6 +73,8 @@ class SimpleServer {
/** @type {!Map<string, function(!IncomingMessage, !ServerResponse)>} */
this._routes = new Map();
/** @type {!Map<string, !{username:string, password:string}>} */
this._auths = new Map();
/** @type {!Map<string, !Promise>} */
this._requestSubscribers = new Map();
}
@@ -88,6 +90,15 @@ class SimpleServer {
socket.once('close', () => this._sockets.delete(socket));
}
/**
* @param {string} path
* @param {string} username
* @param {string} password
*/
setAuth(path, username, password) {
this._auths.set(path, {username, password});
}
async stop() {
this.reset();
for (const socket of this._sockets)
@@ -136,6 +147,7 @@ class SimpleServer {
reset() {
this._routes.clear();
this._auths.clear();
const error = new Error('Static Server has been reset');
for (const subscriber of this._requestSubscribers.values())
subscriber[rejectSymbol].call(null, error);
@@ -150,6 +162,15 @@ class SimpleServer {
throw error;
});
const pathName = url.parse(request.url).path;
if (this._auths.has(pathName)) {
const auth = this._auths.get(pathName);
const credentials = new Buffer((request.headers.authorization || '').split(' ')[1] || '', 'base64').toString();
if (credentials !== `${auth.username}:${auth.password}`) {
response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Secure Area"' });
response.end('HTTP Error 401 Unauthorized: Access is denied');
return;
}
}
// Notify request subscriber.
if (this._requestSubscribers.has(pathName))
this._requestSubscribers.get(pathName)[fulfillSymbol].call(null, request);