| | |
| | | } |
| | | |
| | | /** |
| | | * Refresh nonce if authentication fails |
| | | */ |
| | | async refreshNonce(action = 'wp_rest') { |
| | | try { |
| | | await this.fetchAuth(); |
| | | return this.getNonce(action); |
| | | } catch (error) { |
| | | console.error('Failed to refresh nonce:', error); |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Fetch with automatic nonce refresh on auth failure |
| | | * Use this for all authenticated API requests |
| | | */ |
| | | async fetch(url, options = {}) { |
| | | const attempt = async (retryCount = 0) => { |
| | | const headers = { |
| | | 'Content-Type': 'application/json', |
| | | ...options.headers, |
| | | 'X-WP-Nonce': this.getNonce() |
| | | }; |
| | | |
| | | const response = await fetch(url, { |
| | | ...options, |
| | | credentials: 'same-origin', |
| | | headers |
| | | }); |
| | | |
| | | // If auth failed and we haven't retried yet, refresh and try once more |
| | | if ((response.status === 403 || response.status === 401) && retryCount === 0) { |
| | | const result = await response.clone().json(); |
| | | if (result.code === 'rest_cookie_invalid_nonce' || result.message?.includes('Cookie check')) { |
| | | console.log('Nonce invalid, refreshing auth...'); |
| | | await this.refresh(); |
| | | return attempt(1); // Retry once |
| | | } |
| | | } |
| | | |
| | | return response; |
| | | }; |
| | | |
| | | return attempt(); |
| | | } |
| | | |
| | | /** |
| | | * Fetch authentication status from API |
| | | */ |
| | | async fetchAuth() { |