forked from NHAS/webauthn-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
183 lines (170 loc) · 6.17 KB
/
index.js
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM content loaded, getting started");
// check whether current browser supports WebAuthn
document.getElementById("js_loading").style.display = "none";
if (!window.PublicKeyCredential) {
document.getElementById("no_webauthn").style.display = "block";
}
let p1 = new Promise((resolve, reject) => {
if (!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable) {
document.getElementById("no_platform_auth_api").style.display = "block";
reject("IsUserVerifyingPlatformAuthenticatorAvailable is not available");
} else {
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable().then((available) => {
console.log("isUserVerifyingPlatformAuthenticatorAvailable:", available);
if (!available) {
document.getElementById("no_platform_auth").style.display = "block";
}
resolve(available);
});
}
});
let p2 = new Promise((resolve, reject) => {
if (!PublicKeyCredential.isConditionalMediationAvailable) {
document.getElementById("no_conditional_mediation_api").style.display = "block";
reject("IsConditionalMediationAvailable is not available");
} else {
PublicKeyCredential.isConditionalMediationAvailable().then((available) => {
console.log("isConditionalMediationAvailable:", available);
if (!available) {
document.getElementById("no_conditional_mediation").style.display = "block";
}
resolve(available);
});
}
});
const login_form = document.getElementById("login");
login_form.addEventListener("submit", loginUser, true);
const register_form = document.getElementById("register");
register_form.addEventListener("submit", registerUser, true);
Promise.all([p1, p2]).then((values) => {
if(values[0] && values[1]) {
login_form.style.display = "block";
}
})
});
// Base64 to ArrayBuffer
function bufferDecode(value) {
return Uint8Array.from(atob(value), c => c.charCodeAt(0));
}
// ArrayBuffer to URLBase64
function bufferEncode(value) {
return btoa(String.fromCharCode.apply(null, new Uint8Array(value)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");;
}
async function registerUser(e) {
e.preventDefault();
const username = getRegisterUsername();
const response = await fetch('/register/begin/' + username);
if (!response.ok) {
throw new Error(`HTTP error on begin register: ${response.status}`);
}
const json = await response.json();
var credentialCreationOptions = json;
console.log(credentialCreationOptions);
credentialCreationOptions.publicKey.challenge = bufferDecode(credentialCreationOptions.publicKey.challenge);
credentialCreationOptions.publicKey.user.id = bufferDecode(credentialCreationOptions.publicKey.user.id);
if (credentialCreationOptions.publicKey.excludeCredentials) {
for (var i = 0; i < credentialCreationOptions.publicKey.excludeCredentials.length; i++) {
credentialCreationOptions.publicKey.excludeCredentials[i].id = bufferDecode(credentialCreationOptions.publicKey.excludeCredentials[i].id);
}
}
const credential = await navigator.credentials.create({
publicKey: credentialCreationOptions.publicKey
});
console.log("Credential", credential);
let attestationObject = credential.response.attestationObject;
let clientDataJSON = credential.response.clientDataJSON;
let rawId = credential.rawId;
const response2 = await fetch( '/register/finish/' + username, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: credential.id,
rawId: bufferEncode(rawId),
type: credential.type,
response: {
attestationObject: bufferEncode(attestationObject),
clientDataJSON: bufferEncode(clientDataJSON),
},
})
});
if (!response.ok) {
console.log(error)
alert("failed to register " + username);
return;
}
window.location.href = response2.headers.get("Location");
}
function getLoginUsername() {
var username_element = document.querySelector("#login input[name='username']");
return username_element.value;
}
function getRegisterUsername() {
var username_element = document.querySelector("#register input[name='username']");
return username_element.value;
}
async function loginUser(e) {
e.preventDefault();
const username = getLoginUsername();
if (username === "") {
alert("Please enter a username");
return;
}
const response = await fetch('/login/begin/' + username);
// 404 signals that the user doesn't exist
if (response.status == 404) {
showRegisterForm();
return;
} else if (!response.ok) {
throw new Error(`HTTP error on begin register: ${response.status}`);
}
const json = await response.json();
console.log("Login begin:", json);
const credentialRequestOptions = json;
credentialRequestOptions.publicKey.challenge = bufferDecode(credentialRequestOptions.publicKey.challenge);
credentialRequestOptions.publicKey.allowCredentials.forEach(function (listItem) {
listItem.id = bufferDecode(listItem.id)
});
var assertion = await navigator.credentials.get({
publicKey: credentialRequestOptions.publicKey
});
console.log("Assertion", assertion);
let authData = assertion.response.authenticatorData;
let clientDataJSON = assertion.response.clientDataJSON;
let rawId = assertion.rawId;
let sig = assertion.response.signature;
let userHandle = assertion.response.userHandle;
const response2 = await fetch( '/login/finish/' + username, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: assertion.id,
rawId: bufferEncode(rawId),
type: assertion.type,
response: {
authenticatorData: bufferEncode(authData),
clientDataJSON: bufferEncode(clientDataJSON),
signature: bufferEncode(sig),
userHandle: bufferEncode(userHandle),
},
})
});
const json2 = await response2.json();
console.log("Login finish", json2);
window.location.href = response2.headers.get("Location");
}
function showRegisterForm() {
console.log("Showing registration form");
document.getElementById("login").style.display = "none";
document.getElementById("register").style.display = "block";
const login_username = getLoginUsername();
const register_username = document.querySelector("#register input[name='username']");
register_username.value = login_username;
}