-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauth.ts
More file actions
260 lines (222 loc) · 8.39 KB
/
auth.ts
File metadata and controls
260 lines (222 loc) · 8.39 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
export interface AuthResponse {
access_token: string;
refresh_token: string;
expires_in: number;
refresh_expires_in: number;
token_type: string;
session_state: string;
scope: string;
'not-before-policy': number;
}
export interface SignInCredentials {
username: string;
password: string;
}
export interface SignUpCredentials {
email: string;
roleType: string;
username: string;
firstName: string;
lastName: string;
password: string;
}
export interface SignUpResponse {
data: any;
message: string;
}
export interface RefreshTokenRequest {
refreshToken: string;
}
export interface User {
id: string;
username: string;
email?: string;
name?: string;
givenName?: string;
familyName?: string;
emailVerified?: boolean;
scope?: string;
}
export class AuthService {
private static readonly API_BASE_URL = 'https://api-stage.cyruswallet.io';
private static readonly LOCAL_API_BASE_URL = 'http://fe3ab829-d558-4834-afcf-6ed7ca440ca4.ka.bw-cloud-instance.org:8080';
private static readonly CLIENT_ID = 'exit-normal-customer-mobile-app';
private static readonly GRANT_TYPE = 'password';
static async signUp(credentials: SignUpCredentials): Promise<SignUpResponse> {
const response = await fetch(`${this.LOCAL_API_BASE_URL}/api/v1/users/sign-up`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
});
if (!response.ok) {
let errorText = '';
try {
errorText = await response.text();
} catch {}
let errorMessage = errorText;
try {
const parsed = JSON.parse(errorText);
errorMessage = (parsed as any)?.message || (parsed as any)?.error || errorText;
} catch {}
const fallback = response.statusText || 'Request failed';
throw new Error(errorMessage || fallback);
}
const data: SignUpResponse = await response.json();
return data;
}
static async signIn(credentials: SignInCredentials): Promise<AuthResponse> {
const response = await fetch(`${this.LOCAL_API_BASE_URL}/api/v1/users/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
});
if (!response.ok) {
let errorText = '';
try {
errorText = await response.text();
} catch {}
let errorMessage = errorText;
try {
const parsed = JSON.parse(errorText);
errorMessage = (parsed as any)?.message || (parsed as any)?.error || errorText;
} catch {}
const fallback = response.statusText || 'Request failed';
throw new Error(errorMessage || fallback);
}
const data: AuthResponse = await response.json();
localStorage.setItem('auth.access_token', data.access_token);
localStorage.setItem('auth.refresh_token', data.refresh_token);
localStorage.setItem('auth.expires_in', data.expires_in.toString());
localStorage.setItem('auth.refresh_expires_in', data.refresh_expires_in.toString());
localStorage.setItem('auth.token_type', data.token_type);
localStorage.setItem('auth.session_state', data.session_state);
localStorage.setItem('auth.scope', data.scope);
localStorage.setItem('auth.not_before_policy', data['not-before-policy'].toString());
const accessExpiresAt = Date.now() + (data.expires_in * 1000);
const refreshExpiresAt = Date.now() + (data.refresh_expires_in * 1000);
localStorage.setItem('auth.access_expires_at', accessExpiresAt.toString());
localStorage.setItem('auth.refresh_expires_at', refreshExpiresAt.toString());
return data;
}
static async refreshToken(): Promise<AuthResponse | null> {
const refreshToken = localStorage.getItem('auth.refresh_token');
const refreshExpiresAt = localStorage.getItem('auth.refresh_expires_at');
if (!refreshToken || !refreshExpiresAt) {
return null;
}
const now = Date.now();
const refreshExpiry = parseInt(refreshExpiresAt, 10);
if (Number.isFinite(refreshExpiry) && now >= refreshExpiry) {
await this.signOut();
return null;
}
try {
const requestBody: RefreshTokenRequest = { refreshToken };
const response = await fetch(`${this.LOCAL_API_BASE_URL}/api/v1/users/access-token/by-refresh-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: AuthResponse = await response.json();
localStorage.setItem('auth.access_token', data.access_token);
localStorage.setItem('auth.refresh_token', data.refresh_token);
localStorage.setItem('auth.expires_in', data.expires_in.toString());
localStorage.setItem('auth.refresh_expires_in', data.refresh_expires_in.toString());
localStorage.setItem('auth.token_type', data.token_type);
localStorage.setItem('auth.session_state', data.session_state);
localStorage.setItem('auth.scope', data.scope);
localStorage.setItem('auth.not_before_policy', data['not-before-policy'].toString());
const accessExpiresAt = Date.now() + data.expires_in * 1000;
const newRefreshExpiresAt = Date.now() + data.refresh_expires_in * 1000;
localStorage.setItem('auth.access_expires_at', accessExpiresAt.toString());
localStorage.setItem('auth.refresh_expires_at', newRefreshExpiresAt.toString());
return data;
} catch (error) {
console.error('Failed to refresh token:', error);
await this.signOut();
return null;
}
}
static async signOut(): Promise<void> {
localStorage.removeItem('auth.access_token');
localStorage.removeItem('auth.refresh_token');
localStorage.removeItem('auth.expires_in');
localStorage.removeItem('auth.refresh_expires_in');
localStorage.removeItem('auth.token_type');
localStorage.removeItem('auth.session_state');
localStorage.removeItem('auth.scope');
localStorage.removeItem('auth.not_before_policy');
localStorage.removeItem('auth.access_expires_at');
localStorage.removeItem('auth.refresh_expires_at');
localStorage.removeItem('auth.user');
try {
window.dispatchEvent(new Event('auth:signout'));
} catch {}
}
static isAuthenticated(): boolean {
const now = Date.now();
const accessToken = localStorage.getItem('auth.access_token');
const accessExpiresAt = localStorage.getItem('auth.access_expires_at');
const refreshToken = localStorage.getItem('auth.refresh_token');
const refreshExpiresAt = localStorage.getItem('auth.refresh_expires_at');
const accessValid = !!accessToken && !!accessExpiresAt && now < parseInt(accessExpiresAt, 10);
const refreshValid = !!refreshToken && !!refreshExpiresAt && now < parseInt(refreshExpiresAt, 10);
return accessValid || refreshValid;
}
static async ensureValidToken(): Promise<string | null> {
const now = Date.now();
const accessToken = localStorage.getItem('auth.access_token');
const accessExpiresAt = localStorage.getItem('auth.access_expires_at');
const refreshToken = localStorage.getItem('auth.refresh_token');
const refreshExpiresAt = localStorage.getItem('auth.refresh_expires_at');
const accessValid = !!accessToken && !!accessExpiresAt && now < parseInt(accessExpiresAt, 10);
if (accessValid) {
return accessToken as string;
}
const refreshValid = !!refreshToken && !!refreshExpiresAt && now < parseInt(refreshExpiresAt, 10);
if (!refreshValid) {
await this.signOut();
return null;
}
try {
const refreshResult = await this.refreshToken();
if (refreshResult && refreshResult.access_token) {
return refreshResult.access_token;
}
} catch (error) {
console.error('Failed to refresh token:', error);
}
await this.signOut();
return null;
}
static getAccessToken(): string | null {
if (!this.isAuthenticated()) {
return null;
}
return localStorage.getItem('auth.access_token');
}
static getCurrentUser(): User | null {
const userData = localStorage.getItem('auth.user');
if (!userData) {
return null;
}
try {
return JSON.parse(userData);
} catch {
return null;
}
}
static setCurrentUser(user: User): void {
localStorage.setItem('auth.user', JSON.stringify(user));
}
// Removed unused legacy signIn method
}