Skip to content

Commit

Permalink
Merge pull request #212 from eleliauk/main
Browse files Browse the repository at this point in the history
token and magic
  • Loading branch information
eleliauk authored Dec 20, 2024
2 parents 093de80 + 4982e66 commit c5fe198
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 7 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
61 changes: 58 additions & 3 deletions src/common/utils/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
import Taro from '@tarojs/taro';

import { LoginResponseHeaders } from '../api/handleLogin';

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

const header = {
Expand All @@ -11,7 +13,42 @@ const getToken = async () => {
const res = await Taro.getStorage({ key: 'shortToken' });
if (res.data) return res.data;
void Taro.navigateTo({ url: '/pages/login/index' });
throw new Error(`Failed to get token: ${res.errMsg as unknown as string}`);
throw new Error(`没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('没longToken');
}

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'];
if (shortToken) {
await Taro.setStorage({ key: 'shortToken', data: shortToken.toString() });
}
}
throw new Error('刷新token失败');
} catch (error) {
void Taro.showToast({
title: '登录过期 请刷新小程序重新登录',
icon: 'error',
});
void Taro.navigateTo({ url: '/pages/login/index' });
throw error;
}
};

const request = async (
Expand All @@ -20,7 +57,7 @@ const request = async (
data = {},
isToken = true
) => {
const token = isToken ? `Bearer ${await getToken()}` : '';
let token = isToken ? `Bearer ${await getToken()}` : '';
header['Authorization'] = token ? `${token}` : '';

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

if (response.statusCode.toString().startsWith('2')) {
return response.data;
} else if (response.statusCode === 401) {
await refreshToken();
const newToken = await Taro.getStorage({ key: 'shortToken' });
token = `Bearer ${newToken.data}`;
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.toString());
} else {
const errorData = response.data as { code: number; msg: string };
throw new Error(response.statusCode === 401 ? '401' : `${errorData.code}`);
throw new Error(errorData.code.toString());
}
} catch (error) {
// eslint-disable-next-line no-console
Expand Down
34 changes: 33 additions & 1 deletion src/pages/classInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import LineChart from '@/common/components/chart';
import Label3 from '@/common/components/label3/label3';
import ShowStar from '@/common/components/showStar/showStar';
import { get, post } from '@/common/utils';
import { postBool } from '@/common/utils/fetch';

import { StatusResponse } from '../evaluate/evaluate';

const coursePropertyMap = {
CoursePropertyGeneralCore: '通识核心课',
Expand Down Expand Up @@ -43,6 +46,33 @@ export default function Index() {
const [questionNum, setQuestionNum] = useState<number>(0);
const [questionlist, setQuestionlist] = useState<WebQuestionVo[]>([]);
const [collect, setCollect] = useState<boolean | undefined>(course?.is_collected);
const [test, setTest] = useState<boolean>(false);
useEffect(() => {
const getParams = async () => {
try {
const res = (await postBool('/checkStatus', {
name: 'kestack',
})) as StatusResponse;

setTest(res.data.status);

// const instance = Taro.getCurrentInstance();
// const params = instance?.router?.params || {};

// setId(params.id ? Number(params.id) : null);
// setName(
// params.name ? decodeURIComponent(params.name) : '只能评价自己学过的课程哦'
// );
} catch (error) {
console.error('Error fetching status:', error);
}
};

void getParams();
}, []);
useEffect(() => {
console.log('test status updated:', test);
}, [test]);
const getCommentData = async () => {
try {
await get(
Expand Down Expand Up @@ -221,7 +251,9 @@ export default function Index() {
</View>
</View>
<>
{questionlist.length > 0 ? (
{!test ? (
<View>因为政策原因暂不能发布课评</View>
) : questionlist.length > 0 ? (
<>
<View className="relative">
{questionlist.slice(0, 3).map((question, index) => (
Expand Down
2 changes: 1 addition & 1 deletion src/pages/evaluate/evaluate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import Star from '@/common/components/star/star';
import { post } from '@/common/utils';
import { postBool } from '@/common/utils/fetch';

interface StatusResponse {
export interface StatusResponse {
code: number;
data: {
status: boolean;
Expand Down

0 comments on commit c5fe198

Please sign in to comment.