// ── ERPNext session-cookie auth ────────────────────────────────────────────── // To swap to JWT or another auth method: // 1. Replace login() / logout() / getLoggedUser() implementations here. // 2. The stores/auth.js calls these — no changes needed there. // ───────────────────────────────────────────────────────────────────────────── import { BASE_URL } from 'src/config/erpnext' let _csrf = null export async function getCSRF () { if (_csrf) return _csrf try { const res = await fetch(BASE_URL + '/', { credentials: 'include' }) const html = await res.text() const m = html.match(/csrf_token\s*[:=]\s*['"]([^'"]+)['"]/) if (m) _csrf = m[1] } catch { /* ignore */ } return _csrf } export function invalidateCSRF () { _csrf = null } export async function login (usr, pwd) { const res = await fetch(BASE_URL + '/api/method/login', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ usr, pwd }), }) const data = await res.json() if (!res.ok || data.exc_type === 'AuthenticationError') { throw new Error(data.message || 'Identifiants incorrects') } invalidateCSRF() return data } export async function logout () { try { await fetch(BASE_URL + '/api/method/frappe.auth.logout', { method: 'POST', credentials: 'include', }) } catch { /* ignore */ } invalidateCSRF() } // Returns email string if logged in, null if guest/error export async function getLoggedUser () { try { const res = await fetch(BASE_URL + '/api/method/frappe.auth.get_logged_user', { credentials: 'include', }) const data = await res.json() const user = data.message return user && user !== 'Guest' ? user : null } catch { return null } }