@bagelink/auth 1.4.169 → 1.4.174

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -55,74 +55,199 @@ class AuthApi {
55
55
  }
56
56
  setupInterceptors() {
57
57
  this.api.interceptors.request.use((config) => {
58
- const token = localStorage.getItem("access_token");
59
- if (token !== null && config.headers) {
60
- config.headers.Authorization = `Bearer ${token}`;
58
+ const sessionToken = localStorage.getItem("session_token");
59
+ if (sessionToken !== null && config.headers) {
60
+ config.headers.Authorization = `Bearer ${sessionToken}`;
61
61
  }
62
62
  const urlParams = new URLSearchParams(window.location.search);
63
63
  const resetToken = urlParams.get("token");
64
64
  if (resetToken !== null && config.headers) {
65
- config.headers.Authorization = `Bearer ${resetToken}`;
65
+ config.headers["X-Reset-Token"] = resetToken;
66
66
  }
67
67
  return config;
68
68
  });
69
69
  }
70
- async login(username, password) {
71
- const { data } = await this.api.post("/auth/login", {
72
- username: username.toLowerCase(),
70
+ // ============================================
71
+ // Authentication Methods
72
+ // ============================================
73
+ /**
74
+ * Get available authentication methods
75
+ */
76
+ async getAuthMethods() {
77
+ return this.api.get("/authentication/methods");
78
+ }
79
+ /**
80
+ * Register a new account
81
+ */
82
+ async register(data) {
83
+ const response = await this.api.post("/authentication/register", {
84
+ ...data,
85
+ email: data.email.toLowerCase()
86
+ });
87
+ if (response.data.session_token) {
88
+ localStorage.setItem("session_token", response.data.session_token);
89
+ }
90
+ return response;
91
+ }
92
+ /**
93
+ * Login with password
94
+ */
95
+ async login(email, password) {
96
+ const response = await this.api.post("/authentication/login/password", {
97
+ email: email.toLowerCase(),
73
98
  password
74
99
  });
75
- localStorage.setItem("access_token", data.access_token);
76
- return { data };
77
- }
78
- logout() {
79
- localStorage.removeItem("access_token");
80
- window.location.reload();
81
- }
82
- async passwordRecovery(email) {
83
- return this.api.post("/auth/password-recovery", { email });
84
- }
85
- async resetPassword(newPassword) {
86
- return this.api.post("/auth/reset-password", { new_password: newPassword });
87
- }
100
+ if (response.data.session_token) {
101
+ localStorage.setItem("session_token", response.data.session_token);
102
+ }
103
+ return response;
104
+ }
105
+ /**
106
+ * Logout and clear session
107
+ */
108
+ async logout() {
109
+ const response = await this.api.post("/authentication/logout", {});
110
+ localStorage.removeItem("session_token");
111
+ return response;
112
+ }
113
+ /**
114
+ * Refresh current session
115
+ */
116
+ async refreshSession() {
117
+ const response = await this.api.post("/authentication/refresh", {});
118
+ if (response.data.session_token) {
119
+ localStorage.setItem("session_token", response.data.session_token);
120
+ }
121
+ return response;
122
+ }
123
+ // ============================================
124
+ // Current User (Me) Methods
125
+ // ============================================
126
+ /**
127
+ * Get current user account info
128
+ */
88
129
  async getCurrentUser() {
89
- return this.api.get("/users/me");
90
- }
91
- async signup(user) {
92
- return this.api.post("/users/signup", {
93
- email: user.email.toLowerCase(),
94
- password: user.password,
95
- first_name: user.first_name,
96
- last_name: user.last_name
130
+ return this.api.get("/authentication/me");
131
+ }
132
+ /**
133
+ * Update current user profile
134
+ */
135
+ async updateCurrentUser(data) {
136
+ return this.api.patch("/authentication/me", data);
137
+ }
138
+ /**
139
+ * Delete current user account
140
+ */
141
+ async deleteCurrentUser() {
142
+ const response = await this.api.delete("/authentication/me");
143
+ localStorage.removeItem("session_token");
144
+ return response;
145
+ }
146
+ // ============================================
147
+ // Account Management (Admin)
148
+ // ============================================
149
+ /**
150
+ * Get account information by ID
151
+ */
152
+ async getAccount(accountId) {
153
+ return this.api.get(`/authentication/account/${accountId}`);
154
+ }
155
+ /**
156
+ * Update account by ID
157
+ */
158
+ async updateAccount(accountId, data) {
159
+ return this.api.patch(`/authentication/account/${accountId}`, data);
160
+ }
161
+ /**
162
+ * Delete account by ID
163
+ */
164
+ async deleteAccount(accountId) {
165
+ return this.api.delete(`/authentication/account/${accountId}`);
166
+ }
167
+ /**
168
+ * Activate account by ID
169
+ */
170
+ async activateAccount(accountId) {
171
+ return this.api.post(`/authentication/account/${accountId}/activate`, {});
172
+ }
173
+ /**
174
+ * Deactivate account by ID
175
+ */
176
+ async deactivateAccount(accountId) {
177
+ return this.api.post(`/authentication/account/${accountId}/deactivate`, {});
178
+ }
179
+ // ============================================
180
+ // Password Management
181
+ // ============================================
182
+ /**
183
+ * Change password (requires current password)
184
+ */
185
+ async changePassword(data) {
186
+ return this.api.post("/authentication/password/change", data);
187
+ }
188
+ /**
189
+ * Initiate forgot password flow
190
+ */
191
+ async forgotPassword(email) {
192
+ return this.api.post("/authentication/password/forgot", {
193
+ email: email.toLowerCase()
97
194
  });
98
195
  }
99
- async updatePassword(form) {
100
- return this.api.patch("/users/me/password", {
101
- current_password: form.current_password,
102
- new_password: form.new_password
103
- });
104
- }
105
- async updateUserProfile(user) {
106
- return this.api.patch("/users/me", user);
107
- }
108
- async setUserStatus(userId, isActive) {
109
- return this.api.patch(`/users/${userId}`, {
110
- is_active: isActive
196
+ /**
197
+ * Verify password reset token
198
+ */
199
+ async verifyResetToken(token) {
200
+ return this.api.get(`/authentication/password/verify-reset-token/${token}`);
201
+ }
202
+ /**
203
+ * Reset password with token
204
+ */
205
+ async resetPassword(data) {
206
+ return this.api.post("/authentication/password/reset", data);
207
+ }
208
+ // ============================================
209
+ // Email Verification
210
+ // ============================================
211
+ /**
212
+ * Send email verification
213
+ */
214
+ async sendVerification(data = {}, user) {
215
+ return this.api.post("/authentication/verify/send", data, {
216
+ params: user ? { user } : void 0
111
217
  });
112
218
  }
113
- async deleteUser(userId) {
114
- return this.api.delete(`/users/${userId}`);
115
- }
116
- async getUsers(limit = 100, skip) {
117
- return this.api.get("/users/", {
118
- params: { skip, limit }
119
- });
120
- }
121
- async createUser(user) {
122
- return this.api.post("/users/", user);
123
- }
124
- async getUser(userId) {
125
- return this.api.get(`/users/${userId}`);
219
+ /**
220
+ * Verify email with token
221
+ */
222
+ async verifyEmail(token) {
223
+ return this.api.post("/authentication/verify/email", { token });
224
+ }
225
+ // ============================================
226
+ // Session Management
227
+ // ============================================
228
+ /**
229
+ * Get sessions for an account
230
+ */
231
+ async getSessions(accountId) {
232
+ return this.api.get(`/authentication/sessions/${accountId}`);
233
+ }
234
+ /**
235
+ * Revoke a specific session
236
+ */
237
+ async revokeSession(sessionToken) {
238
+ return this.api.delete(`/authentication/sessions/${sessionToken}`);
239
+ }
240
+ /**
241
+ * Revoke all sessions for an account
242
+ */
243
+ async revokeAllSessions(accountId) {
244
+ return this.api.delete(`/authentication/sessions/account/${accountId}`);
245
+ }
246
+ /**
247
+ * Cleanup expired sessions (admin)
248
+ */
249
+ async cleanupSessions() {
250
+ return this.api.post("/authentication/cleanup-sessions", {});
126
251
  }
127
252
  }
128
253
 
@@ -131,41 +256,85 @@ var AuthState = /* @__PURE__ */ ((AuthState2) => {
131
256
  AuthState2["LOGOUT"] = "logout";
132
257
  AuthState2["SIGNUP"] = "signup";
133
258
  AuthState2["PASSWORD_RESET"] = "password_reset";
259
+ AuthState2["PASSWORD_CHANGE"] = "password_change";
134
260
  AuthState2["PROFILE_UPDATE"] = "profile_update";
135
261
  AuthState2["AUTH_CHECK"] = "auth_check";
262
+ AuthState2["EMAIL_VERIFIED"] = "email_verified";
263
+ AuthState2["SESSION_REFRESH"] = "session_refresh";
136
264
  return AuthState2;
137
265
  })(AuthState || {});
266
+ function accountToUser(account) {
267
+ if (account === null) return null;
268
+ if (account.person !== void 0) {
269
+ return {
270
+ id: account.person.id,
271
+ accountId: account.id,
272
+ name: account.person.name,
273
+ email: account.person.email,
274
+ type: account.account_type,
275
+ roles: account.person.roles,
276
+ isActive: account.is_active,
277
+ isVerified: account.is_verified,
278
+ lastLogin: account.last_login
279
+ };
280
+ }
281
+ if (account.entity !== void 0) {
282
+ return {
283
+ id: account.entity.id,
284
+ accountId: account.id,
285
+ name: account.entity.name,
286
+ type: account.account_type,
287
+ isActive: account.is_active,
288
+ isVerified: account.is_verified,
289
+ lastLogin: account.last_login,
290
+ entityType: account.entity.type,
291
+ metadata: account.entity.metadata
292
+ };
293
+ }
294
+ const emailMethod = account.authentication_methods?.find(
295
+ (m) => m.type === "password" || m.type === "email_token"
296
+ );
297
+ return {
298
+ id: account.id,
299
+ accountId: account.id,
300
+ name: account.display_name,
301
+ email: emailMethod?.identifier,
302
+ type: account.account_type,
303
+ isActive: account.is_active,
304
+ isVerified: account.is_verified,
305
+ lastLogin: account.last_login
306
+ };
307
+ }
138
308
 
139
309
  let authApi = null;
140
310
  let eventEmitter = null;
141
- const currentUser = vue.ref({
142
- id: "",
143
- email: "",
144
- first_name: "",
145
- last_name: "",
146
- is_superuser: false,
147
- is_active: false
148
- });
311
+ const accountInfo = vue.ref(null);
149
312
  function initAuth({
150
313
  axios,
151
314
  baseURL
152
315
  }) {
153
- if (!authApi) {
316
+ if (authApi === null) {
154
317
  authApi = new AuthApi(axios, baseURL);
155
318
  }
156
- if (!eventEmitter) {
319
+ if (eventEmitter === null) {
157
320
  eventEmitter = new EventEmitter();
158
321
  }
159
322
  return {
160
323
  // Event listener methods
161
324
  on(event, handler) {
162
- eventEmitter.on(event, handler);
325
+ if (eventEmitter) {
326
+ eventEmitter.on(event, handler);
327
+ }
163
328
  },
164
329
  off(event, handler) {
165
- eventEmitter.off(event, handler);
330
+ if (eventEmitter) {
331
+ eventEmitter.off(event, handler);
332
+ }
166
333
  },
167
334
  removeAllListeners(event) {
168
- eventEmitter.removeAllListeners(event);
335
+ if (eventEmitter) {
336
+ eventEmitter.removeAllListeners(event);
337
+ }
169
338
  },
170
339
  install(app) {
171
340
  app.config.globalProperties.$auth = useAuth();
@@ -173,135 +342,195 @@ function initAuth({
173
342
  };
174
343
  }
175
344
  function useAuth() {
176
- if (!authApi) {
345
+ if (authApi === null) {
177
346
  throw new Error("Auth not initialized. Call initAuth first.");
178
347
  }
179
- const getFullName = () => `${currentUser.value.first_name} ${currentUser.value.last_name}`;
180
- const getIsLoggedIn = () => currentUser.value.id.length > 0;
348
+ if (eventEmitter === null) {
349
+ throw new Error("Event emitter not initialized. Call initAuth first.");
350
+ }
351
+ const api = authApi;
352
+ const emitter = eventEmitter;
353
+ const user = vue.computed(() => accountToUser(accountInfo.value));
354
+ const getFullName = () => {
355
+ return user.value?.name ?? "";
356
+ };
357
+ const getIsLoggedIn = () => {
358
+ return user.value !== null;
359
+ };
360
+ const getEmail = () => {
361
+ return user.value?.email ?? "";
362
+ };
363
+ const getRoles = () => {
364
+ return user.value?.roles ?? [];
365
+ };
366
+ const getAccountType = () => {
367
+ return user.value?.type ?? "person";
368
+ };
369
+ const isPersonAccount = () => {
370
+ return user.value?.type === "person";
371
+ };
372
+ const isEntityAccount = () => {
373
+ return user.value?.type === "entity";
374
+ };
181
375
  async function logout() {
182
- try {
183
- await authApi.logout();
184
- currentUser.value = {
185
- id: "",
186
- email: "",
187
- first_name: "",
188
- last_name: "",
189
- is_superuser: false,
190
- is_active: false
191
- };
192
- eventEmitter.emit(AuthState.LOGOUT);
193
- } catch (error) {
194
- throw error;
195
- }
376
+ const logoutPromise = api.logout();
377
+ await logoutPromise.catch(() => {
378
+ });
379
+ accountInfo.value = null;
380
+ emitter.emit(AuthState.LOGOUT);
196
381
  }
197
382
  async function login(credentials) {
198
- try {
199
- await authApi.login(
200
- credentials.email.toLowerCase(),
201
- credentials.password
202
- );
383
+ const { data } = await api.login(
384
+ credentials.email.toLowerCase(),
385
+ credentials.password
386
+ );
387
+ if (data.success === true && data.requires_verification !== true) {
203
388
  await checkAuth();
204
- eventEmitter.emit(AuthState.LOGIN);
205
- } catch (error) {
206
- throw error;
207
389
  }
390
+ emitter.emit(AuthState.LOGIN);
391
+ return data;
208
392
  }
209
393
  async function checkAuth() {
210
394
  try {
211
- if (!getIsLoggedIn()) {
212
- const { data } = await authApi.getCurrentUser();
213
- currentUser.value = data;
214
- if (getIsLoggedIn()) {
215
- eventEmitter.emit(AuthState.AUTH_CHECK);
216
- }
395
+ const { data } = await api.getCurrentUser();
396
+ accountInfo.value = data;
397
+ if (getIsLoggedIn()) {
398
+ emitter.emit(AuthState.AUTH_CHECK);
217
399
  }
218
- } catch (error) {
400
+ return true;
401
+ } catch {
402
+ accountInfo.value = null;
219
403
  return false;
220
404
  }
221
- return getIsLoggedIn();
222
405
  }
223
- async function signup(user) {
224
- try {
225
- if (user.password !== user.confirmPassword) {
226
- throw new Error("Passwords do not match");
227
- }
228
- const { data } = await authApi.signup(user);
229
- currentUser.value = data;
230
- eventEmitter.emit(AuthState.SIGNUP);
231
- } catch (error) {
232
- throw error;
406
+ async function signup(newUser) {
407
+ const hasPassword = newUser.password !== void 0 && newUser.password.length > 0;
408
+ if (hasPassword && newUser.password !== newUser.confirmPassword) {
409
+ throw new Error("Passwords do not match");
233
410
  }
234
- }
235
- async function recoverPassword(email) {
236
- try {
237
- await authApi.passwordRecovery(email);
238
- } catch (error) {
239
- throw error;
411
+ const { data } = await api.register({
412
+ email: newUser.email,
413
+ first_name: newUser.first_name,
414
+ last_name: newUser.last_name,
415
+ phone_number: newUser.phone_number,
416
+ password: newUser.password
417
+ });
418
+ if (data.success === true && data.requires_verification !== true) {
419
+ await checkAuth();
240
420
  }
421
+ emitter.emit(AuthState.SIGNUP);
422
+ return data;
241
423
  }
242
- async function resetPassword(newPassword) {
243
- try {
244
- await authApi.resetPassword(newPassword);
245
- eventEmitter.emit(AuthState.PASSWORD_RESET);
246
- } catch (error) {
247
- throw error;
248
- }
424
+ async function forgotPassword(email) {
425
+ await api.forgotPassword(email);
249
426
  }
250
- async function updatePassword(form) {
251
- try {
252
- if (form.new_password !== form.confirmNewPassword) {
253
- throw new Error("Passwords do not match");
254
- }
255
- await authApi.updatePassword(form);
256
- eventEmitter.emit(AuthState.PASSWORD_RESET);
257
- } catch (error) {
258
- throw error;
259
- }
427
+ async function verifyResetToken(token) {
428
+ await api.verifyResetToken(token);
260
429
  }
261
- async function updateProfile(user) {
262
- try {
263
- const { data } = await authApi.updateUserProfile(user);
264
- currentUser.value = { ...currentUser.value, ...data };
265
- eventEmitter.emit(AuthState.PROFILE_UPDATE);
266
- } catch (error) {
267
- throw error;
430
+ async function resetPassword(token, newPassword) {
431
+ await api.resetPassword({ token, new_password: newPassword });
432
+ emitter.emit(AuthState.PASSWORD_RESET);
433
+ }
434
+ async function changePassword(form) {
435
+ if (form.new_password !== form.confirmNewPassword) {
436
+ throw new Error("Passwords do not match");
268
437
  }
438
+ await api.changePassword({
439
+ current_password: form.current_password,
440
+ new_password: form.new_password
441
+ });
442
+ emitter.emit(AuthState.PASSWORD_CHANGE);
269
443
  }
270
- async function toggleUserStatus(userId, isActive) {
271
- try {
272
- await authApi.setUserStatus(userId, isActive);
273
- } catch (error) {
274
- throw error;
444
+ async function updateProfile(updates) {
445
+ const { data } = await api.updateCurrentUser(updates);
446
+ accountInfo.value = data;
447
+ emitter.emit(AuthState.PROFILE_UPDATE);
448
+ }
449
+ async function activateAccount(accountId) {
450
+ await api.activateAccount(accountId);
451
+ }
452
+ async function deactivateAccount(accountId) {
453
+ await api.deactivateAccount(accountId);
454
+ }
455
+ async function deleteAccount(accountId) {
456
+ await api.deleteAccount(accountId);
457
+ }
458
+ async function deleteCurrentUser() {
459
+ await api.deleteCurrentUser();
460
+ accountInfo.value = null;
461
+ }
462
+ async function sendVerification(email) {
463
+ await api.sendVerification({ email });
464
+ }
465
+ async function verifyEmail(token) {
466
+ await api.verifyEmail(token);
467
+ await checkAuth();
468
+ emitter.emit(AuthState.EMAIL_VERIFIED);
469
+ }
470
+ async function refreshSession() {
471
+ await api.refreshSession();
472
+ emitter.emit(AuthState.SESSION_REFRESH);
473
+ }
474
+ async function getSessions(accountId) {
475
+ const id = accountId ?? user.value?.accountId;
476
+ if (id === void 0 || id === "") {
477
+ throw new Error("No account ID available");
275
478
  }
479
+ return api.getSessions(id);
276
480
  }
277
- async function deleteUser(userId) {
278
- try {
279
- await authApi.deleteUser(userId);
280
- } catch (error) {
281
- throw error;
481
+ async function revokeSession(sessionToken) {
482
+ await api.revokeSession(sessionToken);
483
+ }
484
+ async function revokeAllSessions(accountId) {
485
+ const id = accountId ?? user.value?.accountId;
486
+ if (id === void 0 || id === "") {
487
+ throw new Error("No account ID available");
282
488
  }
489
+ await api.revokeAllSessions(id);
283
490
  }
284
491
  return {
285
- // State
286
- currentUser,
492
+ // Primary State (use this!)
493
+ user,
494
+ // Full account info (for advanced use cases)
495
+ accountInfo,
287
496
  // Getters
288
497
  getFullName,
289
498
  getIsLoggedIn,
290
- // Actions
291
- logout,
499
+ getEmail,
500
+ getRoles,
501
+ getAccountType,
502
+ isPersonAccount,
503
+ isEntityAccount,
504
+ // Authentication Actions
292
505
  login,
293
- checkAuth,
506
+ logout,
294
507
  signup,
295
- recoverPassword,
296
- resetPassword,
297
- updatePassword,
508
+ checkAuth,
509
+ refreshSession,
510
+ // Profile Actions
298
511
  updateProfile,
299
- toggleUserStatus,
300
- deleteUser
512
+ deleteCurrentUser,
513
+ // Password Actions
514
+ changePassword,
515
+ forgotPassword,
516
+ verifyResetToken,
517
+ resetPassword,
518
+ // Email Verification Actions
519
+ sendVerification,
520
+ verifyEmail,
521
+ // Admin Actions
522
+ activateAccount,
523
+ deactivateAccount,
524
+ deleteAccount,
525
+ // Session Management
526
+ getSessions,
527
+ revokeSession,
528
+ revokeAllSessions
301
529
  };
302
530
  }
303
531
 
304
532
  exports.AuthApi = AuthApi;
305
533
  exports.AuthState = AuthState;
534
+ exports.accountToUser = accountToUser;
306
535
  exports.initAuth = initAuth;
307
536
  exports.useAuth = useAuth;