File size: 1,045 Bytes
808332c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Shared API utility for AdaptiveAuth React UI
const BASE = '/api/v1';

export const ENDPOINTS = {
  AUTH:  `${BASE}/auth`,
  DEMO:  `${BASE}/demo`,
  ADMIN: `${BASE}/admin`,
  USER:  `${BASE}/user`,
  RISK:  `${BASE}/risk`,
  INTEL: `${BASE}/session-intel`,
  API:   BASE,
};

export const getToken  = () => localStorage.getItem('token') || '';
export const saveToken = (t) => localStorage.setItem('token', t);
export const clearToken = () => localStorage.removeItem('token');

export async function req(url, method = 'GET', body = null, auth = true) {
  const headers = { 'Content-Type': 'application/json' };
  if (auth) {
    const t = getToken();
    if (t) headers['Authorization'] = `Bearer ${t}`;
  }
  try {
    const res = await fetch(url, {
      method,
      headers,
      body: body != null ? JSON.stringify(body) : undefined,
    });
    const data = await res.json().catch(() => ({}));
    return { ok: res.ok, status: res.status, data };
  } catch (e) {
    return { ok: false, status: 0, data: { detail: e.message } };
  }
}