From b9696a65e0c419abc2268d0aff15f4cf6d28e7db Mon Sep 17 00:00:00 2001 From: Louis Chemineau Date: Wed, 6 Nov 2024 13:42:01 +0100 Subject: [PATCH] WIP: rewrite to withPasswordConfirmation Signed-off-by: Louis Chemineau --- src/main.ts | 58 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/src/main.ts b/src/main.ts index ec27531..13373ef 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,12 +3,14 @@ * SPDX-License-Identifier: MIT */ import Vue from 'vue' +import type { ComponentInstance } from 'vue' + +import { Axios } from '@nextcloud/axios' +import { getCurrentUser } from '@nextcloud/auth' import PasswordDialogVue from './components/PasswordDialog.vue' import { DIALOG_ID, MODAL_CLASS } from './globals' -import type { ComponentInstance } from 'vue' - const PAGE_LOAD_TIME = Date.now() /** @@ -42,18 +44,6 @@ export const confirmPassword = (): Promise => { return getPasswordDialog() } -/** - * Ask the password to the user for later use. - * - * @param callback - * @return {Promise} Promise that resolves when password is submitted. - * Rejects if password confirmation was cancelled - * or confirmation is already in process. - */ -export const promptForPassword = (callback: (password: string) => Promise) => { - return getPasswordDialog(callback) -} - /** * * @param mode @@ -97,3 +87,43 @@ function getPasswordDialog(callback?: (password: string) => Promise): Promi }) }) } + +/** + * Add interceptors to an axios instance that for every request + * will prompt for password confirmation and add it as Basic Auth. + * @param axios + */ +export function withPasswordConfirmation(axios: Axios): Axios { + const { + promise: passwordDialogCallbackResolution, + resolve: resolvePwdDialogCallback, + reject: rejectPwdDialogCallback, + } = Promise.withResolvers() + + axios.interceptors.request.use(async (config) => { + return new Promise((resolve, reject) => { + getPasswordDialog((password: string) => { + resolve({ + ...config, + auth: { + username: getCurrentUser()?.uid ?? '', + password, + }, + }) + + // Await for request to be done + return passwordDialogCallbackResolution + }) + }) + }) + + axios.interceptors.response.use((response) => { + if (response.request.auth !== undefined) { + resolvePwdDialogCallback(undefined) + } + + return response + }) + + return axios +}