Compare commits

...

2 Commits

Author SHA1 Message Date
a1935f4008 fix: 对齐租户端鉴权与后端菜单流程
将登录/用户信息/权限/菜单接口对齐到租户后端,补充默认租户头与令牌刷新逻辑,并强制使用后端菜单模式以保证登录后触发 /auth/menu 加载。
2026-02-06 12:40:55 +08:00
09b73076da chore: 默认仅启用 web-antd 应用入口
默认 dev/build/preview 统一指向 web-antd。\nworkspace 仅保留 web-antd 与 backend-mock。
2026-02-06 10:48:08 +08:00
12 changed files with 198 additions and 104 deletions

View File

@@ -4,10 +4,13 @@ VITE_PORT=5666
VITE_BASE=/
# 接口地址
VITE_GLOB_API_URL=/api
VITE_GLOB_API_URL=https://api-tenant-dev.laosankeji.com/api/tenant/v1
# 可选:默认租户标识(若登录不使用 账号@手机号,可在此配置)
VITE_TENANT_ID=806357433394921472
# 是否开启 Nitro Mock服务true 为开启false 为关闭
VITE_NITRO_MOCK=true
VITE_NITRO_MOCK=false
# 是否打开 devtoolstrue 为打开false 为关闭
VITE_DEVTOOLS=false

View File

@@ -1,20 +1,43 @@
import { baseRequestClient, requestClient } from '#/api/request';
export namespace AuthApi {
export interface CurrentUserProfile {
account?: string;
avatar?: string;
displayName?: string;
merchantId?: null | number | string;
permissions?: string[];
roles?: string[];
tenantId?: number | string;
userId?: number | string;
}
/** 登录接口参数 */
export interface LoginParams {
account?: string;
password?: string;
username?: string;
}
/** 登录接口返回值 */
export interface LoginResult {
accessToken: string;
accessToken?: string;
accessTokenExpiresAt?: string;
isNewUser?: boolean;
refreshToken?: string;
refreshTokenExpiresAt?: string;
user?: CurrentUserProfile;
}
export interface RefreshTokenResult {
data: string;
status: number;
export interface RefreshTokenParams {
refreshToken: string;
}
export interface ApiResponse<T> {
code: number;
data: T;
message?: string;
success: boolean;
}
}
@@ -22,30 +45,33 @@ export namespace AuthApi {
* 登录
*/
export async function loginApi(data: AuthApi.LoginParams) {
return requestClient.post<AuthApi.LoginResult>('/auth/login', data);
const account = data.account ?? data.username;
return requestClient.post<AuthApi.LoginResult>('/auth/login', {
account,
password: data.password,
});
}
/**
* 刷新accessToken
*/
export async function refreshTokenApi() {
return baseRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
withCredentials: true,
});
export async function refreshTokenApi(data: AuthApi.RefreshTokenParams) {
return baseRequestClient.post<AuthApi.ApiResponse<AuthApi.LoginResult>>(
'/auth/refresh',
data,
);
}
/**
* 退出登录
*/
export async function logoutApi() {
return baseRequestClient.post('/auth/logout', {
withCredentials: true,
});
return baseRequestClient.post('/auth/logout');
}
/**
* 获取用户权限码
*/
export async function getAccessCodesApi() {
return requestClient.get<string[]>('/auth/codes');
return requestClient.get<string[]>('/auth/permissions');
}

View File

@@ -6,5 +6,5 @@ import { requestClient } from '#/api/request';
* 获取用户所有菜单
*/
export async function getAllMenusApi() {
return requestClient.get<RouteRecordStringComponent[]>('/menu/all');
return requestClient.get<RouteRecordStringComponent[]>('/auth/menu');
}

View File

@@ -2,9 +2,46 @@ import type { UserInfo } from '@vben/types';
import { requestClient } from '#/api/request';
const TENANT_STORAGE_KEY = 'sys-tenant-id';
interface TenantUserProfile {
account?: string;
avatar?: string;
displayName?: string;
merchantId?: null | number | string;
permissions?: string[];
roles?: string[];
tenantId?: number | string;
userId?: number | string;
}
function normalizeId(value: null | number | string | undefined) {
if (value === null || value === undefined) {
return '';
}
return String(value);
}
function mapProfileToUserInfo(profile: TenantUserProfile): UserInfo {
return {
avatar: profile.avatar ?? '',
desc: '',
homePath: '',
realName: profile.displayName ?? profile.account ?? '',
roles: profile.roles ?? [],
token: '',
userId: normalizeId(profile.userId),
username: profile.account ?? '',
};
}
/**
* 获取用户信息
*/
export async function getUserInfoApi() {
return requestClient.get<UserInfo>('/user/info');
const profile = await requestClient.get<TenantUserProfile>('/auth/profile');
if (profile.tenantId !== null && profile.tenantId !== undefined) {
localStorage.setItem(TENANT_STORAGE_KEY, String(profile.tenantId));
}
return mapProfileToUserInfo(profile);
}

View File

@@ -20,6 +20,46 @@ import { useAuthStore } from '#/store';
import { refreshTokenApi } from './core';
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const TENANT_HEADER_KEY = 'X-Tenant-Id';
const TENANT_STORAGE_KEY = 'sys-tenant-id';
const DEV_TENANT_ID = import.meta.env.DEV ? import.meta.env.VITE_TENANT_ID : '';
function getHeaderValue(headers: any, key: string) {
if (!headers) {
return '';
}
if (typeof headers.get === 'function') {
return headers.get(key) || headers.get(key.toLowerCase()) || '';
}
return headers[key] || headers[key.toLowerCase()] || '';
}
function setHeaderValue(headers: any, key: string, value: string) {
if (!headers) {
return;
}
if (typeof headers.set === 'function') {
headers.set(key, value);
return;
}
headers[key] = value;
}
function resolveTenantId() {
const hostname = window.location.hostname;
const hostnameParts = hostname.split('.').filter(Boolean);
const isIpAddress = /^\d+\.\d+\.\d+\.\d+$/.test(hostname);
const subdomainTenantId =
hostnameParts.length > 2 && !isIpAddress ? hostnameParts[0] : '';
const storageTenantId = localStorage.getItem(TENANT_STORAGE_KEY) || '';
return subdomainTenantId || storageTenantId || DEV_TENANT_ID || '';
}
function createRequestClient(baseURL: string, options?: RequestClientOptions) {
const client = new RequestClient({
@@ -50,10 +90,27 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
*/
async function doRefreshToken() {
const accessStore = useAccessStore();
const resp = await refreshTokenApi();
const newToken = resp.data;
accessStore.setAccessToken(newToken);
return newToken;
const currentRefreshToken = accessStore.refreshToken;
if (!currentRefreshToken) {
throw new Error('refresh token is required');
}
const resp = await refreshTokenApi({
refreshToken: currentRefreshToken,
});
const tokenData = resp?.data;
const newAccessToken = tokenData?.accessToken;
const newRefreshToken = tokenData?.refreshToken ?? currentRefreshToken;
if (!newAccessToken) {
throw new Error('access token is missing in refresh response');
}
accessStore.setAccessToken(newAccessToken);
accessStore.setRefreshToken(newRefreshToken);
return newAccessToken;
}
function formatToken(token: null | string) {
@@ -65,8 +122,20 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
fulfilled: async (config) => {
const accessStore = useAccessStore();
config.headers.Authorization = formatToken(accessStore.accessToken);
config.headers['Accept-Language'] = preferences.app.locale;
const authorization = formatToken(accessStore.accessToken);
if (authorization) {
setHeaderValue(config.headers, 'Authorization', authorization);
}
setHeaderValue(config.headers, 'Accept-Language', preferences.app.locale);
const headerTenantId = getHeaderValue(config.headers, TENANT_HEADER_KEY);
if (!headerTenantId) {
const tenantId = resolveTenantId();
if (tenantId) {
setHeaderValue(config.headers, TENANT_HEADER_KEY, String(tenantId));
}
}
return config;
},
});
@@ -76,7 +145,7 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
defaultResponseInterceptor({
codeField: 'code',
dataField: 'data',
successCode: 0,
successCode: 200,
}),
);

View File

@@ -1,4 +1,4 @@
import { initPreferences } from '@vben/preferences';
import { initPreferences, updatePreferences } from '@vben/preferences';
import { unmountGlobalLoading } from '@vben/utils';
import { overridesPreferences } from './preferences';
@@ -19,6 +19,13 @@ async function initApplication() {
overrides: overridesPreferences,
});
updatePreferences({
app: {
accessMode: 'backend',
defaultHomePath: '/dashboard/console',
},
});
// 启动应用并挂载
// vue应用主要逻辑及视图
const { bootstrap } = await import('./bootstrap');

View File

@@ -8,6 +8,11 @@ import { defineOverridesPreferences } from '@vben/preferences';
export const overridesPreferences = defineOverridesPreferences({
// overrides
app: {
accessMode: 'backend',
defaultHomePath: '/dashboard/console',
name: import.meta.env.VITE_APP_TITLE,
},
theme: {
mode: 'light',
},
});

View File

@@ -33,11 +33,12 @@ export const useAuthStore = defineStore('auth', () => {
let userInfo: null | UserInfo = null;
try {
loginLoading.value = true;
const { accessToken } = await loginApi(params);
const { accessToken, refreshToken } = await loginApi(params);
// 如果成功获取到 accessToken
if (accessToken) {
accessStore.setAccessToken(accessToken);
accessStore.setRefreshToken(refreshToken ?? null);
// 获取用户信息并存储到 accessStore 中
const [fetchUserInfoResult, accessCodes] = await Promise.all([

View File

@@ -1,6 +1,5 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { BasicOption } from '@vben/types';
import { computed, markRaw } from 'vue';
@@ -13,59 +12,14 @@ defineOptions({ name: 'Login' });
const authStore = useAuthStore();
const MOCK_USER_OPTIONS: BasicOption[] = [
{
label: 'Super',
value: 'vben',
},
{
label: 'Admin',
value: 'admin',
},
{
label: 'User',
value: 'jack',
},
];
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: MOCK_USER_OPTIONS,
placeholder: $t('authentication.selectAccount'),
},
fieldName: 'selectAccount',
label: $t('authentication.selectAccount'),
rules: z
.string()
.min(1, { message: $t('authentication.selectAccount') })
.optional()
.default('vben'),
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.usernameTip'),
},
dependencies: {
trigger(values, form) {
if (values.selectAccount) {
const findUser = MOCK_USER_OPTIONS.find(
(item) => item.value === values.selectAccount,
);
if (findUser) {
form.setValues({
password: '123456',
username: findUser.value,
});
}
}
},
triggerFields: ['selectAccount'],
},
fieldName: 'username',
fieldName: 'account',
label: $t('authentication.username'),
rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
},

View File

@@ -25,14 +25,11 @@
},
"type": "module",
"scripts": {
"build": "cross-env NODE_OPTIONS=--max-old-space-size=8192 turbo build",
"build": "pnpm run build:antd",
"build:analyze": "turbo build:analyze",
"build:antd": "pnpm run build --filter=@vben/web-antd",
"build:docker": "./scripts/deploy/build-local-docker-image.sh",
"build:docs": "pnpm run build --filter=@vben/docs",
"build:ele": "pnpm run build --filter=@vben/web-ele",
"build:naive": "pnpm run build --filter=@vben/web-naive",
"build:tdesign": "pnpm run build --filter=@vben/web-tdesign",
"build:play": "pnpm run build --filter=@vben/playground",
"changeset": "pnpm exec changeset",
"check": "pnpm run check:circular && pnpm run check:dep && pnpm run check:type && pnpm check:cspell",
@@ -42,18 +39,15 @@
"check:type": "turbo run typecheck",
"clean": "node ./scripts/clean.mjs",
"commit": "czg",
"dev": "turbo-run dev",
"dev": "pnpm run dev:antd",
"dev:antd": "pnpm -F @vben/web-antd run dev",
"dev:docs": "pnpm -F @vben/docs run dev",
"dev:ele": "pnpm -F @vben/web-ele run dev",
"dev:naive": "pnpm -F @vben/web-naive run dev",
"dev:tdesign": "pnpm -F @vben/web-tdesign run dev",
"dev:play": "pnpm -F @vben/playground run dev",
"format": "vsh lint --format",
"lint": "vsh lint",
"postinstall": "pnpm -r run stub --if-present",
"preinstall": "npx only-allow pnpm",
"preview": "turbo-run preview",
"preview": "pnpm -F @vben/web-antd run preview",
"publint": "vsh publint",
"reinstall": "pnpm clean --del-lock && pnpm install",
"test:unit": "vitest run --dom",

View File

@@ -8,20 +8,12 @@ packages:
- packages/@core/*
- packages/effects/*
- packages/business/*
- apps/*
- apps/web-antd
- apps/backend-mock
- scripts/*
- docs
- playground
overrides:
'@ast-grep/napi': 'catalog:'
'@ctrl/tinycolor': 'catalog:'
clsx: 'catalog:'
esbuild: 'catalog:'
jiti: 'catalog:'
pinia: 'catalog:'
vue: 'catalog:'
catalog:
'@ast-grep/napi': ^0.39.9
'@changesets/changelog-github': ^0.5.2
@@ -201,3 +193,21 @@ catalog:
yaml-eslint-parser: ^1.3.2
zod: ^3.25.76
zod-defaults: 0.1.3
onlyBuiltDependencies:
- '@parcel/watcher'
- core-js
- esbuild
- lefthook
- less
- unrs-resolver
- vue-demi
overrides:
'@ast-grep/napi': 'catalog:'
'@ctrl/tinycolor': 'catalog:'
clsx: 'catalog:'
esbuild: 'catalog:'
jiti: 'catalog:'
pinia: 'catalog:'
vue: 'catalog:'

View File

@@ -8,18 +8,6 @@
"name": "@vben/web-antd",
"path": "apps/web-antd",
},
{
"name": "@vben/web-ele",
"path": "apps/web-ele",
},
{
"name": "@vben/web-naive",
"path": "apps/web-naive",
},
{
"name": "@vben/web-tdesign",
"path": "apps/web-tdesign",
},
{
"name": "@vben/docs",
"path": "docs",