-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-usage.ts
More file actions
153 lines (124 loc) · 3.99 KB
/
Copy pathbasic-usage.ts
File metadata and controls
153 lines (124 loc) · 3.99 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/**
* Basic Usage Example - Flux Protocol SDK
*
* This example demonstrates the fundamental workflow:
* 1. Initialize the SDK
* 2. Login and set tokens
* 3. Make authenticated requests
* 4. Handle token rotation
* 5. Logout
*/
import { FluxProtocol } from '@flux-protocol/sdk';
// -----------------------------------
// Step 1: Initialize FluxProtocol
// -----------------------------------
const flux = FluxProtocol({
deviceId: 'my-device-123', // Optional: auto-generated if not provided
rotationWindow: 5000, // Optional: trigger rotation 5s before expiry
});
// -----------------------------------
// Step 2: Login
// -----------------------------------
async function login(email: string, password: string) {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
throw new Error('Login failed');
}
const { accessToken, proofKey, expiresIn } = await response.json();
// Initialize SDK with tokens
flux.setTokens({ accessToken, proofKey, expiresIn });
console.log(' Logged in successfully');
}
// -----------------------------------
// Step 3: Make authenticated requests
// -----------------------------------
async function fetchUserProfile() {
const headers = await flux.buildHeadersAsync();
const response = await fetch('/api/user/profile', {
headers,
});
if (!response.ok) {
throw new Error('Failed to fetch profile');
}
return response.json();
}
// -----------------------------------
// Step 4: Handle token rotation
// -----------------------------------
flux.onRotate(async (event) => {
console.log(' Token rotation triggered', {
expiresAt: new Date(event.expiresAt),
remainingTime: event.expiresAt - event.timestamp,
});
try {
// Call your token rotation endpoint
const headers = await flux.buildHeadersAsync();
const response = await fetch('/api/auth/rotate', {
method: 'POST',
headers,
});
if (!response.ok) {
throw new Error('Token rotation failed');
}
const { accessToken, expiresIn } = await response.json();
// Update SDK with new token
flux.updateAccess(accessToken, expiresIn);
console.log(' Token rotated successfully');
} catch (error) {
console.error(' Token rotation failed:', error);
// Handle rotation failure (e.g., force logout)
}
});
// -----------------------------------
// Error handling
// -----------------------------------
flux.onError((event) => {
console.error(` Flux error [${event.code}]:`, event.message, event.context);
// Handle specific errors
if (event.code === 'TOKEN_EXPIRED') {
console.log('Token expired, redirecting to login...');
// Redirect to login page
}
});
// -----------------------------------
// Step 5: Logout
// -----------------------------------
async function logout() {
try {
const headers = await flux.buildHeadersAsync();
await fetch('/api/auth/logout', {
method: 'POST',
headers,
});
// Stop the SDK (clears tokens and timers)
flux.stop();
console.log(' Logged out successfully');
} catch (error) {
console.error(' Logout failed:', error);
// Still stop the SDK even if request fails
flux.stop();
}
}
// -----------------------------------
// Usage
// -----------------------------------
async function main() {
try {
// Login
await login('user@example.com', 'password123');
// Fetch data
const profile = await fetchUserProfile();
console.log('User profile:', profile);
// SDK will automatically handle rotation in the background
// Later... logout
await logout();
} catch (error) {
console.error('Error:', error);
}
}
// Run the example
void main();