@fluxo-dev/api-client-base 1.0.0 β†’ 25.1.2

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/index.cjs.js CHANGED
@@ -2867,118 +2867,231 @@ class FluxoStateDispatcher {
2867
2867
  }
2868
2868
  }
2869
2869
 
2870
+ // Costanti per la gestione del refresh token
2871
+ const REFRESH_TOKEN_SAFETY_MARGIN_MS = 30000; // 30 secondi prima della scadenza
2870
2872
  class AuthService {
2871
2873
  constructor() {
2872
- RefreshTokenManager.Init(this.refreshToken, this.logout);
2874
+ this.isRefreshingToken = false;
2875
+ console.log("πŸ” AuthService: Inizializzazione");
2876
+ RefreshTokenManager.Init(() => this.refreshToken(), () => this.logout());
2873
2877
  }
2874
2878
  setup() {
2875
2879
  return __awaiter(this, void 0, void 0, function* () {
2880
+ console.log("πŸ” AuthService: Setup iniziato");
2876
2881
  yield this.tryAutoLogin();
2882
+ console.log("πŸ” AuthService: Setup completato");
2877
2883
  });
2878
2884
  }
2879
2885
  tryAutoLogin() {
2880
2886
  return __awaiter(this, void 0, void 0, function* () {
2887
+ console.log("πŸ” AuthService: Tentativo di auto-login");
2881
2888
  const accessToken = localStorage.getItem(LocalStorageConstants.accessToken);
2882
- if (accessToken) {
2889
+ if (!accessToken) {
2890
+ console.log("πŸ” AuthService: Nessun access token trovato in localStorage, eseguo logout");
2891
+ this.logout();
2892
+ return;
2893
+ }
2894
+ try {
2895
+ console.log("πŸ” AuthService: Access token trovato, decodifica in corso");
2883
2896
  const decoded = o(accessToken);
2884
2897
  if (!decoded) {
2898
+ console.log("πŸ” AuthService: Decodifica del token fallita, eseguo logout");
2885
2899
  this.logout();
2886
2900
  return;
2887
2901
  }
2888
- if (decoded.exp <= new Date().getTime() / 1000) {
2902
+ const currentTimeInSeconds = Math.floor(Date.now() / 1000);
2903
+ console.log(`πŸ” AuthService: Token exp: ${decoded.exp}, ora attuale (sec): ${currentTimeInSeconds}`);
2904
+ if (decoded.exp <= currentTimeInSeconds) {
2905
+ console.log("πŸ” AuthService: Token scaduto, richiedo refresh");
2889
2906
  yield this.refreshToken();
2890
2907
  } else {
2891
- // Avvio il timeout indicando il tempo di attesa come scadenza token - 30 secondi.
2892
- // pertanto, 30 secondi prima della scadenza del token, Fluxo richiederΓ  un nuovo token grazie al refresh token.
2893
- RefreshTokenManager.Instance.start(AuthService.getJwtTokenRemainingLifetime() - 30000);
2908
+ console.log("πŸ” AuthService: Token valido, calcolo tempo rimanente");
2909
+ // Avvio il timeout 30 secondi prima della scadenza del token
2910
+ const remainingLifetimeMs = AuthService.getJwtTokenRemainingLifetime();
2911
+ if (remainingLifetimeMs) {
2912
+ const timeoutMs = remainingLifetimeMs - REFRESH_TOKEN_SAFETY_MARGIN_MS;
2913
+ console.log(`πŸ” AuthService: Tempo rimanente: ${remainingLifetimeMs}ms, imposto refresh tra ${timeoutMs}ms`);
2914
+ RefreshTokenManager.Instance.start(timeoutMs);
2915
+ } else {
2916
+ console.log("πŸ” AuthService: Impossibile calcolare tempo rimanente per il token");
2917
+ }
2894
2918
  }
2895
- FluxoStateDispatcher.dispatchAutoLoginSucceded(localStorage.getItem(LocalStorageConstants.userData));
2919
+ const userData = localStorage.getItem(LocalStorageConstants.userData);
2920
+ if (userData) {
2921
+ console.log("πŸ” AuthService: Dati utente trovati, dispatch auto-login riuscito");
2922
+ FluxoStateDispatcher.dispatchAutoLoginSucceded(userData);
2923
+ } else {
2924
+ console.log("πŸ” AuthService: Dati utente mancanti nel localStorage");
2925
+ }
2926
+ } catch (error) {
2927
+ console.error("πŸ” AuthService: Errore durante l'auto-login", error);
2928
+ // Se c'Γ¨ un errore nel decodificare il token, facciamo logout
2929
+ this.logout();
2896
2930
  }
2897
2931
  });
2898
2932
  }
2899
2933
  login(username, password) {
2900
2934
  return __awaiter(this, void 0, void 0, function* () {
2935
+ console.log(`πŸ” AuthService: Tentativo di login per utente: ${username}`);
2901
2936
  try {
2902
- const data = yield HttpClient.Instance().client.post('/identity/authenticate', {
2937
+ console.log("πŸ” AuthService: Invio richiesta di autenticazione");
2938
+ const response = yield HttpClient.Instance().client.post('/identity/authenticate', {
2903
2939
  username,
2904
2940
  password
2905
2941
  }, {
2906
2942
  withCredentials: true
2907
2943
  });
2944
+ const data = response;
2945
+ console.log("πŸ” AuthService: Login riuscito, token ricevuto");
2908
2946
  localStorage.setItem(LocalStorageConstants.accessToken, data.token);
2909
2947
  localStorage.setItem(LocalStorageConstants.userData, JSON.stringify(data.userData));
2910
- RefreshTokenManager.Instance.start(AuthService.getJwtTokenRemainingLifetime() - 60);
2948
+ console.log("πŸ” AuthService: Token e dati utente salvati in localStorage");
2949
+ const remainingLifetimeMs = AuthService.getJwtTokenRemainingLifetime();
2950
+ if (remainingLifetimeMs) {
2951
+ const timeoutMs = remainingLifetimeMs - REFRESH_TOKEN_SAFETY_MARGIN_MS;
2952
+ console.log(`πŸ” AuthService: Imposto refresh token tra ${timeoutMs}ms`);
2953
+ RefreshTokenManager.Instance.start(timeoutMs);
2954
+ } else {
2955
+ console.log("πŸ” AuthService: Impossibile calcolare tempo rimanente per il token");
2956
+ }
2957
+ console.log("πŸ” AuthService: Dispatch evento login utente");
2911
2958
  FluxoStateDispatcher.dispatchUserLogin({
2912
2959
  data
2913
2960
  });
2914
- } catch (err) {
2961
+ return true;
2962
+ } catch (error) {
2963
+ console.error("πŸ” AuthService: Errore durante il login", error);
2915
2964
  FluxoStateDispatcher.dispatchUserLogin(null);
2965
+ return false;
2916
2966
  }
2917
2967
  });
2918
2968
  }
2919
2969
  logout() {
2970
+ console.log("πŸ” AuthService: Esecuzione logout");
2920
2971
  RefreshTokenManager.Instance.stop();
2921
2972
  localStorage.removeItem(LocalStorageConstants.accessToken);
2922
2973
  localStorage.removeItem(LocalStorageConstants.userData);
2974
+ console.log("πŸ” AuthService: Token e dati utente rimossi da localStorage");
2975
+ console.log("πŸ” AuthService: Dispatch evento logout utente");
2923
2976
  FluxoStateDispatcher.dispatchUserLogout();
2924
2977
  }
2925
2978
  refreshToken() {
2926
2979
  return __awaiter(this, void 0, void 0, function* () {
2980
+ console.log("πŸ” AuthService: Tentativo di refresh token");
2981
+ // Previeni multiple richieste di refresh contemporaneamente
2982
+ if (this.isRefreshingToken) {
2983
+ console.log("πŸ” AuthService: Refresh giΓ  in corso, richiesta ignorata");
2984
+ return false;
2985
+ }
2986
+ this.isRefreshingToken = true;
2987
+ console.log("πŸ” AuthService: Flag isRefreshingToken impostato a true");
2927
2988
  try {
2928
- const data = yield HttpClient.Instance().client.post('/identity/refresh-token', {}, {
2989
+ console.log("πŸ” AuthService: Invio richiesta di refresh token");
2990
+ const response = yield HttpClient.Instance().client.post('/identity/refresh-token', {}, {
2929
2991
  withCredentials: true
2930
2992
  });
2993
+ const data = response;
2994
+ console.log("πŸ” AuthService: Refresh token riuscito, nuovo token ricevuto");
2931
2995
  localStorage.setItem(LocalStorageConstants.accessToken, data.token);
2932
2996
  localStorage.setItem(LocalStorageConstants.userData, JSON.stringify(data.userData));
2997
+ console.log("πŸ” AuthService: Nuovo token e dati utente salvati in localStorage");
2933
2998
  RefreshTokenManager.Instance.stop();
2934
- RefreshTokenManager.Instance.start(AuthService.getJwtTokenRemainingLifetime() - 10000);
2935
- } catch (err) {
2936
- localStorage.removeItem(LocalStorageConstants.accessToken);
2937
- localStorage.removeItem(LocalStorageConstants.userData);
2999
+ console.log("πŸ” AuthService: Timeout precedente fermato");
3000
+ const remainingLifetimeMs = AuthService.getJwtTokenRemainingLifetime();
3001
+ if (remainingLifetimeMs) {
3002
+ const timeoutMs = remainingLifetimeMs - REFRESH_TOKEN_SAFETY_MARGIN_MS;
3003
+ console.log(`πŸ” AuthService: Imposto nuovo refresh token tra ${timeoutMs}ms`);
3004
+ RefreshTokenManager.Instance.start(timeoutMs);
3005
+ } else {
3006
+ console.log("πŸ” AuthService: Impossibile calcolare tempo rimanente per il nuovo token");
3007
+ }
3008
+ this.isRefreshingToken = false;
3009
+ console.log("πŸ” AuthService: Flag isRefreshingToken reimpostato a false");
3010
+ return true;
3011
+ } catch (error) {
3012
+ console.error("πŸ” AuthService: Errore durante il refresh token", error);
3013
+ this.isRefreshingToken = false;
3014
+ console.log("πŸ” AuthService: Flag isRefreshingToken reimpostato a false dopo errore");
2938
3015
  this.logout();
3016
+ return false;
2939
3017
  }
2940
3018
  });
2941
3019
  }
2942
3020
  static getJwtTokenRemainingLifetime() {
3021
+ console.log("πŸ” AuthService: Calcolo tempo rimanente del token");
2943
3022
  const token = localStorage.getItem(LocalStorageConstants.accessToken);
2944
3023
  if (!token) {
2945
- throw new Error('Called getJwtTokenRemainingLifetime but no access token found');
3024
+ console.warn('πŸ” AuthService: Called getJwtTokenRemainingLifetime but no access token found');
3025
+ return null;
3026
+ }
3027
+ try {
3028
+ const decoded = o(token);
3029
+ const expTimeInSeconds = decoded.exp;
3030
+ const currentTimeInMs = Date.now();
3031
+ const expTimeInMs = expTimeInSeconds * 1000;
3032
+ const diffMs = expTimeInMs - currentTimeInMs;
3033
+ console.log(`πŸ” AuthService: Token scade in ${diffMs}ms (${Math.round(diffMs / 1000 / 60)} minuti)`);
3034
+ return diffMs <= 0 ? 0 : diffMs;
3035
+ } catch (error) {
3036
+ console.error('πŸ” AuthService: Error decoding JWT token', error);
3037
+ return null;
2946
3038
  }
2947
- const decoded = o(token);
2948
- const exp = +decoded.exp;
2949
- const dateNow = new Date(Date.now()).getTime();
2950
- const diff = exp * 1000 - dateNow;
2951
- return diff <= 0 ? 0 : diff;
2952
3039
  }
2953
3040
  }
2954
3041
  class RefreshTokenManager {
2955
- constructor(action, onErrorCallback) {
2956
- this.event = new Event('build');
2957
- this._refreshTokenInterval = null;
2958
- this._actionOnTimeout = action;
3042
+ constructor(refreshAction, onErrorCallback) {
3043
+ this._refreshTokenTimeout = null;
3044
+ console.log("πŸ”„ RefreshTokenManager: Inizializzazione");
3045
+ this._refreshTokenAction = refreshAction;
2959
3046
  this._onErrorCallback = onErrorCallback;
2960
3047
  }
2961
- static Init(actionOnTimeout, onErrorCallback) {
2962
- this._instance = new this(actionOnTimeout, onErrorCallback);
3048
+ static Init(refreshAction, onErrorCallback) {
3049
+ console.log("πŸ”„ RefreshTokenManager: Init chiamato");
3050
+ if (!this._instance) {
3051
+ console.log("πŸ”„ RefreshTokenManager: Creazione nuova istanza");
3052
+ this._instance = new RefreshTokenManager(refreshAction, onErrorCallback);
3053
+ } else {
3054
+ console.log("πŸ”„ RefreshTokenManager: Istanza giΓ  esistente");
3055
+ }
2963
3056
  }
2964
3057
  static get Instance() {
2965
- if (!this._instance) throw new Error('RefreshTokenManager not initialized');
3058
+ if (!this._instance) {
3059
+ console.error("πŸ”„ RefreshTokenManager: Tentativo di accesso all'istanza prima dell'inizializzazione");
3060
+ throw new Error('RefreshTokenManager not initialized');
3061
+ }
2966
3062
  return this._instance;
2967
3063
  }
2968
3064
  start(timeoutMs) {
2969
- console.info(' - start refresh token:' + timeoutMs + 'ms');
2970
- if (this._actionOnTimeout === undefined) throw new Error('RefreshTokenManager not initialized');
2971
- this._refreshTokenInterval = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
3065
+ // Arrotonda il timeout a un valore positivo
3066
+ const safeTimeoutMs = Math.max(1000, Math.floor(timeoutMs));
3067
+ console.log(`πŸ”„ RefreshTokenManager: Avvio refresh token in: ${safeTimeoutMs}ms (${Math.round(safeTimeoutMs / 1000 / 60)} minuti)`);
3068
+ // Assicuriamoci di fermare qualsiasi timeout precedente
3069
+ this.stop();
3070
+ this._refreshTokenTimeout = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
3071
+ console.log("πŸ”„ RefreshTokenManager: Timeout scaduto, esecuzione refresh token");
2972
3072
  try {
2973
- yield this._actionOnTimeout();
2974
- } catch (err) {
3073
+ const success = yield this._refreshTokenAction();
3074
+ console.log(`πŸ”„ RefreshTokenManager: Refresh token completato con ${success ? 'successo' : 'fallimento'}`);
3075
+ if (!success) {
3076
+ console.log("πŸ”„ RefreshTokenManager: Chiamata callback di errore");
3077
+ this._onErrorCallback();
3078
+ }
3079
+ } catch (error) {
3080
+ console.error('πŸ”„ RefreshTokenManager: Errore durante refresh token', error);
3081
+ console.log("πŸ”„ RefreshTokenManager: Chiamata callback di errore dopo eccezione");
2975
3082
  this._onErrorCallback();
2976
3083
  }
2977
- }), timeoutMs);
3084
+ }), safeTimeoutMs);
2978
3085
  }
2979
3086
  stop() {
2980
- console.info(' - stop refresh token');
2981
- clearInterval(this._refreshTokenInterval);
3087
+ console.log('πŸ”„ RefreshTokenManager: Stop refresh token');
3088
+ if (this._refreshTokenTimeout) {
3089
+ console.log('πŸ”„ RefreshTokenManager: Cancellazione timeout esistente');
3090
+ clearTimeout(this._refreshTokenTimeout);
3091
+ this._refreshTokenTimeout = null;
3092
+ } else {
3093
+ console.log('πŸ”„ RefreshTokenManager: Nessun timeout attivo da cancellare');
3094
+ }
2982
3095
  }
2983
3096
  }
2984
3097
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluxo-dev/api-client-base",
3
- "version": "1.0.0",
3
+ "version": "25.1.2",
4
4
  "type": "commonjs",
5
5
  "peerDependencies": {
6
6
  "react": "^18.3.1",
@@ -8,7 +8,7 @@
8
8
  "react-router-dom": "^6.11.2",
9
9
  "react-redux": "^8.0.5",
10
10
  "@reduxjs/toolkit": "^1.9.1",
11
- "@fluxo-dev/state": "^1.0.0"
11
+ "@fluxo-dev/state": "^25.1.2"
12
12
  },
13
13
  "main": "./index.cjs.js",
14
14
  "types": "./index.cjs.d.ts"
@@ -1,9 +1,10 @@
1
1
  export declare class AuthService {
2
+ private isRefreshingToken;
2
3
  constructor();
3
4
  setup(): Promise<void>;
4
5
  private tryAutoLogin;
5
- login(username: string, password: string): Promise<any>;
6
+ login(username: string, password: string): Promise<boolean>;
6
7
  logout(): void;
7
- refreshToken(): Promise<any>;
8
+ refreshToken(): Promise<boolean>;
8
9
  static getJwtTokenRemainingLifetime(): number | null;
9
10
  }