-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoFAModal.vue
More file actions
358 lines (316 loc) · 12.3 KB
/
Copy pathTwoFAModal.vue
File metadata and controls
358 lines (316 loc) · 12.3 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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<template>
<div class="af-two-factors-modal fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 top-0 bottom-0 left-0 right-0"
v-show ="twofaApi.isOpened && (isLoading === false)">
<div v-if="twofaApi.modalMode === 'totp'" class="af-two-factor-modal-totp flex flex-col items-center relative bg-white dark:bg-gray-700 rounded-lg shadow p-6 w-full max-w-md">
<div id="mfaCode-label" class="mb-4 text-gray-700 dark:text-gray-100 text-center">
<p> {{ twofaApi.customDialogTitle }} </p>
<p>{{ $t('Please enter your authenticator code') }}</p>
</div>
<div class="flex flex-col max-w-[calc(15rem_+_60px)]">
<div class="mb-4 w-full flex justify-center" ref="otpRoot">
<v-otp-input
ref="confirmationResult"
container-class="grid grid-cols-6 gap-3 w-full"
input-classes="bg-gray-50 text-center flex justify-center otp-input border leading-none border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-10 h-10 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
:num-inputs="6"
inputType="number"
inputmode="numeric"
:should-auto-focus="true"
:should-focus-order="true"
v-model:value="bindValue"
@on-complete="handleOnComplete"
/>
</div>
<div class="flex items-center w-full" :class="twofaApi.doesUserHavePasskeys ? 'justify-between' : 'justify-center' ">
<p v-if="twofaApi.doesUserHavePasskeys===true" class="underline hover:no-underline text-lightPrimary whitespace-nowrap hover:cursor-pointer" @click="twofaApi.setModalMode('passkey')" >{{$t('use passkey')}}</p>
<Button
class="px-4 py-2 rounded border"
@click="onCancel"
:disabled="inProgress"
>{{ $t('Cancel') }}</Button>
</div>
</div>
</div>
<div v-else-if="twofaApi.modalMode === 'passkey'" class="af-two-factor-modal-passkeys flex flex-col items-center justify-center py-4 gap-6 relative bg-white dark:bg-gray-700 rounded-lg shadow p-6">
<button
type="button"
class="text-lightDialogCloseButton bg-transparent hover:bg-lightDialogCloseButtonHoverBackground hover:text-lightDialogCloseButtonHover rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:text-darkDialogCloseButton dark:hover:bg-darkDialogCloseButtonHoverBackground dark:hover:text-darkDialogCloseButtonHover"
@click="onCancel"
>
<svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>
</svg>
<span class="sr-only">{{$t('Close modal')}}</span>
</button>
<IconShieldOutline class="af-2fa-shield-icon w-16 h-16 text-lightPrimary dark:text-darkPrimary"/>
<p class="text-4xl font-semibold mb-4 text:gray-900 dark:text-gray-200 ">{{$t('Passkey')}}</p>
<div class="mb-2 max-w-[300px] text:gray-900 dark:text-gray-200">
<p class="mb-2">{{twofaApi.customDialogTitle}} </p>
<p>{{$t('Authenticate yourself using the button below')}}</p>
</div>
<Button @click="usePasskeyButtonClick" :disabled="isFetchingPasskey" :loader="isFetchingPasskey" class="w-full mx-16">
{{$t('Use passkey')}}
</Button>
<div v-if="twofaApi.modalMode === 'passkey'" class="af-2fa-passkey-issues-card max-w-sm px-6 pt-3 w-full bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700">
<div class="mb-3 font-normal text-gray-700 dark:text-gray-400">
<p>{{$t('Have issues with passkey?')}}</p>
<p class="underline hover:no-underline text-lightPrimary whitespace-nowrap hover:cursor-pointer" @click="twofaApi.setModalMode('totp')" >{{$t('use TOTP')}}</p>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import VOtpInput from 'vue3-otp-input';
import { ref, nextTick, watch, onMounted } from 'vue';
import { useUserStore } from '@/stores/user';
import { useI18n } from 'vue-i18n';
import { callAdminForthApi } from '@/utils';
import { Link, Button } from '@/afcl';
import { IconShieldOutline } from '@iconify-prerendered/vue-flowbite';
import { getPasskey } from './utils.js'
import adminforth from '@/adminforth';
import { use2faApi } from './use2faApi';
const twofaApi = use2faApi();
declare global {
interface Window {
adminforthTwoFaModal: {
get2FaConfirmationResult: (
title?: string,
verifyingCallback?: (confirmationResult: string) => Promise<boolean>
) => Promise<any>;
};
}
}
const props = defineProps<{
autoFinishLogin?: boolean
}>();
const emit = defineEmits<{
(e: 'resolved', payload: any): void
(e: 'rejected', err?: any): void
(e: 'closed'): void
}>();
onMounted(() => {
twofaApi.registerAddEventListenerForOTPInput(addEventListenerForOTPInput);
});
async function addEventListenerForOTPInput(){
document.addEventListener('focusin', handleGlobalFocusIn, true);
focusFirstAvailableOtpInput();
isLoading.value = false;
await nextTick();
const rootEl = otpRoot.value;
rootEl && rootEl.addEventListener('focusout', handleFocusOut, true);
}
function removeEventListenerForOTPInput() {
window.removeEventListener('paste', handlePaste);
document.removeEventListener('focusin', handleGlobalFocusIn, true);
const rootEl = otpRoot.value;
rootEl && rootEl.removeEventListener('focusout', handleFocusOut, true);
// Abort any in-flight WebAuthn request when leaving the component
}
const modelShow = ref(false);
// let resolveFn: ((confirmationResult: any) => void) | null = null;
// let verifyingCallback: ((confirmationResult: string) => boolean) | null = null;
// let verifyFn: null | ((confirmationResult: string) => Promise<boolean> | boolean) = null;
// let rejectFn: ((err?: any) => void) | null = null;
window.adminforthTwoFaModal = {
get2FaConfirmationResult: (title?: string, verifyingCallback?: (confirmationResult: string) => Promise<boolean>) =>
new Promise(async (resolve, reject) => {
if (twofaApi.isOpened) throw new Error('Modal is already open');
const skipAllowModal = await checkIfSkipAllowModal();
if (skipAllowModal) {
resolve({ code: "123456" }); // dummy code
return;
}
await checkIfUserHasPasskeys();
if (title) {
twofaApi.setCustomDialogTitle(title);
}
twofaApi.setIsOpened(true);
if (twofaApi.modalMode === 'totp') {
await addEventListenerForOTPInput();
}
twofaApi.registerResolveFn(resolve);
twofaApi.registerRejectFn(reject);
twofaApi.registerVerifyFn(verifyingCallback ?? null);
}),
};
const { t } = useI18n();
const user = useUserStore();
const confirmationResult = ref<any>(null);
const otpRoot = ref<HTMLElement | null>(null);
const bindValue = ref('');
const doesUserHavePasskeys = ref(false);
const modalMode = ref<"totp" | "passkey">("totp");
const isLoading = ref(false);
const customDialogTitle = ref("");
async function usePasskeyButtonClick() {
let passkeyData;
try {
passkeyData = await getPasskey();
} catch (error) {
onCancel();
return null;
}
twofaApi.setIsOpened(false);
const dataToReturn = {
mode: "passkey",
result: passkeyData
}
twofaApi.setCustomDialogTitle("");
removeEventListenerForOTPInput();
twofaApi.resolveFn?.(dataToReturn);
}
function tagOtpInputs() {
const root = otpRoot.value;
if (!root) return;
const inputs = root.querySelectorAll('input.otp-input');
inputs.forEach((el, idx) => {
el.setAttribute('name', 'mfaCode');
el.setAttribute('id', `mfaCode-${idx + 1}`);
el.setAttribute('autocomplete', 'one-time-code');
el.setAttribute('inputmode', 'numeric');
el.setAttribute('aria-labelledby', 'mfaCode-label');
});
(inputs[0] as HTMLInputElement)?.focus();
}
function handlePaste(event: ClipboardEvent) {
event.preventDefault();
const pastedText = event.clipboardData?.getData('text') || '';
if (pastedText.length === 6) {
confirmationResult.value?.fillInput(pastedText);
}
}
async function handleOnComplete(value: string) {
await sendConfirmationResult(value);
}
async function sendConfirmationResult(value: string) {
if (!twofaApi.resolveFn) throw new Error('Modal is not initialized properly');
if (twofaApi.verifyFn) {
try {
const ok = await twofaApi.verifyFn(value);
if (!ok) {
twofaApi.rejectFn?.(new Error('Invalid code'));
return;
}
} catch (err) {
twofaApi.rejectFn?.(err);
return;
}
}
twofaApi.setIsOpened(false);
const dataToReturn = {
mode: "totp",
result: value
}
twofaApi.setCustomDialogTitle("");
removeEventListenerForOTPInput();
twofaApi.resolveFn?.(dataToReturn);
}
function onCancel() {
twofaApi.setIsOpened(false);
bindValue.value = '';
confirmationResult.value?.clearInput();
removeEventListenerForOTPInput();
twofaApi.rejectFn?.(new Error('Cancel'));
emit('rejected', new Error('cancelled'));
emit('closed');
}
watch(() => twofaApi.modalMode, async (newMode) => {
if (newMode === 'totp') {
await addEventListenerForOTPInput();
} else {
removeEventListenerForOTPInput();
}
});
watch(() => twofaApi.isOpened, async (open) => {
if (open) {
await nextTick();
const htmlRef = document.querySelector('html');
if (htmlRef) {
htmlRef.style.overflow = 'hidden';
}
// Wait for conditional rendering to complete
if (twofaApi.modalMode === 'totp' && !isLoading.value) {
await nextTick();
setTimeout(() => {
tagOtpInputs();
window.addEventListener('paste', handlePaste);
}, 100);
} else {
window.addEventListener('paste', handlePaste);
}
} else {
window.removeEventListener('paste', handlePaste);
const htmlRef = document.querySelector('html');
if (htmlRef) {
htmlRef.style.overflow = '';
}
bindValue.value = '';
confirmationResult.value?.clearInput();
}
});
async function checkIfUserHasPasskeys() {
isLoading.value = true;
await twofaApi.checkIfUserHasPasskeys();
isLoading.value = false;
}
function getOtpInputs() {
const root = otpRoot.value;
if (!root) return [];
return Array.from(root.querySelectorAll('input.otp-input'));
}
function focusFirstAvailableOtpInput() {
const inputs = getOtpInputs();
if (!inputs.length) {
// Retry after a short delay if inputs aren't ready yet
setTimeout(() => focusFirstAvailableOtpInput(), 50);
return;
}
const firstEmpty = inputs.find((i) => !(i as HTMLInputElement).value);
((firstEmpty || inputs[0]) as HTMLInputElement).focus();
}
function handleGlobalFocusIn(event) {
const inputs = getOtpInputs();
if (!inputs.length) return;
const target = event.target;
if (!target) return;
if (!inputs.includes(target)) {
requestAnimationFrame(() => {
focusFirstAvailableOtpInput();
});
}
}
function handleFocusOut() {
requestAnimationFrame(() => {
const inputs = getOtpInputs();
if (!inputs.length) return;
const active = document.activeElement;
if (!active || !inputs.includes(active)) {
focusFirstAvailableOtpInput();
}
});
}
async function checkIfSkipAllowModal(){
try {
const response = await callAdminForthApi({
method: "GET",
path: "/plugin/twofa/skip-allow-modal",
});
if ( response.skipAllowed === true ) {
return true;
} else {
return false;
}
} catch (error) {
console.error('Error checking skip allow modal:', error);
return false;
}
}
</script>
<style scoped>
:deep(.otp-input-container) {
display: flex;
gap: 0.75rem;
}
</style>