File size: 2,071 Bytes
9e7d4f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { BACKEND_URL } from './api.js';

export async function login(username, password) {
  const res = await fetch(`${BACKEND_URL}/api/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password })
  });

  const data = await res.json();
  if (!res.ok) {
    throw new Error(data.detail || "Login failed");
  }

  localStorage.setItem('serinity_token', data.access_token);
  return data;
}



export async function signup(payload) {
  const res = await fetch(`${BACKEND_URL}/api/auth/signup`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  });

  const data = await res.json();
  if (!res.ok) {
    if (Array.isArray(data.detail)) {
      throw new Error(data.detail[0].msg || "Validation error");
    }
    throw new Error(data.detail || "Signup failed");
  }

  localStorage.setItem('serinity_token', data.access_token);
  return data;
}

export async function resetPassword(email, new_password) {
  const res = await fetch(`${BACKEND_URL}/api/auth/reset-password`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, new_password })
  });

  const data = await res.json();
  if (!res.ok) {
    if (Array.isArray(data.detail)) {
      throw new Error(data.detail[0].msg || "Validation error");
    }
    throw new Error(data.detail || "Failed to reset password");
  }
  return data;
}

export async function deleteAccount() {
  const token = localStorage.getItem('serinity_token');
  const res = await fetch(`${BACKEND_URL}/api/auth/delete-account`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${token}`
    }
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.detail || "Failed to delete account");
  return data;
}

export function logout() {
  localStorage.removeItem('serinity_token');
}

export function isAuthenticated() {
  return !!localStorage.getItem('serinity_token');
}