230 lines
8.1 KiB
TypeScript

import { Global } from "../../Core/Globals"
import { EventManager } from "../../Core/Events"
import { Ui } from "../../Core/Ui"
import * as Events from "../../Core/EventDefinitions"
import { LocalizationManager } from "../../Core/Localization"
import * as Utility from "../../Core/Utility";
import { FormValidation } from "../../Core/Forms"
import * as Models from "../../Common/Models";
class FidoCreatePlatformModule {
private _moduleName = "FidoCreatePlatformModule";
private _component = "#fidoCreateContainer";
private _global: Global;
private _eventManager: EventManager;
private _uiManager: Ui;
private _localizationMananger: LocalizationManager;
constructor() {
this._global = Global.getInstance();
this._eventManager = EventManager.getInstance();
this._uiManager = Ui.getInstance();
this._localizationMananger = LocalizationManager.getInstance();
}
/**
* Stellt einen Prefix vor einen Selektor
* @param selector
*/
private prefix(selector: string): string {
const self = this;
if ($(`${self._component} ${selector}`).length > 0)
return `${self._component} ${selector}`;
return `html ${selector}`;
}
/**
* Speichern
*/
private save(): void {
var self = this;
self._uiManager.blockMainUi();
var action = <string>$(self.prefix("#jsMakeCredentialOptionsUrl")).val();
var data = $(self.prefix("#frmCreateFido")).serialize();
$.post(action, data)
.done(result => {
self.handleCredentialOptionsResult(result);
})
.fail(result => {
self._uiManager.showErrorMessage(self._localizationMananger.get("Common_Save_NoSuccess"));
})
.always(result => {
self._uiManager.unblockMainUi();
});
}
/**
* Überprüfen des Ergebnis des MakeCredentialOptions Request
* Wenn alles ok, dann Registrierung starten
* @param result
*/
private async handleCredentialOptionsResult(result: any) {
var self = this;
let makeCredentialOptions = <any>result;
if (makeCredentialOptions.status !== "ok") {
console.log("Error creating credential options");
console.log(makeCredentialOptions.errorMessage);
self._uiManager.showErrorMessage(makeCredentialOptions.errorMessage);
self._uiManager.pageTitleClear(self._component);
self._eventManager.unSubscribeAll(self._moduleName);
self._eventManager.publish(Events.Fido.createPlatformCancel);
return;
}
// Turn the challenge back into the accepted format of padded base64
makeCredentialOptions.challenge = Utility.coerceToArrayBuffer(makeCredentialOptions.challenge);
// Turn ID into a UInt8Array Buffer for some reason
makeCredentialOptions.user.id = Utility.coerceToArrayBuffer(makeCredentialOptions.user.id);
makeCredentialOptions.excludeCredentials = makeCredentialOptions.excludeCredentials.map((c) => {
c.id = Utility.coerceToArrayBuffer(c.id);
return c;
});
if (makeCredentialOptions.authenticatorSelection.authenticatorAttachment === null)
makeCredentialOptions.authenticatorSelection.authenticatorAttachment = undefined;
let newCredential;
try {
newCredential = await navigator.credentials.create({
publicKey: makeCredentialOptions
});
} catch (e) {
var msg = self._localizationMananger.get("Err_Fido_Exists");
console.error(msg, e);
self._uiManager.showErrorMessage(msg);
//Abbrechen
self._uiManager.pageTitleClear(self._component);
self._eventManager.unSubscribeAll(self._moduleName);
self._eventManager.publish(Events.Fido.createPlatformCancel);
}
try {
self.registerNewCredential(newCredential);
} catch (ex) {
self._uiManager.showErrorMessage(ex.message ? ex.message : ex);
self._uiManager.pageTitleClear(self._component);
self._eventManager.unSubscribeAll(self._moduleName);
self._eventManager.publish(Events.Fido.createPlatformCancel);
}
}
/**
* Credentials registrieren, wenn möglich
* @param newCredential
*/
private async registerNewCredential(newCredential: any) {
var self = this;
// Move data into Arrays incase it is super long
let attestationObject = new Uint8Array(newCredential.response.attestationObject);
let clientDataJSON = new Uint8Array(newCredential.response.clientDataJSON);
let rawId = new Uint8Array(newCredential.rawId);
const data = {
id: newCredential.id,
rawId: Utility.coerceToBase64Url(rawId),
type: newCredential.type,
extensions: newCredential.getClientExtensionResults(),
response: {
AttestationObject: Utility.coerceToBase64Url(attestationObject),
clientDataJson: Utility.coerceToBase64Url(clientDataJSON)
}
};
let response;
try {
response = await self.registerCredentialWithServer(data);
} catch (e) {
self._uiManager.showErrorMessage(e);
}
// show error
if (response.status !== "ok") {
console.log("Error creating credential");
console.log(response.errorMessage);
self._uiManager.showErrorMessage(response.errorMessage);
self._uiManager.pageTitleClear(self._component);
self._eventManager.unSubscribeAll(self._moduleName);
self._eventManager.publish(Events.Fido.createPlatformCancel);
return;
}
self._uiManager.showSuccessMessage(self._localizationMananger.get("Fido_Create_Success"));
self._uiManager.pageTitleClear(self._component);
self._eventManager.unSubscribeAll(self._moduleName);
self._eventManager.publish(Events.Fido.createPlatformSuccess);
}
/**
* Senden der Registrierungs-Infos an Server
* @param formData
*/
private async registerCredentialWithServer(formData: any) {
var self = this;
let response = await fetch(<string>$(self.prefix("#jsMakeCredentialUrl")).val(), {
method: "POST", // or 'PUT'
body: JSON.stringify(formData), // data can be `string` or {object}!
headers: {
'Accept': "application/json",
'Content-Type': "application/json",
'RequestVerificationToken': $(self.prefix("input[name='__RequestVerificationToken']")).val().toString()
}
});
let data = await response.json();
return data;
}
/**
* Bindungen erstellen
*/
private setupBindings(): void {
var self = this;
$(self.prefix("#btnCreate")).off("click").on("click", function () {
FormValidation.getInstance().validateForm(self.prefix("#frmCreateFido"), () => {
self.save();
}, () => {
$.highlightErrors();
});
});
$(self.prefix("#btnCancel")).off("click").on("click", function () {
self._uiManager.pageTitleClear(self._component);
self._eventManager.unSubscribeAll(self._moduleName);
self._eventManager.publish(Events.Fido.createPlatformCancel);
});
$('[data-toggle="tooltip"]').tooltip();
}
/**
* Aktivieren des Moduls
*/
public activate(): void {
var self = this;
$.setupValidator();
$.reinitializeValidator();
this.setupBindings();
self._uiManager.pageTitleAdd(self._component, self.prefix("#pageTitleAdd"));
$.randomAutocompleteValue();
}
/**
* Initialisieren des Moduls
*/
public init(): void {
if (this._global.appInitialized) {
fidoCreatePlatformModule.activate();
} else {
setTimeout(() => { this.init() }, 10);
}
}
}
let fidoCreatePlatformModule = new FidoCreatePlatformModule();
fidoCreatePlatformModule.init();