@arex95/vue-core 1.1.29 → 1.1.31
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.
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { AuthParams, AuthResponse, AuthTokenPaths } from "@/types";
|
|
2
|
-
import { SessionPreference } from "@config/global/sessionConfig";
|
|
1
|
+
import { AuthParams, AuthResponse, AuthTokenPaths, LocationPreference } from "@/types";
|
|
3
2
|
/**
|
|
4
3
|
* @typedef {object} AuthHook
|
|
5
4
|
* @property {function(): Promise<number | null>} getTokenExpiry - Retrieves the expiration time of the current token in milliseconds.
|
|
@@ -9,7 +8,7 @@ import { SessionPreference } from "@config/global/sessionConfig";
|
|
|
9
8
|
* @property {(tokenPaths?: AuthTokenPaths) => Promise<AuthResponse>} refresh - Refreshes authentication tokens.
|
|
10
9
|
* @property {function(): Promise<boolean>} verifyAuth - Verifies the validity and expiration of the current authentication token.
|
|
11
10
|
* @property {(preference: SessionPreference) => void} setSessionPersistencePreference - Sets the user's preferred storage for authentication data.
|
|
12
|
-
* @property {function(): SessionPreference}
|
|
11
|
+
* @property {function(): SessionPreference} getSessionPersistence - Retrieves the user's current preferred storage for authentication data.
|
|
13
12
|
*/
|
|
14
13
|
/**
|
|
15
14
|
* Custom hook for authentication logic, including login, logout, token management, and session preference.
|
|
@@ -19,6 +18,6 @@ import { SessionPreference } from "@config/global/sessionConfig";
|
|
|
19
18
|
*/
|
|
20
19
|
export declare function useAuth(secretKey?: string): {
|
|
21
20
|
logout: (params?: AuthParams) => Promise<void>;
|
|
22
|
-
login: (params: AuthParams, persistence:
|
|
21
|
+
login: (params: AuthParams, persistence: LocationPreference, tokenPaths?: AuthTokenPaths) => Promise<AuthResponse>;
|
|
23
22
|
refresh: (tokenPaths?: AuthTokenPaths) => Promise<AuthResponse>;
|
|
24
23
|
};
|
|
@@ -1,49 +1,34 @@
|
|
|
1
|
-
|
|
1
|
+
import { LocationPreference, SessionConfigObject, SessionConfig } from "@/types/SessionConfig";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
|
|
5
|
-
interface SessionConfigObject {
|
|
6
|
-
/** The unique session identifier. */
|
|
7
|
-
sessionId?: string;
|
|
8
|
-
/** The storage preference: 'local' for localStorage, 'session' for sessionStorage. */
|
|
9
|
-
persistencePreference?: SessionPreference;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Loads the session configuration from storage (local or session).
|
|
13
|
-
* This should be called once when the application initializes.
|
|
14
|
-
*/
|
|
15
|
-
export declare function loadSessionConfigFromStorage(): Promise<void>;
|
|
16
|
-
/**
|
|
17
|
-
* Configures the session identifier and/or the data persistence preference for the active browser session.
|
|
18
|
-
* Once configured, the session ID cannot be modified. The persistence preference can be updated.
|
|
3
|
+
* Configures the session identifier and/or data persistence preference
|
|
4
|
+
* for the active browser session.
|
|
19
5
|
*
|
|
20
|
-
*
|
|
6
|
+
* This function is asynchronous because it will always attempt to load the current configuration
|
|
7
|
+
* before applying changes and then saving them.
|
|
21
8
|
*
|
|
22
|
-
* @
|
|
9
|
+
* @param {SessionConfigObject} config - An object containing the unique session identifier and/or
|
|
10
|
+
* the persistence preference.
|
|
11
|
+
* @returns {Promise<void>} A promise that resolves when the session has been configured and saved.
|
|
23
12
|
*/
|
|
24
|
-
export declare function configSession(config: SessionConfigObject): void
|
|
13
|
+
export declare function configSession(config: SessionConfigObject): Promise<void>;
|
|
25
14
|
/**
|
|
26
|
-
* Retrieves the current session identifier
|
|
15
|
+
* Retrieves the current session identifier.
|
|
16
|
+
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
27
17
|
*
|
|
28
|
-
* @returns {string}
|
|
18
|
+
* @returns {Promise<string>} A promise that resolves with the unique session identifier.
|
|
29
19
|
*/
|
|
30
|
-
export declare function
|
|
20
|
+
export declare function getSessionId(): Promise<string>;
|
|
31
21
|
/**
|
|
32
22
|
* Retrieves the current data persistence preference.
|
|
23
|
+
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
33
24
|
*
|
|
34
|
-
* @returns {SessionPreference}
|
|
25
|
+
* @returns {Promise<SessionPreference>} A promise that resolves with the configured persistence preference ('local' or 'session').
|
|
35
26
|
*/
|
|
36
|
-
export declare function
|
|
27
|
+
export declare function getSessionPersistence(): Promise<LocationPreference>;
|
|
37
28
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* @returns {void} Does not return anything, but updates the session identifier.
|
|
41
|
-
*/
|
|
42
|
-
export declare function regenerateSessionId(): void;
|
|
43
|
-
/**
|
|
44
|
-
* Retrieves the current session identifier.
|
|
29
|
+
* Retrieves the complete session configuration.
|
|
30
|
+
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
45
31
|
*
|
|
46
|
-
* @returns {
|
|
32
|
+
* @returns {Promise<SessionConfig>} A promise that resolves with the session configuration object.
|
|
47
33
|
*/
|
|
48
|
-
export declare function
|
|
49
|
-
export {};
|
|
34
|
+
export declare function getSessionConfig(): Promise<SessionConfig>;
|
package/dist/index.mjs
CHANGED
|
@@ -866,14 +866,14 @@ async function decrypt(encryptedValue, secretKey) {
|
|
|
866
866
|
* @param key The key under which to store the value.
|
|
867
867
|
* @param value The value to encrypt and store.
|
|
868
868
|
* @param secretKey The secret key for encryption.
|
|
869
|
-
* @param
|
|
869
|
+
* @param location Determines where the item is stored: 'local' for localStorage, 'session' for sessionStorage.
|
|
870
870
|
* @returns A promise that resolves when the item is stored. Throws an error if it fails.
|
|
871
871
|
*/
|
|
872
|
-
async function storeEncryptedItem(key, value, secretKey,
|
|
872
|
+
async function storeEncryptedItem(key, value, secretKey, location) {
|
|
873
873
|
if (typeof window === "undefined") {
|
|
874
874
|
throw new Error("Cannot access storage: window is not defined.");
|
|
875
875
|
}
|
|
876
|
-
const storage =
|
|
876
|
+
const storage = location === "local" ? window.localStorage : window.sessionStorage;
|
|
877
877
|
const encryptedValue = await encrypt(value, secretKey);
|
|
878
878
|
storage.setItem(key, encryptedValue);
|
|
879
879
|
}
|
|
@@ -882,15 +882,20 @@ async function storeEncryptedItem(key, value, secretKey, persistent) {
|
|
|
882
882
|
* Assumes the `window` environment is available.
|
|
883
883
|
* @param key The key of the item to retrieve.
|
|
884
884
|
* @param secretKey The secret key for decryption.
|
|
885
|
-
* @param
|
|
885
|
+
* @param location Specifies where to search for the item: 'local' for localStorage, 'session' for sessionStorage, or 'any' to check both (session first).
|
|
886
886
|
* @returns A promise that resolves with the decrypted value or null if not found or decryption fails.
|
|
887
887
|
*/
|
|
888
|
-
async function getDecryptedItem(key, secretKey,
|
|
888
|
+
async function getDecryptedItem(key, secretKey, location) {
|
|
889
889
|
if (typeof window === "undefined") {
|
|
890
890
|
return null;
|
|
891
891
|
}
|
|
892
|
-
|
|
893
|
-
|
|
892
|
+
let encryptedData = null;
|
|
893
|
+
if (location === "session" || location === "any") {
|
|
894
|
+
encryptedData = window.sessionStorage.getItem(key);
|
|
895
|
+
}
|
|
896
|
+
if (!encryptedData && (location === "local" || location === "any")) {
|
|
897
|
+
encryptedData = window.localStorage.getItem(key);
|
|
898
|
+
}
|
|
894
899
|
if (!encryptedData) {
|
|
895
900
|
return null;
|
|
896
901
|
}
|
|
@@ -933,106 +938,110 @@ function getAppKey() {
|
|
|
933
938
|
return appKey;
|
|
934
939
|
}
|
|
935
940
|
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
941
|
+
const SESSION_KEY = "session_config_";
|
|
942
|
+
const internalSessionState = {
|
|
943
|
+
sessionId: v4(),
|
|
944
|
+
persistencePreference: "session",
|
|
945
|
+
};
|
|
946
|
+
let _sessionConfig = Object.freeze({
|
|
947
|
+
SESSION_ID: internalSessionState.sessionId,
|
|
948
|
+
PERSISTENCE: internalSessionState.persistencePreference,
|
|
939
949
|
});
|
|
940
|
-
let persistencePreference = "session";
|
|
941
950
|
/**
|
|
942
|
-
*
|
|
943
|
-
*
|
|
951
|
+
* Updates the immutable `_sessionConfig` object with the current state of `internalSessionState`
|
|
952
|
+
* and freezes it.
|
|
944
953
|
*/
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
const parsedConfig = JSON.parse(storedConfig);
|
|
951
|
-
sessionConfig = Object.freeze({
|
|
952
|
-
...sessionConfig,
|
|
953
|
-
...parsedConfig,
|
|
954
|
-
});
|
|
955
|
-
if (parsedConfig.SESSION_ID) {
|
|
956
|
-
sessionId = parsedConfig.SESSION_ID;
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
catch (error) {
|
|
960
|
-
console.error("Error parsing stored session config:", error);
|
|
961
|
-
regenerateSessionId();
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
else {
|
|
965
|
-
regenerateSessionId();
|
|
966
|
-
}
|
|
967
|
-
await saveSessionConfigToStorage();
|
|
954
|
+
function updateSessionConfig() {
|
|
955
|
+
_sessionConfig = Object.freeze({
|
|
956
|
+
SESSION_ID: internalSessionState.sessionId,
|
|
957
|
+
PERSISTENCE: internalSessionState.persistencePreference,
|
|
958
|
+
});
|
|
968
959
|
}
|
|
969
960
|
/**
|
|
970
961
|
* Saves the current session configuration to local or session storage.
|
|
962
|
+
* @returns {Promise<void>} A promise that resolves when the session configuration has been saved.
|
|
971
963
|
*/
|
|
972
|
-
async function
|
|
973
|
-
const
|
|
964
|
+
async function saveSessionConfig() {
|
|
965
|
+
const location = internalSessionState.persistencePreference;
|
|
974
966
|
try {
|
|
975
|
-
await storeEncryptedItem(
|
|
967
|
+
await storeEncryptedItem(SESSION_KEY, JSON.stringify(_sessionConfig), getAppKey(), location);
|
|
976
968
|
}
|
|
977
969
|
catch (error) {
|
|
978
|
-
console.error("Error saving session
|
|
970
|
+
console.error("Error saving session configuration to storage:", error);
|
|
979
971
|
}
|
|
980
972
|
}
|
|
981
973
|
/**
|
|
982
|
-
*
|
|
983
|
-
*
|
|
984
|
-
*
|
|
985
|
-
* @param {SessionConfigObject} config - An object containing the unique session identifier and/or persistence preference.
|
|
974
|
+
* Attempts to load the configuration from storage.
|
|
975
|
+
* If it fails or is not found, `internalSessionState` will retain its current values (initial or last configured).
|
|
976
|
+
* Then, it updates `_sessionConfig`.
|
|
986
977
|
*
|
|
987
|
-
* @returns {void}
|
|
988
|
-
*/
|
|
989
|
-
function
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
978
|
+
* @returns {Promise<void>} A promise that resolves when the state has been loaded and updated.
|
|
979
|
+
*/
|
|
980
|
+
async function loadSessionConfig() {
|
|
981
|
+
const location = internalSessionState.persistencePreference;
|
|
982
|
+
try {
|
|
983
|
+
const storedConfig = await getDecryptedItem(SESSION_KEY, getAppKey(), location);
|
|
984
|
+
if (storedConfig) {
|
|
985
|
+
const parsedConfig = JSON.parse(storedConfig);
|
|
986
|
+
internalSessionState.sessionId = parsedConfig.SESSION_ID;
|
|
987
|
+
internalSessionState.persistencePreference = parsedConfig.PERSISTENCE;
|
|
988
|
+
updateSessionConfig();
|
|
989
|
+
}
|
|
997
990
|
}
|
|
998
|
-
|
|
999
|
-
|
|
991
|
+
catch (error) {
|
|
992
|
+
console.warn(`Error loading or parsing from storage`, error);
|
|
1000
993
|
}
|
|
1001
|
-
sessionConfig = Object.freeze(updatedConfig);
|
|
1002
|
-
saveSessionConfigToStorage();
|
|
1003
994
|
}
|
|
1004
995
|
/**
|
|
1005
|
-
*
|
|
996
|
+
* Configures the session identifier and/or data persistence preference
|
|
997
|
+
* for the active browser session.
|
|
998
|
+
*
|
|
999
|
+
* This function is asynchronous because it will always attempt to load the current configuration
|
|
1000
|
+
* before applying changes and then saving them.
|
|
1006
1001
|
*
|
|
1007
|
-
* @
|
|
1002
|
+
* @param {SessionConfigObject} config - An object containing the unique session identifier and/or
|
|
1003
|
+
* the persistence preference.
|
|
1004
|
+
* @returns {Promise<void>} A promise that resolves when the session has been configured and saved.
|
|
1008
1005
|
*/
|
|
1009
|
-
function
|
|
1010
|
-
|
|
1006
|
+
async function configSession(config) {
|
|
1007
|
+
if (config.sessionId) {
|
|
1008
|
+
internalSessionState.sessionId = config.sessionId;
|
|
1009
|
+
}
|
|
1010
|
+
if (config.persistencePreference) {
|
|
1011
|
+
internalSessionState.persistencePreference = config.persistencePreference;
|
|
1012
|
+
}
|
|
1013
|
+
updateSessionConfig();
|
|
1014
|
+
await saveSessionConfig();
|
|
1011
1015
|
}
|
|
1012
1016
|
/**
|
|
1013
|
-
* Retrieves the current
|
|
1017
|
+
* Retrieves the current session identifier.
|
|
1018
|
+
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
1014
1019
|
*
|
|
1015
|
-
* @returns {
|
|
1020
|
+
* @returns {Promise<string>} A promise that resolves with the unique session identifier.
|
|
1016
1021
|
*/
|
|
1017
|
-
function
|
|
1018
|
-
|
|
1022
|
+
async function getSessionId() {
|
|
1023
|
+
await loadSessionConfig();
|
|
1024
|
+
return _sessionConfig.SESSION_ID;
|
|
1019
1025
|
}
|
|
1020
1026
|
/**
|
|
1021
|
-
*
|
|
1027
|
+
* Retrieves the current data persistence preference.
|
|
1028
|
+
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
1022
1029
|
*
|
|
1023
|
-
* @returns {
|
|
1030
|
+
* @returns {Promise<SessionPreference>} A promise that resolves with the configured persistence preference ('local' or 'session').
|
|
1024
1031
|
*/
|
|
1025
|
-
function
|
|
1026
|
-
|
|
1027
|
-
|
|
1032
|
+
async function getSessionPersistence() {
|
|
1033
|
+
await loadSessionConfig();
|
|
1034
|
+
return _sessionConfig.PERSISTENCE;
|
|
1028
1035
|
}
|
|
1029
1036
|
/**
|
|
1030
|
-
* Retrieves the
|
|
1037
|
+
* Retrieves the complete session configuration.
|
|
1038
|
+
* Always attempts to load the configuration from storage. If it fails, it uses the internal state.
|
|
1031
1039
|
*
|
|
1032
|
-
* @returns {
|
|
1040
|
+
* @returns {Promise<SessionConfig>} A promise that resolves with the session configuration object.
|
|
1033
1041
|
*/
|
|
1034
|
-
function
|
|
1035
|
-
|
|
1042
|
+
async function getSessionConfig() {
|
|
1043
|
+
await loadSessionConfig();
|
|
1044
|
+
return _sessionConfig;
|
|
1036
1045
|
}
|
|
1037
1046
|
|
|
1038
1047
|
/**
|
|
@@ -2699,16 +2708,21 @@ function isValidHexNumber(hex) {
|
|
|
2699
2708
|
|
|
2700
2709
|
/**
|
|
2701
2710
|
* Clears all stored authentication data (access and refresh tokens)
|
|
2702
|
-
* from either sessionStorage or
|
|
2711
|
+
* from either sessionStorage, localStorage, or both based on the provided location preference.
|
|
2703
2712
|
*
|
|
2704
|
-
* @param {
|
|
2713
|
+
* @param {LocationPreference} location - The storage preference ('local' for localStorage, 'session' for sessionStorage, 'any' for both).
|
|
2705
2714
|
* @returns {Promise<void>} A promise that resolves when all relevant storage items are removed.
|
|
2706
2715
|
*/
|
|
2707
|
-
const cleanCredentials = async (
|
|
2716
|
+
const cleanCredentials = async (location) => {
|
|
2708
2717
|
const tokensConfig = getTokenConfig();
|
|
2709
2718
|
Object.keys(tokensConfig).forEach((key) => {
|
|
2710
|
-
const
|
|
2711
|
-
|
|
2719
|
+
const itemKey = tokensConfig[key];
|
|
2720
|
+
if (location === "local" || location === "any") {
|
|
2721
|
+
localStorage.removeItem(itemKey);
|
|
2722
|
+
}
|
|
2723
|
+
if (location === "session" || location === "any") {
|
|
2724
|
+
sessionStorage.removeItem(itemKey);
|
|
2725
|
+
}
|
|
2712
2726
|
});
|
|
2713
2727
|
};
|
|
2714
2728
|
/**
|
|
@@ -2719,9 +2733,9 @@ const cleanCredentials = async (preference) => {
|
|
|
2719
2733
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
2720
2734
|
* @returns {Promise<string | null>} A promise that resolves with the decrypted access token, or null if not found.
|
|
2721
2735
|
*/
|
|
2722
|
-
const getAuthToken = async (secretKey,
|
|
2736
|
+
const getAuthToken = async (secretKey, location) => {
|
|
2723
2737
|
const tokensConfig = getTokenConfig();
|
|
2724
|
-
return await getDecryptedItem(tokensConfig.ACCESS_TOKEN, secretKey,
|
|
2738
|
+
return await getDecryptedItem(tokensConfig.ACCESS_TOKEN, secretKey, location);
|
|
2725
2739
|
};
|
|
2726
2740
|
/**
|
|
2727
2741
|
* Retrieves the authentication refresh token from storage, decrypting it
|
|
@@ -2731,9 +2745,9 @@ const getAuthToken = async (secretKey, preference) => {
|
|
|
2731
2745
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
2732
2746
|
* @returns {Promise<string | null>} A promise that resolves with the decrypted refresh token, or null if not found.
|
|
2733
2747
|
*/
|
|
2734
|
-
const getAuthRefreshToken = async (secretKey,
|
|
2748
|
+
const getAuthRefreshToken = async (secretKey, location) => {
|
|
2735
2749
|
const tokensConfig = getTokenConfig();
|
|
2736
|
-
return await getDecryptedItem(tokensConfig.REFRESH_TOKEN, secretKey,
|
|
2750
|
+
return await getDecryptedItem(tokensConfig.REFRESH_TOKEN, secretKey, location);
|
|
2737
2751
|
};
|
|
2738
2752
|
/**
|
|
2739
2753
|
* Stores the authentication token (access token) in storage after encrypting it,
|
|
@@ -2744,9 +2758,9 @@ const getAuthRefreshToken = async (secretKey, preference) => {
|
|
|
2744
2758
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
2745
2759
|
* @returns {Promise<void>} A promise that resolves when the token is successfully stored.
|
|
2746
2760
|
*/
|
|
2747
|
-
const storeAuthToken = async (token, secretKey,
|
|
2761
|
+
const storeAuthToken = async (token, secretKey, location) => {
|
|
2748
2762
|
const tokensConfig = getTokenConfig();
|
|
2749
|
-
await storeEncryptedItem(tokensConfig.ACCESS_TOKEN, token, secretKey,
|
|
2763
|
+
await storeEncryptedItem(tokensConfig.ACCESS_TOKEN, token, secretKey, location);
|
|
2750
2764
|
};
|
|
2751
2765
|
/**
|
|
2752
2766
|
* Stores the authentication refresh token in storage after encrypting it,
|
|
@@ -2757,52 +2771,50 @@ const storeAuthToken = async (token, secretKey, preference) => {
|
|
|
2757
2771
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
2758
2772
|
* @returns {Promise<void>} A promise that resolves when the token is successfully stored.
|
|
2759
2773
|
*/
|
|
2760
|
-
const storeAuthRefreshToken = async (token, secretKey,
|
|
2774
|
+
const storeAuthRefreshToken = async (token, secretKey, location) => {
|
|
2761
2775
|
const tokensConfig = getTokenConfig();
|
|
2762
|
-
await storeEncryptedItem(tokensConfig.REFRESH_TOKEN, token, secretKey,
|
|
2776
|
+
await storeEncryptedItem(tokensConfig.REFRESH_TOKEN, token, secretKey, location);
|
|
2763
2777
|
};
|
|
2764
2778
|
/**
|
|
2765
2779
|
* Verifies the validity and expiration of the current authentication token.
|
|
2766
2780
|
* If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
|
|
2767
2781
|
*
|
|
2768
|
-
* @param {string} secretKey - The secret key used for token decryption.
|
|
2769
|
-
* @param {SessionPreference} preference - The current session persistence preference.
|
|
2770
2782
|
* @returns {Promise<boolean>} True if the token is valid and unexpired.
|
|
2771
2783
|
* @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
|
|
2772
2784
|
* "TOKEN_INVALID" if the token format is invalid.
|
|
2773
2785
|
*/
|
|
2774
2786
|
const verifyAuth = async () => {
|
|
2775
|
-
const
|
|
2787
|
+
const sessionPersistence = 'any';
|
|
2788
|
+
const handleAuthError = async (message, shouldClean = true) => {
|
|
2789
|
+
handleError(message, false);
|
|
2790
|
+
if (shouldClean) {
|
|
2791
|
+
await cleanCredentials(sessionPersistence);
|
|
2792
|
+
}
|
|
2793
|
+
return false;
|
|
2794
|
+
};
|
|
2776
2795
|
try {
|
|
2777
|
-
const token = await getAuthToken(getAppKey(),
|
|
2796
|
+
const token = await getAuthToken(getAppKey(), sessionPersistence);
|
|
2778
2797
|
if (!token) {
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2798
|
+
return await handleAuthError("TOKEN_MISSING: No valid token found");
|
|
2799
|
+
}
|
|
2800
|
+
let decoded;
|
|
2801
|
+
try {
|
|
2802
|
+
decoded = jwtDecode(token);
|
|
2803
|
+
}
|
|
2804
|
+
catch (decodeError) {
|
|
2805
|
+
return await handleAuthError("TOKEN_INVALID: Invalid token format");
|
|
2782
2806
|
}
|
|
2783
|
-
const decoded = jwtDecode(token);
|
|
2784
2807
|
const currentTime = Date.now() / 1000;
|
|
2785
2808
|
if (typeof decoded.exp !== "number") {
|
|
2786
|
-
|
|
2787
|
-
await cleanCredentials(preference);
|
|
2788
|
-
return false;
|
|
2809
|
+
return await handleAuthError("TOKEN_INVALID: Invalid expiration format");
|
|
2789
2810
|
}
|
|
2790
2811
|
if (decoded.exp <= currentTime) {
|
|
2791
|
-
|
|
2792
|
-
await cleanCredentials(preference);
|
|
2793
|
-
return false;
|
|
2812
|
+
return await handleAuthError("TOKEN_EXPIRED: Token is expired");
|
|
2794
2813
|
}
|
|
2795
2814
|
return true;
|
|
2796
2815
|
}
|
|
2797
2816
|
catch (error) {
|
|
2798
|
-
|
|
2799
|
-
handleError("TOKEN_INVALID: Invalid token format", false);
|
|
2800
|
-
await cleanCredentials(preference);
|
|
2801
|
-
return false;
|
|
2802
|
-
}
|
|
2803
|
-
handleError("AUTH_ERROR: An unexpected error occurred", false);
|
|
2804
|
-
await cleanCredentials(preference);
|
|
2805
|
-
return false;
|
|
2817
|
+
return await handleAuthError("AUTH_ERROR: An unexpected error occurred", true);
|
|
2806
2818
|
}
|
|
2807
2819
|
};
|
|
2808
2820
|
|
|
@@ -3366,7 +3378,7 @@ function useSorter(items, criteriaList, selectedCriteria) {
|
|
|
3366
3378
|
* @property {(tokenPaths?: AuthTokenPaths) => Promise<AuthResponse>} refresh - Refreshes authentication tokens.
|
|
3367
3379
|
* @property {function(): Promise<boolean>} verifyAuth - Verifies the validity and expiration of the current authentication token.
|
|
3368
3380
|
* @property {(preference: SessionPreference) => void} setSessionPersistencePreference - Sets the user's preferred storage for authentication data.
|
|
3369
|
-
* @property {function(): SessionPreference}
|
|
3381
|
+
* @property {function(): SessionPreference} getSessionPersistence - Retrieves the user's current preferred storage for authentication data.
|
|
3370
3382
|
*/
|
|
3371
3383
|
/**
|
|
3372
3384
|
* Custom hook for authentication logic, including login, logout, token management, and session preference.
|
|
@@ -3377,7 +3389,6 @@ function useSorter(items, criteriaList, selectedCriteria) {
|
|
|
3377
3389
|
function useAuth(secretKey = getAppKey()) {
|
|
3378
3390
|
const axiosInstance = getAxiosInstance();
|
|
3379
3391
|
const endpoints = getEndpointsConfig();
|
|
3380
|
-
const currentPersistencePreference = getSessionPersistencePreference();
|
|
3381
3392
|
/**
|
|
3382
3393
|
* Logs out the user by making a POST request to the logout endpoint,
|
|
3383
3394
|
* cleaning all stored credentials, and reloading the page.
|
|
@@ -3394,7 +3405,7 @@ function useAuth(secretKey = getAppKey()) {
|
|
|
3394
3405
|
handleError(error, false);
|
|
3395
3406
|
}
|
|
3396
3407
|
finally {
|
|
3397
|
-
await cleanCredentials(
|
|
3408
|
+
await cleanCredentials(await getSessionPersistence());
|
|
3398
3409
|
window.location.reload();
|
|
3399
3410
|
}
|
|
3400
3411
|
};
|
|
@@ -3450,7 +3461,7 @@ function useAuth(secretKey = getAppKey()) {
|
|
|
3450
3461
|
*/
|
|
3451
3462
|
const refresh = async (tokenPaths) => {
|
|
3452
3463
|
try {
|
|
3453
|
-
const refreshTokenFromStorage = await getAuthRefreshToken(secretKey,
|
|
3464
|
+
const refreshTokenFromStorage = await getAuthRefreshToken(secretKey, await getSessionPersistence());
|
|
3454
3465
|
if (!refreshTokenFromStorage) {
|
|
3455
3466
|
throw new Error("TOKEN_MISSING: No refresh token found in storage.");
|
|
3456
3467
|
}
|
|
@@ -3472,8 +3483,8 @@ function useAuth(secretKey = getAppKey()) {
|
|
|
3472
3483
|
typeof refreshTokenAfterRefresh !== "string") {
|
|
3473
3484
|
throw new Error(`REFRESH_ERROR: Refresh token not found or invalid at path '${refreshTokenPath}' in refresh response.`);
|
|
3474
3485
|
}
|
|
3475
|
-
await storeAuthToken(accessTokenAfterRefresh, secretKey,
|
|
3476
|
-
await storeAuthRefreshToken(refreshTokenAfterRefresh, secretKey,
|
|
3486
|
+
await storeAuthToken(accessTokenAfterRefresh, secretKey, await getSessionPersistence());
|
|
3487
|
+
await storeAuthRefreshToken(refreshTokenAfterRefresh, secretKey, await getSessionPersistence());
|
|
3477
3488
|
return data;
|
|
3478
3489
|
}
|
|
3479
3490
|
catch (error) {
|
|
@@ -3524,4 +3535,4 @@ const ArexVueCore = {
|
|
|
3524
3535
|
},
|
|
3525
3536
|
};
|
|
3526
3537
|
|
|
3527
|
-
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, configAppKey, 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, getAppKey, getAuthRefreshToken, getAuthToken, getAxiosInstance, getDecryptedItem, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getQueryParam, getSessionConfig, getSessionId,
|
|
3538
|
+
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, configAppKey, 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, getAppKey, getAuthRefreshToken, getAuthToken, getAxiosInstance, getDecryptedItem, getEndOfMonth, getEndpointsConfig, getObjectDifferences, getObjectKeys, getQueryParam, getSessionConfig, getSessionId, getSessionPersistence, 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, registerKeyboardShortcuts, removeAccent, removeClickOutside, removeCustomKeyboardShortcut, removeCustomShortcuts, removeDoubleClickListener, removeEmptyProperties, removeKeyListeners, replaceAll, reverseString, safeGet, screenMap, scrollToTop, simulateKeyPress, stopDetectingKeyHold, storeAuthRefreshToken, storeAuthToken, storeEncryptedItem, stringToBlob, subtractDays, throttle, toCamelCase, toKebabCase, toggleTabNavigation, truncateString, unregisterKeyboardShortcuts, upperFirst, useAuth, useBreakpoint, useFilter, usePagination, useSorter, useVueQuery, validateAlphanumeric, validateLetters, validateNumbers, verifyAuth };
|
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
export type LocationPreference = "local" | "session" | "any";
|
|
1
2
|
export type SessionConfig = {
|
|
2
3
|
SESSION_ID: string;
|
|
4
|
+
PERSISTENCE: LocationPreference;
|
|
3
5
|
};
|
|
6
|
+
export interface InternalSessionState {
|
|
7
|
+
sessionId: string;
|
|
8
|
+
persistencePreference: LocationPreference;
|
|
9
|
+
}
|
|
10
|
+
export interface SessionConfigObject {
|
|
11
|
+
sessionId?: string;
|
|
12
|
+
persistencePreference?: LocationPreference;
|
|
13
|
+
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { LocationPreference } from "@/types/SessionConfig";
|
|
2
2
|
/**
|
|
3
3
|
* Clears all stored authentication data (access and refresh tokens)
|
|
4
|
-
* from either sessionStorage or
|
|
4
|
+
* from either sessionStorage, localStorage, or both based on the provided location preference.
|
|
5
5
|
*
|
|
6
|
-
* @param {
|
|
6
|
+
* @param {LocationPreference} location - The storage preference ('local' for localStorage, 'session' for sessionStorage, 'any' for both).
|
|
7
7
|
* @returns {Promise<void>} A promise that resolves when all relevant storage items are removed.
|
|
8
8
|
*/
|
|
9
|
-
export declare const cleanCredentials: (
|
|
9
|
+
export declare const cleanCredentials: (location: LocationPreference) => Promise<void>;
|
|
10
10
|
/**
|
|
11
11
|
* Retrieves the authentication token (access token) from storage, decrypting it
|
|
12
12
|
* using the provided secret key and based on the specified session preference.
|
|
@@ -15,7 +15,7 @@ export declare const cleanCredentials: (preference: SessionPreference) => Promis
|
|
|
15
15
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
16
16
|
* @returns {Promise<string | null>} A promise that resolves with the decrypted access token, or null if not found.
|
|
17
17
|
*/
|
|
18
|
-
export declare const getAuthToken: (secretKey: string,
|
|
18
|
+
export declare const getAuthToken: (secretKey: string, location: LocationPreference) => Promise<string | null>;
|
|
19
19
|
/**
|
|
20
20
|
* Retrieves the authentication refresh token from storage, decrypting it
|
|
21
21
|
* using the provided secret key and based on the specified session preference.
|
|
@@ -24,7 +24,7 @@ export declare const getAuthToken: (secretKey: string, preference: SessionPrefer
|
|
|
24
24
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
25
25
|
* @returns {Promise<string | null>} A promise that resolves with the decrypted refresh token, or null if not found.
|
|
26
26
|
*/
|
|
27
|
-
export declare const getAuthRefreshToken: (secretKey: string,
|
|
27
|
+
export declare const getAuthRefreshToken: (secretKey: string, location: LocationPreference) => Promise<string | null>;
|
|
28
28
|
/**
|
|
29
29
|
* Stores the authentication token (access token) in storage after encrypting it,
|
|
30
30
|
* based on the specified session preference.
|
|
@@ -34,7 +34,7 @@ export declare const getAuthRefreshToken: (secretKey: string, preference: Sessio
|
|
|
34
34
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
35
35
|
* @returns {Promise<void>} A promise that resolves when the token is successfully stored.
|
|
36
36
|
*/
|
|
37
|
-
export declare const storeAuthToken: (token: string, secretKey: string,
|
|
37
|
+
export declare const storeAuthToken: (token: string, secretKey: string, location: LocationPreference) => Promise<void>;
|
|
38
38
|
/**
|
|
39
39
|
* Stores the authentication refresh token in storage after encrypting it,
|
|
40
40
|
* based on the specified session preference.
|
|
@@ -44,13 +44,11 @@ export declare const storeAuthToken: (token: string, secretKey: string, preferen
|
|
|
44
44
|
* @param {SessionPreference} preference - The storage preference ('local' for localStorage, 'session' for sessionStorage).
|
|
45
45
|
* @returns {Promise<void>} A promise that resolves when the token is successfully stored.
|
|
46
46
|
*/
|
|
47
|
-
export declare const storeAuthRefreshToken: (token: string, secretKey: string,
|
|
47
|
+
export declare const storeAuthRefreshToken: (token: string, secretKey: string, location: LocationPreference) => Promise<void>;
|
|
48
48
|
/**
|
|
49
49
|
* Verifies the validity and expiration of the current authentication token.
|
|
50
50
|
* If the token is missing, invalid, or expired, appropriate errors are thrown and credentials are cleaned.
|
|
51
51
|
*
|
|
52
|
-
* @param {string} secretKey - The secret key used for token decryption.
|
|
53
|
-
* @param {SessionPreference} preference - The current session persistence preference.
|
|
54
52
|
* @returns {Promise<boolean>} True if the token is valid and unexpired.
|
|
55
53
|
* @throws {Error} "TOKEN_MISSING" if no token is found, "TOKEN_EXPIRED" if the token has expired,
|
|
56
54
|
* "TOKEN_INVALID" if the token format is invalid.
|
package/dist/utils/storage.d.ts
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
|
+
import { LocationPreference } from "@/types";
|
|
1
2
|
/**
|
|
2
3
|
* Encrypts and stores an item in local or session storage.
|
|
3
4
|
* Assumes the `window` environment is available.
|
|
4
5
|
* @param key The key under which to store the value.
|
|
5
6
|
* @param value The value to encrypt and store.
|
|
6
7
|
* @param secretKey The secret key for encryption.
|
|
7
|
-
* @param
|
|
8
|
+
* @param location Determines where the item is stored: 'local' for localStorage, 'session' for sessionStorage.
|
|
8
9
|
* @returns A promise that resolves when the item is stored. Throws an error if it fails.
|
|
9
10
|
*/
|
|
10
|
-
export declare function storeEncryptedItem(key: string, value: string, secretKey: string,
|
|
11
|
+
export declare function storeEncryptedItem(key: string, value: string, secretKey: string, location: LocationPreference): Promise<void>;
|
|
11
12
|
/**
|
|
12
13
|
* Retrieves and decrypts a value from local or session storage.
|
|
13
14
|
* Assumes the `window` environment is available.
|
|
14
15
|
* @param key The key of the item to retrieve.
|
|
15
16
|
* @param secretKey The secret key for decryption.
|
|
16
|
-
* @param
|
|
17
|
+
* @param location Specifies where to search for the item: 'local' for localStorage, 'session' for sessionStorage, or 'any' to check both (session first).
|
|
17
18
|
* @returns A promise that resolves with the decrypted value or null if not found or decryption fails.
|
|
18
19
|
*/
|
|
19
|
-
export declare function getDecryptedItem(key: string, secretKey: string,
|
|
20
|
+
export declare function getDecryptedItem(key: string, secretKey: string, location: LocationPreference): Promise<string | null>;
|