2018-01-10 05:05:46 +01:00
|
|
|
import {
|
|
|
|
CipherService,
|
|
|
|
PlatformUtilsService,
|
|
|
|
} from 'jslib/abstractions';
|
2018-01-05 22:30:15 +01:00
|
|
|
|
2017-12-07 03:54:38 +01:00
|
|
|
export default class WebRequestBackground {
|
|
|
|
private pendingAuthRequests: any[] = [];
|
|
|
|
private webRequest: any;
|
|
|
|
private isFirefox: boolean;
|
|
|
|
|
2018-01-09 20:26:20 +01:00
|
|
|
constructor(private platformUtilsService: PlatformUtilsService,
|
2018-01-07 04:13:48 +01:00
|
|
|
private cipherService: CipherService) {
|
2017-12-07 03:54:38 +01:00
|
|
|
this.webRequest = (window as any).chrome.webRequest;
|
2018-01-05 22:30:15 +01:00
|
|
|
this.isFirefox = platformUtilsService.isFirefox();
|
2017-12-07 03:54:38 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async init() {
|
|
|
|
if (!this.webRequest || !this.webRequest.onAuthRequired) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.webRequest.onAuthRequired.addListener(async (details: any, callback: any) => {
|
|
|
|
if (!details.url || this.pendingAuthRequests.indexOf(details.requestId) !== -1) {
|
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-01-05 22:30:15 +01:00
|
|
|
const domain = this.platformUtilsService.getDomain(details.url);
|
2017-12-07 03:54:38 +01:00
|
|
|
if (domain == null) {
|
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.pendingAuthRequests.push(details.requestId);
|
|
|
|
|
|
|
|
if (this.isFirefox) {
|
|
|
|
return new Promise(async (resolve, reject) => {
|
|
|
|
await this.resolveAuthCredentials(domain, resolve, reject);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
await this.resolveAuthCredentials(domain, callback, callback);
|
|
|
|
}
|
|
|
|
}, { urls: ['http://*/*', 'https://*/*'] }, [this.isFirefox ? 'blocking' : 'asyncBlocking']);
|
|
|
|
|
|
|
|
this.webRequest.onCompleted.addListener(
|
|
|
|
(details: any) => this.completeAuthRequest(details), { urls: ['http://*/*'] });
|
|
|
|
this.webRequest.onErrorOccurred.addListener(
|
|
|
|
(details: any) => this.completeAuthRequest(details), { urls: ['http://*/*'] });
|
|
|
|
}
|
|
|
|
|
|
|
|
private async resolveAuthCredentials(domain: string, success: Function, error: Function) {
|
|
|
|
try {
|
|
|
|
const ciphers = await this.cipherService.getAllDecryptedForDomain(domain);
|
|
|
|
if (ciphers == null || ciphers.length !== 1) {
|
|
|
|
error();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
success({
|
|
|
|
authCredentials: {
|
|
|
|
username: ciphers[0].login.username,
|
|
|
|
password: ciphers[0].login.password,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
} catch {
|
|
|
|
error();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private completeAuthRequest(details: any) {
|
|
|
|
const i = this.pendingAuthRequests.indexOf(details.requestId);
|
|
|
|
if (i > -1) {
|
|
|
|
this.pendingAuthRequests.splice(i, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|