Skip to content

Commit

Permalink
feat(token):解决登录过期问题
Browse files Browse the repository at this point in the history
  • Loading branch information
eleliauk committed Dec 20, 2024
1 parent 6ae43bd commit 5828f70
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/common/api/handleLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Taro from '@tarojs/taro';

const preUrl = 'https://kstack.muxixyz.com';

type LoginResponseHeaders = {
export type LoginResponseHeaders = {
'X-Jwt-Token'?: string;
'X-Refresh-Token'?: string;
};
Expand Down
2 changes: 1 addition & 1 deletion src/common/components/QuestionDetail/QuestionDetail.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import '@/common/components/QuestionDetail/QuestionDetail';
import { Button, Image, Text, Textarea, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect, useState } from 'react';

import answericon from '@/common/assets/img/publishQuestion/answer.png';
Expand All @@ -8,7 +9,6 @@ import IconFont from '@/common/components/iconfont';
import PublishHeader from '@/common/components/PublishHeader/PublishHeader';
import { get, post } from '@/common/utils';
import { useCourseStore } from '@/pages/main/store/store';
import Taro from '@tarojs/taro';

interface IUser {
avatar: string;
Expand Down
55 changes: 53 additions & 2 deletions src/common/utils/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,46 @@ const getToken = async () => {
throw new Error(`Failed to get token: ${res.errMsg as unknown as string}`);
};

const refreshToken = async () => {
try {
const longToken = await Taro.getStorage({ key: 'longToken' });
if (!longToken.data) {
void Taro.navigateTo({ url: '/pages/login/index' });
throw new Error('No long token found');
}

const response = await Taro.request({
url: `${preUrl}/users/refresh_token`,
method: 'GET',
header: {
...header,
Authorization: `Bearer ${longToken.data}`,
},
});

if (response.statusCode.toString().startsWith('2')) {
const headers: LoginResponseHeaders = response.header || {};
const shortToken = headers['X-Jwt-Token'];
//const longToken = headers['X-Refresh-Token'];
if (shortToken && longToken) {
await Taro.setStorage({ key: 'shortToken', data: shortToken });
// await Taro.setStorage({ key: 'longToken', data: longToken });
}
}
throw new Error('Failed to refresh token');
} catch (error) {
void Taro.navigateTo({ url: '/pages/login/index' });
throw error;
}
};

const request = async (
url = '',
method: 'GET' | 'POST' = 'GET',
data = {},
isToken = true
) => {
const token = isToken ? `Bearer ${await getToken()}` : '';
let token = isToken ? `Bearer ${await getToken()}` : '';
header['Authorization'] = token ? `${token}` : '';

try {
Expand All @@ -33,9 +66,27 @@ const request = async (

if (response.statusCode.toString().startsWith('2')) {
return response.data;
} else if (response.statusCode === 401) {
// Token 过期,尝试刷新
const newToken = await refreshToken();
token = `Bearer ${newToken}`;
header['Authorization'] = token;

// 使用新 token 重试请求
const retryResponse = await Taro.request({
url: `${preUrl}${url}`,
method,
header,
data: method === 'POST' ? JSON.stringify(data) : data,
});

if (retryResponse.statusCode.toString().startsWith('2')) {
return retryResponse.data;
}
throw new Error(`${retryResponse.statusCode}`);
} else {
const errorData = response.data as { code: number; msg: string };
throw new Error(response.statusCode === 401 ? '401' : `${errorData.code}`);
throw new Error(`${errorData.code}`);
}
} catch (error) {
// eslint-disable-next-line no-console
Expand Down

0 comments on commit 5828f70

Please sign in to comment.