1919 * along with this program. If not, see <http://www.gnu.org/licenses/>.
2020 *
2121 */
22- import type { RequestOptions , Response } from 'webdav'
2322
2423import { createClient , getPatcher } from 'webdav'
2524import { generateRemoteUrl } from '@nextcloud/router'
26- import { getCurrentUser , getRequestToken } from '@nextcloud/auth'
27- import { request } from 'webdav/dist/node/request.js'
25+ import { getCurrentUser , getRequestToken , onRequestTokenUpdate } from '@nextcloud/auth'
2826
2927export const rootPath = `/files/${ getCurrentUser ( ) ?. uid } `
3028export const defaultRootUrl = generateRemoteUrl ( 'dav' + rootPath )
3129
3230export const getClient = ( rootUrl = defaultRootUrl ) => {
33- const client = createClient ( rootUrl , {
34- headers : {
35- requesttoken : getRequestToken ( ) || '' ,
36- } ,
37- } )
31+ const client = createClient ( rootUrl )
32+
33+ // set CSRF token header
34+ const setHeaders = ( token : string | null ) => {
35+ client ?. setHeaders ( {
36+ // Add this so the server knows it is an request from the browser
37+ 'X-Requested-With' : 'XMLHttpRequest' ,
38+ // Inject user auth
39+ requesttoken : token ?? '' ,
40+ } ) ;
41+ }
42+
43+ // refresh headers when request token changes
44+ onRequestTokenUpdate ( setHeaders )
45+ setHeaders ( getRequestToken ( ) )
3846
3947 /**
4048 * Allow to override the METHOD to support dav REPORT
@@ -45,12 +53,14 @@ export const getClient = (rootUrl = defaultRootUrl) => {
4553 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
4654 // @ts -ignore
4755 // https://github.com/perry-mitchell/hot-patcher/issues/6
48- patcher . patch ( 'request' , ( options : RequestOptions ) : Promise < Response > => {
49- if ( options . headers ?. method ) {
50- options . method = options . headers . method
51- delete options . headers . method
56+ patcher . patch ( 'fetch' , ( url : string , options : RequestInit ) : Promise < Response > => {
57+ const headers = options . headers as Record < string , string >
58+ if ( headers ?. method ) {
59+ options . method = headers . method
60+ delete headers . method
5261 }
53- return request ( options )
62+ return fetch ( url , options )
5463 } )
55- return client
64+
65+ return client ;
5666}
0 commit comments