@arex95/vue-core 1.1.21 → 1.1.22

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.
@@ -2667,6 +2667,49 @@ const storeAuthToken = async (token, secretKey, preference) => {
2667
2667
  const storeAuthRefreshToken = async (token, secretKey, preference) => {
2668
2668
  await storeEncryptedItem(tokensConfig.REFRESH_TOKEN, token, secretKey, preference === "session");
2669
2669
  };
2670
+ /**
2671
+ * Verifies the validity and expiration of the current authentication token.
2672
+ * If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
2673
+ *
2674
+ * @param {string} secretKey - The secret key used for token decryption.
2675
+ * @param {SessionPreference} preference - The current session persistence preference.
2676
+ * @returns {Promise<boolean>} True if the token is valid and unexpired.
2677
+ * @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
2678
+ * "TOKEN_INVALID" if the token format is invalid.
2679
+ */
2680
+ const verifyAuth = async (secretKey = getSecretKey(), preference = getSessionPersistencePreference()) => {
2681
+ try {
2682
+ const token = await getAuthToken(secretKey, preference);
2683
+ if (!token) {
2684
+ handleError("TOKEN_MISSING: No valid token found", false);
2685
+ await cleanCredentials(preference);
2686
+ return false;
2687
+ }
2688
+ const decoded = jwtDecode(token);
2689
+ const currentTime = Date.now() / 1000;
2690
+ if (typeof decoded.exp !== "number") {
2691
+ handleError("TOKEN_INVALID: Invalid expiration format", false);
2692
+ await cleanCredentials(preference);
2693
+ return false;
2694
+ }
2695
+ if (decoded.exp <= currentTime) {
2696
+ handleError("TOKEN_EXPIRED: Token is expired", false);
2697
+ await cleanCredentials(preference);
2698
+ return false;
2699
+ }
2700
+ return true;
2701
+ }
2702
+ catch (error) {
2703
+ if (error instanceof Error && error.message.includes("Invalid")) {
2704
+ handleError("TOKEN_INVALID: Invalid token format", false);
2705
+ await cleanCredentials(preference);
2706
+ return false;
2707
+ }
2708
+ handleError("AUTH_ERROR: An unexpected error occurred", false);
2709
+ await cleanCredentials(preference);
2710
+ return false;
2711
+ }
2712
+ };
2670
2713
 
2671
2714
  class RestStd {
2672
2715
  static resource;
@@ -3221,7 +3264,6 @@ function useSorter(items, criteriaList, selectedCriteria) {
3221
3264
 
3222
3265
  /**
3223
3266
  * @typedef {object} AuthHook
3224
- * @property {function(): Promise<string | null>} getJwt - Retrieves the current JWT.
3225
3267
  * @property {function(): Promise<number | null>} getTokenExpiry - Retrieves the expiration time of the current token in milliseconds.
3226
3268
  * @property {function(): Promise<void>} cleanCredentials - Clears authentication credentials from storage.
3227
3269
  * @property {(params?: AuthParams) => Promise<void>} logout - Logs out the user, clears credentials, and reloads the page.
@@ -3241,38 +3283,6 @@ function useAuth(secretKey = getSecretKey()) {
3241
3283
  const axiosInstance = getAxiosInstance();
3242
3284
  const endpoints = getEndpointsConfig();
3243
3285
  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
3286
  /**
3277
3287
  * Logs out the user by making a POST request to the logout endpoint,
3278
3288
  * cleaning all stored credentials, and reloading the page.
@@ -3341,51 +3351,10 @@ function useAuth(secretKey = getSecretKey()) {
3341
3351
  throw error;
3342
3352
  }
3343
3353
  };
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
3354
  return {
3382
- getJwt,
3383
- getTokenExpiry,
3384
- cleanCredentials,
3385
3355
  logout,
3386
3356
  login,
3387
- refresh,
3388
- verifyAuth
3357
+ refresh
3389
3358
  };
3390
3359
  }
3391
3360
 
@@ -3421,4 +3390,4 @@ const ArexVueCore = {
3421
3390
  },
3422
3391
  };
3423
3392
 
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 };
3393
+ 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.22",
4
4
  "description": "Opinionated Vue Core",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",