-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathauth-api.ts
More file actions
62 lines (50 loc) · 1.75 KB
/
auth-api.ts
File metadata and controls
62 lines (50 loc) · 1.75 KB
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
import { AuthConfig, AuthTokens, User } from "./types";
const API_BASE = "/api/v1";
export const authService = {
async getAuthConfig(): Promise<AuthConfig> {
const res = await fetch(`${API_BASE}/`);
if (!res.ok) throw new Error("Failed to fetch auth config");
const data = await res.json();
return data.authentication;
},
async loginWithPassword(
provider: string,
username: string,
password: string,
): Promise<AuthTokens> {
const body = new URLSearchParams({ username, password });
const res = await fetch(`${API_BASE}/auth/provider/${provider}/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body,
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: "Login failed" }));
throw new Error(err.detail || "Invalid credentials");
}
return res.json();
},
async refreshSession(refreshToken: string): Promise<AuthTokens> {
const res = await fetch(`${API_BASE}/auth/session/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!res.ok) throw new Error("Failed to refresh session");
return res.json();
},
async getCurrentUser(accessToken: string): Promise<User> {
const res = await fetch(`${API_BASE}/auth/whoami`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!res.ok) throw new Error("Failed to get user info");
const data = await res.json();
return data.data;
},
async logout(accessToken: string): Promise<void> {
await fetch(`${API_BASE}/auth/logout`, {
method: "POST",
headers: { Authorization: `Bearer ${accessToken}` },
});
},
};