San3yuan | a2ee30b | 2025-06-05 21:20:17 +0800 | [diff] [blame^] | 1 | import { getRefreshToken } from '@/api/auth'; |
| 2 | import axios from 'axios'; |
| 3 | |
| 4 | function parseJwt(token: string) { |
| 5 | console.log('Parsing JWT token:', token); |
| 6 | try { |
| 7 | const base64Url = token.split('.')[1]; |
| 8 | const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); |
| 9 | const jsonPayload = decodeURIComponent( |
| 10 | atob(base64) |
| 11 | .split('') |
| 12 | .map(c => `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`) |
| 13 | .join('') |
| 14 | ); |
| 15 | return JSON.parse(jsonPayload); |
| 16 | } catch (error) { |
| 17 | console.error('Invalid JWT token:', error); |
| 18 | return null; |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * 检查token是否过期 |
| 24 | * @returns {string} -1: token无效 0: token未过期 1: token已过期 |
| 25 | **/ |
| 26 | export function isTokenExpired(token: string): string { |
| 27 | if (token === null || token === undefined) { |
| 28 | return '-1'; // 如果没有token,认为token无效 |
| 29 | } |
| 30 | const decoded = parseJwt(token); |
| 31 | if (!decoded || !decoded.exp) { |
| 32 | return '-1'; // 如果解析失败或没有 `exp` 字段,认为token无效 |
| 33 | } |
| 34 | const currentTime = Math.floor(Date.now() / 1000); // 当前时间(秒) |
| 35 | const bufferTime = 60 * 10; // 过期前的缓冲时间(秒) |
| 36 | return decoded.exp < currentTime ?decoded.exp < currentTime - bufferTime ? '-1' : '1' :"0"; |
| 37 | } |
| 38 | |
| 39 | async function refreshToken() { |
| 40 | try { |
| 41 | const response = await axios.post(getRefreshToken, { |
| 42 | token: localStorage.getItem('token'), |
| 43 | }); |
| 44 | const newToken = response.data.token; |
| 45 | localStorage.setItem('token', newToken); |
| 46 | return newToken; |
| 47 | } catch (error) { |
| 48 | console.error('Failed to refresh token:', error); |
| 49 | return null; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | export async function checkAndRefreshToken() { |
| 54 | const token = localStorage.getItem('token'); |
| 55 | if (token && isTokenExpired(token)=='1') { |
| 56 | const newToken = await refreshToken(); |
| 57 | if (!newToken) { |
| 58 | localStorage.removeItem('token'); |
| 59 | } |
| 60 | } |
| 61 | } |