(url, options = {})
| 152 | */ |
| 153 | |
| 154 | export async function fetchWithCsrf(url, options = {}) { |
| 155 | const original = window.fetch.bind(window); |
| 156 | const wantJson = (options.headers && /json/i.test(options.headers['Content-Type'] || '')) || typeof options.body === 'string' && options.body.trim().startsWith('{'); |
| 157 | |
| 158 | options = { credentials: 'include', ...options }; |
| 159 | options.headers = { |
| 160 | 'Accept': 'application/json', |
| 161 | ...(options.headers || {}) |
| 162 | }; |
| 163 | if (window.csrfToken) { |
| 164 | options.headers['X-CSRF-Token'] = window.csrfToken; |
| 165 | } |
| 166 | |
| 167 | async function retryWithFreshCsrf(asFormFallback = false) { |
| 168 | const tokRes = await original('/api/auth/token.php', { credentials: 'include' }); |
| 169 | if (tokRes.ok) { |
| 170 | const body = await tokRes.json().catch(() => ({})); |
| 171 | if (body?.csrf_token) { |
| 172 | window.csrfToken = body.csrf_token; |
| 173 | const meta = document.querySelector('meta[name="csrf-token"]'); |
| 174 | if (meta) meta.content = body.csrf_token; |
| 175 | options.headers['X-CSRF-Token'] = body.csrf_token; |
| 176 | } |
| 177 | } |
| 178 | if (asFormFallback && wantJson) { |
| 179 | // convert JSON body into x-www-form-urlencoded |
| 180 | const orig = options.body && typeof options.body === 'string' ? JSON.parse(options.body) : {}; |
| 181 | options.body = toFormBody(orig); |
| 182 | options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; |
| 183 | } |
| 184 | return original(url, options); |
| 185 | } |
| 186 | |
| 187 | let res = await original(url, options); |
| 188 | |
| 189 | // If API doesn’t like JSON or token is stale |
| 190 | if (res.status === 400 || res.status === 403 || res.status === 415) { |
| 191 | // 1) retry with fresh CSRF keeping same encoding |
| 192 | res = await retryWithFreshCsrf(false); |
| 193 | if (!res.ok && wantJson) { |
| 194 | // 2) retry again as form-encoded |
| 195 | res = await retryWithFreshCsrf(true); |
| 196 | } |
| 197 | } |
| 198 | return res; |
| 199 | } |
| 200 | |
| 201 | // wrap the TOTP modal opener to disable other login buttons only for Basic/OIDC flows |
| 202 | function openTOTPLoginModal() { |
no test coverage detected