blob: 8ecf0b3de7e0272a241897f7be06f54207367355 (
plain)
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
|
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { emit } from '@nextcloud/event-bus'
import { generateUrl } from '@nextcloud/router'
/**
* Get the current CSRF token.
*/
export function getRequestToken(): string {
return document.head.dataset.requesttoken!
}
/**
* Set a new CSRF token (e.g. because of session refresh).
* This also emits an event bus event for the updated token.
*
* @param token - The new token
* @fires Error - If the passed token is not a potential valid token
*/
export function setRequestToken(token: string): void {
if (!token || typeof token !== 'string') {
throw new Error('Invalid CSRF token given', { cause: { token } })
}
document.head.dataset.requesttoken = token
emit('csrf-token-update', { token })
}
/**
* Fetch the request token from the API.
* This does also set it on the current context, see `setRequestToken`.
*
* @fires Error - If the request failed
*/
export async function fetchRequestToken(): Promise<string> {
const url = generateUrl('/csrftoken')
const response = await fetch(url)
if (!response.ok) {
throw new Error('Could not fetch CSRF token from API', { cause: response })
}
const { token } = await response.json()
setRequestToken(token)
return token
}
|