# All files / src/hooks useTokenManager.ts

74.54% Statements 82/110
54.76% Branches 23/42
63.15% Functions 12/19
78.64% Lines 81/103

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213

    1x
    1x
    1x
    1x

    3x
    3x
    3x

    3x
    8x
    8x
    8x
    8x

    8x
    8x

    3x
    2x
    2x

    2x
    2x

    3x
    2x
    2x

    2x
    2x
    2x

    3x
    4x
    4x

    4x
    4x

    3x
    4x
    4x
    4x
    2x
    2x

    1x
    1x
    1x

    1x

    1x
    1x
    1x

    1x

    3x
    4x
    2x
    2x

    3x
    4x

    4x
    4x

    3x

    3x
    3x
    3x

    1x

    2x
    2x
    2x

    3x
    2x
    2x

    2x

    2x

    1x

    2x

    3x
    2x
    2x
    2x

    2x
    2x
    2x
    2x
    1x

    2x

    2x

    3x

    3x

    3x

     'use client';

    import { useEffect, useCallback, useRef } from 'react';
    import { useRouter } from 'next/navigation';
    import { authService } from '@/services';
    import { STORAGE_KEYS } from '@/constants';

    export interface TokenPayload {
      sub: string;
      device_id?: string | null;
      exp: number;
      iat: number;
      role: string;
      username: string;
    }

    export function useTokenManager() {
      const router = useRouter();
      const refreshTimeoutRef = useRef<NodeJS.Timeout | null>(null);

      // Decode JWT token
      const decodeToken = useCallback((token: string): TokenPayload | null => {
        try {
          const payloadPart = token.split('.')[1];
          Iif (!payloadPart) return null;
          const paddedPayload = payloadPart
            .replace(/-/g, '+')
            .replace(/_/g, '/')
            .padEnd(Math.ceil(payloadPart.length / 4) * 4, '=');
          const payload = JSON.parse(atob(paddedPayload));
          return payload;
        } catch {
          return null;
        }
      }, []);

      // Check if token is expired
      const isTokenExpired = useCallback((token: string): boolean => {
        const payload = decodeToken(token);
        Iif (!payload) return true;

        const currentTime = Date.now() / 1000;
        return payload.exp < currentTime;
      }, [decodeToken]);

      // Check if token will expire soon (within 5 minutes)
      const isTokenExpiringSoon = useCallback((token: string): boolean => {
        const payload = decodeToken(token);
        Iif (!payload) return true;

        const currentTime = Date.now() / 1000;
        const fiveMinutes = 5 * 60;
        return payload.exp < (currentTime + fiveMinutes);
      }, [decodeToken]);

      // Get time until token expires
      const getTimeUntilExpiry = useCallback((token: string): number => {
        const payload = decodeToken(token);
        Iif (!payload) return 0;

        const currentTime = Date.now() / 1000;
        return Math.max(0, payload.exp - currentTime);
      }, [decodeToken]);

      // Refresh token
      const refreshToken = useCallback(async (): Promise<boolean> => {
        try {
          const result = await authService.refreshToken();
          if (result.success) {
            authService.setAuthToken(result.data.token);
            return true;
          }
          // If refresh fails, clear auth data
          authService.clearStoredUser();
          Eif (typeof window !== 'undefined') {
            localStorage.removeItem('iptv_auth_token');
          }
          return false;
        } catch {
          // Clear auth data on any error
          authService.clearStoredUser();
          Eif (typeof window !== 'undefined') {
            localStorage.removeItem('iptv_auth_token');
          }
          return false;
        }
      }, []);

      // Clear refresh timeout
      const clearRefreshTimeout = useCallback(() => {
        if (refreshTimeoutRef.current) {
          clearTimeout(refreshTimeoutRef.current);
          refreshTimeoutRef.current = null;
        }
      }, []);

      // Schedule token refresh
      const scheduleTokenRefresh = useCallback((token: string) => {
        clearRefreshTimeout();

        const timeUntilExpiry = getTimeUntilExpiry(token);
        if (timeUntilExpiry <= 0) return;

        // Schedule refresh 2 minutes before expiry
        const refreshTime = Math.max(0, (timeUntilExpiry - 120) * 1000);

        refreshTimeoutRef.current = setTimeout(async () => {
          const success = await refreshToken();
          if (!success) {
            // Refresh failed, clear auth and let higher-level guards decide navigation
            authService.clearStoredUser();
          } else {
            // Schedule next refresh
            const newToken = localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
            Eif (newToken) {
              scheduleTokenRefresh(newToken);
            }
          }
        }, refreshTime);
      }, [getTimeUntilExpiry, refreshToken, clearRefreshTimeout, router]);

      // Validate current token
      const validateToken = useCallback(async (): Promise<boolean> => {
        const token = localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
        Iif (!token) return false;

        Iif (isTokenExpired(token)) {
          // Token is expired, try to refresh
          const success = await refreshToken();
          if (!success) {
            authService.clearStoredUser();
            localStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
            return false;
          }
          return true;
        }

        if (isTokenExpiringSoon(token)) {
          // Token is expiring soon, refresh proactively
          await refreshToken();
        }

        return true;
      }, [isTokenExpired, isTokenExpiringSoon, refreshToken]);

      // Initialize token management
      useEffect(() => {
        const initTokenManager = async () => {
          const token = localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
          Iif (!token) return;

          const isValid = await validateToken();
          Eif (isValid) {
            const currentToken = localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
            if (currentToken) {
              scheduleTokenRefresh(currentToken);
            }
          }
        };

        initTokenManager();

        // Cleanup on unmount
        return () => {
          clearRefreshTimeout();
        };
      }, [validateToken, scheduleTokenRefresh, clearRefreshTimeout]);

      // Listen for storage changes (multiple tabs)
      useEffect(() => {
        const handleStorageChange = (e: StorageEvent) => {
          if (e.key === STORAGE_KEYS.AUTH_TOKEN) {
            if (e.newValue) {
              // Token was updated in another tab
              scheduleTokenRefresh(e.newValue);
            } else {
              // Token was removed in another tab; stop refresh scheduling
              clearRefreshTimeout();
            }
          }
        };

        window.addEventListener('storage', handleStorageChange);
        return () => {
          window.removeEventListener('storage', handleStorageChange);
        };
      }, [scheduleTokenRefresh, clearRefreshTimeout, router]);

      // Listen for page visibility changes
      useEffect(() => {
        const handleVisibilityChange = async () => {
          if (document.visibilityState === 'visible') {
            // Page became visible, validate token (do not auto-redirect here)
            await validateToken();
          }
        };

        document.addEventListener('visibilitychange', handleVisibilityChange);
        return () => {
          document.removeEventListener('visibilitychange', handleVisibilityChange);
        };
      }, [validateToken, router]);

      return {
        decodeToken,
        isTokenExpired,
        isTokenExpiringSoon,
        getTimeUntilExpiry,
        refreshToken,
        validateToken,
        scheduleTokenRefresh};
    }