@arex95/vue-core 1.1.21 → 1.1.23

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.
@@ -2,7 +2,6 @@ import { AuthParams, AuthResponse } from "@/types";
2
2
  import { SessionPreference } from "@config/global/sessionConfig";
3
3
  /**
4
4
  * @typedef {object} AuthHook
5
- * @property {function(): Promise<string | null>} getJwt - Retrieves the current JWT.
6
5
  * @property {function(): Promise<number | null>} getTokenExpiry - Retrieves the expiration time of the current token in milliseconds.
7
6
  * @property {function(): Promise<void>} cleanCredentials - Clears authentication credentials from storage.
8
7
  * @property {(params?: AuthParams) => Promise<void>} logout - Logs out the user, clears credentials, and reloads the page.
@@ -19,11 +18,7 @@ import { SessionPreference } from "@config/global/sessionConfig";
19
18
  * @returns {AuthHook} An object containing authentication functions.
20
19
  */
21
20
  export declare function useAuth(secretKey?: string): {
22
- getJwt: () => Promise<string | null>;
23
- getTokenExpiry: () => Promise<number | null>;
24
- cleanCredentials: (preference: SessionPreference) => Promise<void>;
25
21
  logout: (params?: AuthParams) => Promise<void>;
26
22
  login: (params: AuthParams, persistence: SessionPreference) => Promise<AuthResponse>;
27
23
  refresh: () => Promise<AuthResponse>;
28
- verifyAuth: () => Promise<boolean>;
29
24
  };
package/dist/index.mjs CHANGED
@@ -2,9 +2,9 @@ import axios from 'axios';
2
2
  import { useRouter } from 'vue-router';
3
3
  import { v4 } from 'uuid';
4
4
  import { useTimeoutFn, useBreakpoints, breakpointsTailwind, useWindowSize } from '@vueuse/core';
5
+ import { jwtDecode } from 'jwt-decode';
5
6
  import { useQuery } from '@tanstack/vue-query';
6
7
  import { ref, watch, onServerPrefetch, onMounted, computed } from 'vue';
7
- import { jwtDecode } from 'jwt-decode';
8
8
 
9
9
  /**
10
10
  * Enum defining available screen sizes.
@@ -539,7 +539,7 @@ function inferErrorType(error) {
539
539
  }
540
540
 
541
541
  let secretKey = "12345678901234567890123456789012";
542
- let tokensConfig$1 = Object.freeze({
542
+ let tokensConfig = Object.freeze({
543
543
  ACCESS_TOKEN: "access_token",
544
544
  REFRESH_TOKEN: "refresh_token",
545
545
  });
@@ -554,7 +554,7 @@ let tokensConfig$1 = Object.freeze({
554
554
  * @returns {void} Does not return anything, but freezes the token configuration object.
555
555
  */
556
556
  function configTokenKeys(config) {
557
- tokensConfig$1 = Object.freeze({
557
+ tokensConfig = Object.freeze({
558
558
  ACCESS_TOKEN: config.accessTokenKey,
559
559
  REFRESH_TOKEN: config.refreshTokenKey,
560
560
  });
@@ -565,7 +565,7 @@ function configTokenKeys(config) {
565
565
  * @returns {TokensConfig} The configuration of the access and refresh token keys.
566
566
  */
567
567
  function getTokenConfig() {
568
- return tokensConfig$1;
568
+ return tokensConfig;
569
569
  }
570
570
  /**
571
571
  * Sets the secret key for use in authentication.
@@ -2607,7 +2607,6 @@ async function getDecryptedItem(key, secretKey, isRememberMe) {
2607
2607
  }
2608
2608
  }
2609
2609
 
2610
- const tokensConfig = getTokenConfig();
2611
2610
  /**
2612
2611
  * Clears all stored authentication data (access and refresh tokens)
2613
2612
  * from either sessionStorage or localStorage based on the provided preference.
@@ -2616,6 +2615,7 @@ const tokensConfig = getTokenConfig();
2616
2615
  * @returns {Promise<void>} A promise that resolves when all relevant storage items are removed.
2617
2616
  */
2618
2617
  const cleanCredentials = async (preference) => {
2618
+ const tokensConfig = getTokenConfig();
2619
2619
  Object.keys(tokensConfig).forEach((key) => {
2620
2620
  const storage = preference === "session" ? sessionStorage : localStorage;
2621
2621
  storage.removeItem(tokensConfig[key]);
@@ -2630,6 +2630,7 @@ const cleanCredentials = async (preference) => {
2630
2630
  * @returns {Promise<string | null>} A promise that resolves with the decrypted access token, or null if not found.
2631
2631
  */
2632
2632
  const getAuthToken = async (secretKey, preference) => {
2633
+ const tokensConfig = getTokenConfig();
2633
2634
  return await getDecryptedItem(tokensConfig.ACCESS_TOKEN, secretKey, preference === "session");
2634
2635
  };
2635
2636
  /**
@@ -2641,6 +2642,7 @@ const getAuthToken = async (secretKey, preference) => {
2641
2642
  * @returns {Promise<string | null>} A promise that resolves with the decrypted refresh token, or null if not found.
2642
2643
  */
2643
2644
  const getAuthRefreshToken = async (secretKey, preference) => {
2645
+ const tokensConfig = getTokenConfig();
2644
2646
  return await getDecryptedItem(tokensConfig.REFRESH_TOKEN, secretKey, preference === "session");
2645
2647
  };
2646
2648
  /**
@@ -2653,6 +2655,7 @@ const getAuthRefreshToken = async (secretKey, preference) => {
2653
2655
  * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
2654
2656
  */
2655
2657
  const storeAuthToken = async (token, secretKey, preference) => {
2658
+ const tokensConfig = getTokenConfig();
2656
2659
  await storeEncryptedItem(tokensConfig.ACCESS_TOKEN, token, secretKey, preference === "session");
2657
2660
  };
2658
2661
  /**
@@ -2665,8 +2668,52 @@ const storeAuthToken = async (token, secretKey, preference) => {
2665
2668
  * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
2666
2669
  */
2667
2670
  const storeAuthRefreshToken = async (token, secretKey, preference) => {
2671
+ const tokensConfig = getTokenConfig();
2668
2672
  await storeEncryptedItem(tokensConfig.REFRESH_TOKEN, token, secretKey, preference === "session");
2669
2673
  };
2674
+ /**
2675
+ * Verifies the validity and expiration of the current authentication token.
2676
+ * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
2677
+ *
2678
+ * @param {string} secretKey - The secret key used for token decryption.
2679
+ * @param {SessionPreference} preference - The current session persistence preference.
2680
+ * @returns {Promise<boolean>} True if the token is valid and unexpired.
2681
+ * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
2682
+ * "TOKEN_INVALID" if the token format is invalid.
2683
+ */
2684
+ const verifyAuth = async (secretKey = getSecretKey(), preference = getSessionPersistencePreference()) => {
2685
+ try {
2686
+ const token = await getAuthToken(secretKey, preference);
2687
+ if (!token) {
2688
+ handleError("TOKEN_MISSING: No valid token found", false);
2689
+ await cleanCredentials(preference);
2690
+ return false;
2691
+ }
2692
+ const decoded = jwtDecode(token);
2693
+ const currentTime = Date.now() / 1000;
2694
+ if (typeof decoded.exp !== "number") {
2695
+ handleError("TOKEN_INVALID: Invalid expiration format", false);
2696
+ await cleanCredentials(preference);
2697
+ return false;
2698
+ }
2699
+ if (decoded.exp <= currentTime) {
2700
+ handleError("TOKEN_EXPIRED: Token is expired", false);
2701
+ await cleanCredentials(preference);
2702
+ return false;
2703
+ }
2704
+ return true;
2705
+ }
2706
+ catch (error) {
2707
+ if (error instanceof Error && error.message.includes("Invalid")) {
2708
+ handleError("TOKEN_INVALID: Invalid token format", false);
2709
+ await cleanCredentials(preference);
2710
+ return false;
2711
+ }
2712
+ handleError("AUTH_ERROR: An unexpected error occurred", false);
2713
+ await cleanCredentials(preference);
2714
+ return false;
2715
+ }
2716
+ };
2670
2717
 
2671
2718
  class RestStd {
2672
2719
  static resource;
@@ -3221,7 +3268,6 @@ function useSorter(items, criteriaList, selectedCriteria) {
3221
3268
 
3222
3269
  /**
3223
3270
  * @typedef {object} AuthHook
3224
- * @property {function(): Promise<string | null>} getJwt - Retrieves the current JWT.
3225
3271
  * @property {function(): Promise<number | null>} getTokenExpiry - Retrieves the expiration time of the current token in milliseconds.
3226
3272
  * @property {function(): Promise<void>} cleanCredentials - Clears authentication credentials from storage.
3227
3273
  * @property {(params?: AuthParams) => Promise<void>} logout - Logs out the user, clears credentials, and reloads the page.
@@ -3241,38 +3287,6 @@ function useAuth(secretKey = getSecretKey()) {
3241
3287
  const axiosInstance = getAxiosInstance();
3242
3288
  const endpoints = getEndpointsConfig();
3243
3289
  const currentPersistencePreference = getSessionPersistencePreference();
3244
- /**
3245
- * Retrieves the current JSON Web Token (JWT) from storage based on the active session preference.
3246
- *
3247
- * @returns {Promise<string | null>} The JWT string if found, otherwise null.
3248
- */
3249
- const getJwt = async () => {
3250
- try {
3251
- return await getAuthToken(secretKey, currentPersistencePreference);
3252
- }
3253
- catch (error) {
3254
- handleError("Error getting JWT: " + error, false);
3255
- return null;
3256
- }
3257
- };
3258
- /**
3259
- * Retrieves the expiration timestamp of the current authentication token in milliseconds.
3260
- *
3261
- * @returns {Promise<number | null>} The expiration timestamp in milliseconds if the token is valid, otherwise null.
3262
- */
3263
- const getTokenExpiry = async () => {
3264
- const token = await getJwt();
3265
- if (!token)
3266
- return null;
3267
- try {
3268
- const decoded = jwtDecode(token);
3269
- return decoded.exp ? decoded.exp * 1000 : null;
3270
- }
3271
- catch (error) {
3272
- handleError(`TOKEN_INVALID: Token verification failed (malformed or unreadable): ${error.message}`, false);
3273
- return null;
3274
- }
3275
- };
3276
3290
  /**
3277
3291
  * Logs out the user by making a POST request to the logout endpoint,
3278
3292
  * cleaning all stored credentials, and reloading the page.
@@ -3341,51 +3355,10 @@ function useAuth(secretKey = getSecretKey()) {
3341
3355
  throw error;
3342
3356
  }
3343
3357
  };
3344
- /**
3345
- * Verifies the validity and expiration of the current authentication token.
3346
- * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
3347
- *
3348
- * @returns {Promise<boolean>} True if the token is valid and unexpired.
3349
- * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
3350
- * "TOKEN_INVALID" if the token format is invalid.
3351
- */
3352
- const verifyAuth = async () => {
3353
- const token = await getJwt();
3354
- if (!token) {
3355
- handleError("TOKEN_MISSING: No valid token found", false);
3356
- await cleanCredentials(currentPersistencePreference);
3357
- throw new Error("TOKEN_MISSING: No valid token found");
3358
- }
3359
- try {
3360
- const decoded = jwtDecode(token);
3361
- const currentTime = Date.now() / 1000;
3362
- if (typeof decoded.exp !== "number") {
3363
- throw new Error("Invalid expiration format");
3364
- }
3365
- if (decoded.exp <= currentTime) {
3366
- handleError("TOKEN_EXPIRED: Token is expired", false);
3367
- await cleanCredentials(currentPersistencePreference);
3368
- throw new Error("TOKEN_EXPIRED: Token is expired");
3369
- }
3370
- return true;
3371
- }
3372
- catch (error) {
3373
- if (error instanceof Error && error.message.includes("Invalid")) {
3374
- handleError("TOKEN_INVALID: Invalid token format", false);
3375
- await cleanCredentials(currentPersistencePreference);
3376
- throw new Error("TOKEN_INVALID: Invalid token format");
3377
- }
3378
- throw error;
3379
- }
3380
- };
3381
3358
  return {
3382
- getJwt,
3383
- getTokenExpiry,
3384
- cleanCredentials,
3385
3359
  logout,
3386
3360
  login,
3387
- refresh,
3388
- verifyAuth
3361
+ refresh
3389
3362
  };
3390
3363
  }
3391
3364
 
@@ -3421,4 +3394,4 @@ const ArexVueCore = {
3421
3394
  },
3422
3395
  };
3423
3396
 
3424
- export { AppTypes, ArchiveTypes, ArexVueCore, AudioTypes, AxiosService, ContentTypeEnum, DocumentTypes, ERROR_MESSAGES, ERROR_STYLES, ErrorEnum, ErrorMessages, ErrorStyles, ExceptionEnum, FontTypes, ImageTypes, KeyCodeEnum, OtherTypes, RestStd, ScreenBreakpoint, ScreenSize, StorageKeyEnum, StorageTypeEnum, TextTypes, VideoTypes, ab2hex, addCustomKeyboardShortcut, addDays, addDoubleClickListener, addKeyListener, ageAtDate, axiosFetch, blobToFormData, bufferToBlob, calculateAge, cleanCredentials, clickOutside, compareObject, configAxios, configEndpoints, configSession, configTokenKeys, copyToClipboard, countWords, createCustomAxiosInstance, createFetch, createKeyMap, customShortcut, daysBetween, daysToNextBirthday, debounce, debounceAsync, debounceAsyncValidator, debounceAsyncWithImmediate, debounceLeading, debounceLeadingTrailing, debounceTrailing, decrypt, deepClone, deepEqual, deepMerge, detectKeyHold, disableCopy, disableF12Key, disableMouseButtons, disableRightClick, disableSpecificKeys, downloadBlob, enableMouseButtons, enableRightClick, enableSpecificKeys, encrypt, exportToCSV, exportToExcel, exportToJSON, exportToText, exportToXML, filterObjectByKeys, flattenObject, formDataToObject, formatDate, generateRandomString, getAuthRefreshToken, getAuthToken, getAxiosInstance, getDecryptedItem, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getQueryParam, getSecretKey, getSessionConfig, getSessionId, getSessionPersistencePreference, getStartOfMonth, getTokenConfig, handleError, hasNestedProperties, hex2ab, importKey, isEmptyObject, isLeapYear, isStrongPassword, isValidAge, isValidCreditCard, isValidDate, isValidEmail, isValidExpiryDate, isValidHexColor, isValidHexColorAlpha, isValidHexNumber, isValidIP, isValidPhoneNumber, isValidSSN, isValidTime, isValidURL, isValidUsername, isValidZIP, lowerFirst, objectToFormData, objectToFormDataEnhanced, objectToQueryString, openWindow, parseDate, proxyToPlainObject, readFileAsDataURL, readFileAsText, regenerateSessionId, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, reverseString, safeGet, screenMap, scrollToTop, setSecretKey, simulateKeyPress, stopDetectingKeyHold, storeAuthRefreshToken, storeAuthToken, storeEncryptedItem, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFilter, usePagination, useSorter, useVueQuery, validateAlphanumeric, validateLetters, validateNumbers };
3397
+ export { AppTypes, ArchiveTypes, ArexVueCore, AudioTypes, AxiosService, ContentTypeEnum, DocumentTypes, ERROR_MESSAGES, ERROR_STYLES, ErrorEnum, ErrorMessages, ErrorStyles, ExceptionEnum, FontTypes, ImageTypes, KeyCodeEnum, OtherTypes, RestStd, ScreenBreakpoint, ScreenSize, StorageKeyEnum, StorageTypeEnum, TextTypes, VideoTypes, ab2hex, addCustomKeyboardShortcut, addDays, addDoubleClickListener, addKeyListener, ageAtDate, axiosFetch, blobToFormData, bufferToBlob, calculateAge, cleanCredentials, clickOutside, compareObject, configAxios, configEndpoints, configSession, configTokenKeys, copyToClipboard, countWords, createCustomAxiosInstance, createFetch, createKeyMap, customShortcut, daysBetween, daysToNextBirthday, debounce, debounceAsync, debounceAsyncValidator, debounceAsyncWithImmediate, debounceLeading, debounceLeadingTrailing, debounceTrailing, decrypt, deepClone, deepEqual, deepMerge, detectKeyHold, disableCopy, disableF12Key, disableMouseButtons, disableRightClick, disableSpecificKeys, downloadBlob, enableMouseButtons, enableRightClick, enableSpecificKeys, encrypt, exportToCSV, exportToExcel, exportToJSON, exportToText, exportToXML, filterObjectByKeys, flattenObject, formDataToObject, formatDate, generateRandomString, getAuthRefreshToken, getAuthToken, getAxiosInstance, getDecryptedItem, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getQueryParam, getSecretKey, getSessionConfig, getSessionId, getSessionPersistencePreference, getStartOfMonth, getTokenConfig, handleError, hasNestedProperties, hex2ab, importKey, isEmptyObject, isLeapYear, isStrongPassword, isValidAge, isValidCreditCard, isValidDate, isValidEmail, isValidExpiryDate, isValidHexColor, isValidHexColorAlpha, isValidHexNumber, isValidIP, isValidPhoneNumber, isValidSSN, isValidTime, isValidURL, isValidUsername, isValidZIP, lowerFirst, objectToFormData, objectToFormDataEnhanced, objectToQueryString, openWindow, parseDate, proxyToPlainObject, readFileAsDataURL, readFileAsText, regenerateSessionId, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, reverseString, safeGet, screenMap, scrollToTop, setSecretKey, simulateKeyPress, stopDetectingKeyHold, storeAuthRefreshToken, storeAuthToken, storeEncryptedItem, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFilter, usePagination, useSorter, useVueQuery, validateAlphanumeric, validateLetters, validateNumbers, verifyAuth };
@@ -45,3 +45,14 @@ export declare const storeAuthToken: (token: string, secretKey: string, preferen
45
45
  * @returns {Promise<void>} A promise that resolves when the token is successfully stored.
46
46
  */
47
47
  export declare const storeAuthRefreshToken: (token: string, secretKey: string, preference: SessionPreference) => Promise<void>;
48
+ /**
49
+ * Verifies the validity and expiration of the current authentication token.
50
+ * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
51
+ *
52
+ * @param {string} secretKey - The secret key used for token decryption.
53
+ * @param {SessionPreference} preference - The current session persistence preference.
54
+ * @returns {Promise<boolean>} True if the token is valid and unexpired.
55
+ * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
56
+ * "TOKEN_INVALID" if the token format is invalid.
57
+ */
58
+ export declare const verifyAuth: (secretKey?: string, preference?: SessionPreference) => Promise<boolean>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arex95/vue-core",
3
- "version": "1.1.21",
3
+ "version": "1.1.23",
4
4
  "description": "Opinionated Vue Core",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",