Skip to content

Commit 3caf9ff

Browse files
authored
feat: add custom auth request client (#9)
1 parent b8fd034 commit 3caf9ff

File tree

10 files changed

+86
-137
lines changed

10 files changed

+86
-137
lines changed

apps/web-antd/index.html

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,6 @@
1414
<!-- 由 vite 注入 VITE_APP_TITLE 变量,在 .env 文件内配置 -->
1515
<title><%= VITE_APP_TITLE %></title>
1616
<link rel="icon" href="/favicon.ico" />
17-
<script>
18-
// 生产环境下注入百度统计
19-
if (window._VBEN_ADMIN_PRO_APP_CONF_) {
20-
var _hmt = _hmt || [];
21-
(function () {
22-
var hm = document.createElement('script');
23-
hm.src =
24-
'https://hm.baidu.com/hm.js?b38e689f40558f20a9a686d7f6f33edf';
25-
var s = document.getElementsByTagName('script')[0];
26-
s.parentNode.insertBefore(hm, s);
27-
})();
28-
}
29-
</script>
3017
</head>
3118
<body>
3219
<div id="app"></div>

apps/web-antd/src/api/auth.ts

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { baseRequestClient, requestClient } from '#/api/request';
1+
import {
2+
authRequestClient,
3+
baseRequestClient,
4+
requestClient,
5+
} from '#/api/request';
26

37
export interface CaptchaResult {
48
image: string;
@@ -15,10 +19,7 @@ export interface LoginResult {
1519
access_token: string;
1620
}
1721

18-
export interface RefreshTokenResult {
19-
data: string;
20-
status: number;
21-
}
22+
export type RefreshTokenResult = LoginResult;
2223

2324
/**
2425
* 登录验证码
@@ -38,16 +39,19 @@ export async function loginApi(data: LoginParams) {
3839
* 刷新accessToken
3940
*/
4041
export async function refreshTokenApi() {
41-
return baseRequestClient.post<RefreshTokenResult>('/api/v1/token/new', {
42-
withCredentials: true,
43-
});
42+
return baseRequestClient.post<RefreshTokenResult>('/api/v1/token/new');
4443
}
4544

4645
/**
4746
* 退出登录
4847
*/
4948
export async function logoutApi() {
50-
return baseRequestClient.post('/api/v1/auth/logout', {
51-
withCredentials: true,
52-
});
49+
return authRequestClient.post('/api/v1/auth/logout');
50+
}
51+
52+
/**
53+
* 获取用户权限码
54+
*/
55+
export async function getAccessCodesApi() {
56+
return [];
5357
}

apps/web-antd/src/api/request.ts

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ import { refreshTokenApi } from '.';
2121

2222
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
2323

24+
function formatToken(token: null | string) {
25+
return token ? `Bearer ${token}` : null;
26+
}
27+
2428
function createRequestClient(baseURL: string, options?: RequestClientOptions) {
2529
const client = new RequestClient({
2630
...options,
@@ -51,15 +55,11 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
5155
async function doRefreshToken() {
5256
const accessStore = useAccessStore();
5357
const resp = await refreshTokenApi();
54-
const newToken = resp.data;
58+
const newToken = resp.access_token;
5559
accessStore.setAccessToken(newToken);
5660
return newToken;
5761
}
5862

59-
function formatToken(token: null | string) {
60-
return token ? `Bearer ${token}` : null;
61-
}
62-
6363
// 请求头处理
6464
client.addRequestInterceptor({
6565
fulfilled: async (config) => {
@@ -95,7 +95,7 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
9595
client.addResponseInterceptor(
9696
errorMessageResponseInterceptor((msg: string, error) => {
9797
const responseData = error?.response?.data ?? {};
98-
const errorMessage = responseData?.msg ?? '';
98+
const errorMessage = responseData?.error ?? responseData?.msg ?? '';
9999
// 如果没有错误信息,则会根据状态码进行提示
100100
message.error(errorMessage || msg);
101101
}),
@@ -104,8 +104,40 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
104104
return client;
105105
}
106106

107+
function createAuthRequestClient(
108+
baseURL: string,
109+
options?: RequestClientOptions,
110+
) {
111+
const client = new RequestClient({
112+
...options,
113+
baseURL,
114+
});
115+
116+
// 请求头处理
117+
client.addRequestInterceptor({
118+
fulfilled: async (config) => {
119+
const accessStore = useAccessStore();
120+
121+
config.headers.Authorization = formatToken(accessStore.accessToken);
122+
config.headers['Accept-Language'] = preferences.app.locale;
123+
return config;
124+
},
125+
});
126+
127+
return client;
128+
}
129+
107130
export const requestClient = createRequestClient(apiURL, {
108131
responseReturn: 'data',
109132
});
110133

111-
export const baseRequestClient = new RequestClient({ baseURL: apiURL });
134+
export const authRequestClient = createAuthRequestClient(apiURL, {
135+
withCredentials: true,
136+
responseReturn: 'data',
137+
});
138+
139+
export const baseRequestClient = new RequestClient({
140+
baseURL: apiURL,
141+
withCredentials: true,
142+
responseReturn: 'data',
143+
});

apps/web-antd/src/api/user.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1-
import type { MyUserInfo } from '#/types';
1+
import type { UserInfo } from '@vben/types';
22

33
import { requestClient } from '#/api/request';
44

5+
export interface MyUserInfo extends UserInfo {
6+
id: number;
7+
nickname: string;
8+
}
9+
510
/**
611
* 获取用户信息
712
*/

apps/web-antd/src/router/routes/modules/vben.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,30 @@
11
import type { RouteRecordRaw } from 'vue-router';
22

33
import { IFrameView } from '#/layouts';
4-
import { $t } from '#/locales';
54

65
const routes: RouteRecordRaw[] = [
76
{
87
meta: {
98
badgeType: 'dot',
109
icon: 'https://wu-clan.github.io/picx-images-hosting/logo/fba.png',
1110
order: 9998,
12-
title: $t('demos.vben.title'),
11+
title: '项目',
1312
},
1413
name: 'VbenProject',
1514
path: '/fba-admin',
1615
children: [
1716
{
18-
name: 'VbenDocument',
17+
name: 'Document',
1918
path: '/fba-admin/document',
2019
component: IFrameView,
2120
meta: {
2221
icon: 'lucide:book-open-text',
2322
link: 'https://fastapi-practices.github.io/fastapi_best_architecture_docs',
24-
title: $t('demos.vben.document'),
23+
title: '文档',
2524
},
2625
},
2726
{
28-
name: 'VbenGithub',
27+
name: 'Github',
2928
path: '/fba-admin/github',
3029
component: IFrameView,
3130
meta: {
@@ -42,7 +41,7 @@ const routes: RouteRecordRaw[] = [
4241
component: () => import('#/views/_core/about/index.vue'),
4342
meta: {
4443
icon: 'lucide:copyright',
45-
title: $t('demos.vben.about'),
44+
title: '关于项目',
4645
order: 9999,
4746
},
4847
},

apps/web-antd/src/store/auth.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1-
import type { CaptchaResult } from '#/api';
2-
import type { MyUserInfo } from '#/types';
1+
import type { CaptchaResult, LoginParams, MyUserInfo } from '#/api';
32

43
import { ref } from 'vue';
54
import { useRouter } from 'vue-router';
65

76
import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
8-
import { resetAllStores, useAccessStore } from '@vben/stores';
7+
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
98

109
import { notification } from 'ant-design-vue';
1110
import { defineStore } from 'pinia';
1211

13-
import { getCaptchaApi, getUserInfoApi, loginApi, logoutApi } from '#/api';
12+
import {
13+
getAccessCodesApi,
14+
getCaptchaApi,
15+
getUserInfoApi,
16+
loginApi,
17+
logoutApi,
18+
} from '#/api';
1419
import { $t } from '#/locales';
1520

16-
import { myUseUserStore } from '.';
17-
1821
export const useAuthStore = defineStore('auth', () => {
1922
const accessStore = useAccessStore();
20-
const userStore = myUseUserStore();
23+
const userStore = useUserStore();
2124
const router = useRouter();
2225

2326
const loginLoading = ref(false);
2427

25-
/** 登陆验证码 */
28+
/**
29+
* 登陆验证码
30+
*/
2631
async function captcha() {
2732
const res: CaptchaResult = await getCaptchaApi();
2833
return res.image;
@@ -34,7 +39,7 @@ export const useAuthStore = defineStore('auth', () => {
3439
* @param params 登录表单数据
3540
*/
3641
async function authLogin(
37-
params: any,
42+
params: LoginParams,
3843
onSuccess?: () => Promise<void> | void,
3944
) {
4045
// 异步处理用户登录操作并获取 accessToken
@@ -48,9 +53,15 @@ export const useAuthStore = defineStore('auth', () => {
4853
accessStore.setAccessToken(access_token);
4954

5055
// 获取用户信息并存储到 accessStore 中
51-
userInfo = userInfo = await Promise.resolve(fetchUserInfo());
56+
const [fetchUserInfoResult, accessCodes] = await Promise.all([
57+
fetchUserInfo(),
58+
getAccessCodesApi(),
59+
]);
60+
61+
userInfo = fetchUserInfoResult;
5262

5363
userStore.setUserInfo(userInfo);
64+
accessStore.setAccessCodes(accessCodes);
5465

5566
if (accessStore.loginExpired) {
5667
accessStore.setLoginExpired(false);

apps/web-antd/src/store/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
export * from './auth';
2-
export * from './user';

apps/web-antd/src/store/user.ts

Lines changed: 0 additions & 65 deletions
This file was deleted.

apps/web-antd/src/types/index.ts

Lines changed: 0 additions & 1 deletion
This file was deleted.

apps/web-antd/src/types/user.ts

Lines changed: 0 additions & 22 deletions
This file was deleted.

0 commit comments

Comments
 (0)