refactor: tenantId 验证方式 z.number().positive()

pull/78/MERGE
xingyu4j 2025-04-22 16:51:40 +08:00
parent 1e9b966638
commit 69fb58f2c8
9 changed files with 175 additions and 130 deletions

View File

@ -1,6 +1,7 @@
import { baseRequestClient, requestClient } from '#/api/request';
import type { AuthPermissionInfo } from '@vben/types';
import { baseRequestClient, requestClient } from '#/api/request';
export namespace AuthApi {
/** 登录接口参数 */
export interface LoginParams {
@ -41,9 +42,9 @@ export namespace AuthApi {
/** 注册接口参数 */
export interface RegisterParams {
username: string
password: string
captchaVerification: string
username: string;
password: string;
captchaVerification: string;
}
/** 重置密码接口参数 */
@ -68,16 +69,22 @@ export async function loginApi(data: AuthApi.LoginParams) {
/** 刷新 accessToken */
export async function refreshTokenApi(refreshToken: string) {
return baseRequestClient.post(`/system/auth/refresh-token?refreshToken=${refreshToken}`);
return baseRequestClient.post(
`/system/auth/refresh-token?refreshToken=${refreshToken}`,
);
}
/** 退出登录 */
export async function logoutApi(accessToken: string) {
return baseRequestClient.post('/system/auth/logout', {}, {
headers: {
Authorization: `Bearer ${accessToken}`,
}
});
return baseRequestClient.post(
'/system/auth/logout',
{},
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
);
}
/** 获取权限信息 */
@ -96,7 +103,9 @@ export async function getTenantSimpleList() {
/** 使用租户域名,获得租户信息 */
export async function getTenantByWebsite(website: string) {
return requestClient.get<AuthApi.TenantResult>(`/system/tenant/get-by-website?website=${website}`);
return requestClient.get<AuthApi.TenantResult>(
`/system/tenant/get-by-website?website=${website}`,
);
}
/** 获取验证码 */
@ -111,23 +120,23 @@ export async function checkCaptcha(data: any) {
/** 获取登录验证码 */
export const sendSmsCode = (data: AuthApi.SmsCodeParams) => {
return requestClient.post('/system/auth/send-sms-code', data )
}
return requestClient.post('/system/auth/send-sms-code', data);
};
/** 短信验证码登录 */
export const smsLogin = (data: AuthApi.SmsLoginParams) => {
return requestClient.post('/system/auth/sms-login', data)
}
return requestClient.post('/system/auth/sms-login', data);
};
/** 注册 */
export const register = (data: AuthApi.RegisterParams) => {
return requestClient.post('/system/auth/register', data)
}
return requestClient.post('/system/auth/register', data);
};
/** 通过短信重置密码 */
export const smsResetPassword = (data: AuthApi.ResetPasswordParams) => {
return requestClient.post('/system/auth/reset-password', data)
}
return requestClient.post('/system/auth/reset-password', data);
};
/** 社交授权的跳转 */
export const socialAuthRedirect = (type: number, redirectUri: string) => {
@ -137,9 +146,12 @@ export const socialAuthRedirect = (type: number, redirectUri: string) => {
redirectUri,
},
});
}
};
/** 社交快捷登录 */
export const socialLogin = (data: AuthApi.SocialLoginParams) => {
return requestClient.post<AuthApi.LoginResult>('/system/auth/social-login', data);
}
return requestClient.post<AuthApi.LoginResult>(
'/system/auth/social-login',
data,
);
};

View File

@ -2,21 +2,25 @@
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import { computed, ref, onMounted } from 'vue';
import type { AuthApi } from '#/api';
import { computed, onMounted, ref } from 'vue';
import { AuthenticationCodeLogin, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { type AuthApi, sendSmsCode } from '#/api';
import { useAppConfig } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue';
import { getTenantSimpleList, getTenantByWebsite } from '#/api/core/auth';
import { useAccessStore } from '@vben/stores';
import { sendSmsCode } from '#/api';
import { getTenantByWebsite, getTenantSimpleList } from '#/api/core/auth';
import { useAuthStore } from '#/store';
const { tenantEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
defineOptions({ name: 'CodeLogin' });
const { tenantEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
const authStore = useAuthStore();
const accessStore = useAccessStore();
@ -37,7 +41,7 @@ const fetchTenantList = async () => {
tenantList.value = await getTenantSimpleList();
// > store >
let tenantId: number | null = null;
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
@ -77,11 +81,7 @@ const formSchema = computed((): VbenFormSchema[] => {
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z
.number()
.nullable()
.refine((val) => val != null && val > 0, $t('authentication.tenantTip'))
.default(null),
rules: z.number().positive(),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
@ -140,7 +140,7 @@ const formSchema = computed((): VbenFormSchema[] => {
} finally {
loading.value = false;
}
}
},
},
fieldName: 'code',
label: $t('authentication.code'),

View File

@ -2,18 +2,21 @@
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import { computed, ref, onMounted, h } from 'vue';
import type { AuthApi } from '#/api';
import { AuthenticationForgetPassword, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { type AuthApi, sendSmsCode, smsResetPassword } from '#/api';
import { useAppConfig } from '@vben/hooks';
import { message } from 'ant-design-vue';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { getTenantSimpleList, getTenantByWebsite } from '#/api/core/auth';
import { AuthenticationForgetPassword, z } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue';
import { sendSmsCode, smsResetPassword } from '#/api';
import { getTenantByWebsite, getTenantSimpleList } from '#/api/core/auth';
defineOptions({ name: 'ForgetPassword' });
const { tenantEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
@ -36,7 +39,7 @@ const fetchTenantList = async () => {
tenantList.value = await getTenantSimpleList();
// > store >
let tenantId: number | null = null;
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
@ -76,11 +79,7 @@ const formSchema = computed((): VbenFormSchema[] => {
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z
.number()
.nullable()
.refine((val) => val != null && val > 0, $t('authentication.tenantTip'))
.default(null),
rules: z.number().positive(),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
@ -139,7 +138,7 @@ const formSchema = computed((): VbenFormSchema[] => {
} finally {
loading.value = false;
}
}
},
},
fieldName: 'code',
label: $t('authentication.code'),

View File

@ -1,24 +1,32 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import { type AuthApi, checkCaptcha, getCaptcha, socialAuthRedirect } from '#/api/core/auth';
import type { AuthApi } from '#/api/core/auth';
import { computed, onMounted, ref } from 'vue';
import { AuthenticationLogin, Verification, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useAppConfig } from '@vben/hooks';
import { useAuthStore } from '#/store';
import { useAccessStore } from '@vben/stores';
import { useRoute } from 'vue-router';
import { getTenantSimpleList, getTenantByWebsite } from '#/api/core/auth';
import {message} from 'ant-design-vue';
import { AuthenticationLogin, Verification, z } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
const { tenantEnable, captchaEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
import {
checkCaptcha,
getCaptcha,
getTenantByWebsite,
getTenantSimpleList,
socialAuthRedirect,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'Login' });
const { tenantEnable, captchaEnable } = useAppConfig(
import.meta.env,
import.meta.env.PROD,
);
const { query } = useRoute();
const authStore = useAuthStore();
const accessStore = useAccessStore();
@ -38,9 +46,10 @@ const fetchTenantList = async () => {
//
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
console.error('tenantList', tenantList.value);
// > store >
let tenantId: number | null = null;
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
@ -72,7 +81,7 @@ const handleLogin = async (values: any) => {
//
await authStore.authLogin('username', values);
}
};
/** 验证码通过,执行登录 */
const handleVerifySuccess = async ({ captchaVerification }: any) => {
@ -95,13 +104,14 @@ const handleThirdLogin = async (type: number) => {
try {
// redirectUri
// tricky: typeredirect encode social-login.vue#getUrlValue() 使
const redirectUri =
location.origin +
'/auth/social-login?' +
encodeURIComponent(`type=${type}&redirect=${redirect || '/'}`)
const redirectUri = `${
location.origin
}/auth/social-login?${encodeURIComponent(
`type=${type}&redirect=${redirect || '/'}`,
)}`;
//
window.location.href = await socialAuthRedirect(type, redirectUri)
window.location.href = await socialAuthRedirect(type, redirectUri);
} catch (error) {
console.error('第三方登录处理失败:', error);
}
@ -125,11 +135,7 @@ const formSchema = computed((): VbenFormSchema[] => {
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z
.number()
.nullable()
.refine((val) => val != null && val > 0, $t('authentication.tenantTip'))
.default(null),
rules: z.number().positive(),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,

View File

@ -1,21 +1,30 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import { type AuthApi, checkCaptcha, getCaptcha } from '#/api/core/auth';
import type { AuthApi } from '#/api/core/auth';
import { computed, h, onMounted, ref } from 'vue';
import { AuthenticationRegister, Verification, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useAppConfig } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import { useAuthStore } from '#/store';
import { getTenantSimpleList, getTenantByWebsite } from '#/api/core/auth';
const { tenantEnable, captchaEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
import {
checkCaptcha,
getCaptcha,
getTenantByWebsite,
getTenantSimpleList,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'Register' });
const { tenantEnable, captchaEnable } = useAppConfig(
import.meta.env,
import.meta.env.PROD,
);
const loading = ref(false);
const registerRef = ref();
const verifyRef = ref();
@ -36,7 +45,7 @@ const fetchTenantList = async () => {
tenantList.value = await getTenantSimpleList();
// > store >
let tenantId: number | null = null;
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
@ -94,17 +103,13 @@ const formSchema = computed((): VbenFormSchema[] => {
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id,
value: item.id.toString(),
})),
placeholder: $t('authentication.tenantTip'),
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z
.number()
.nullable()
.refine((val) => val != null && val > 0, $t('authentication.tenantTip'))
.default(null),
rules: z.number().positive(),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,

View File

@ -1,23 +1,31 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import { type AuthApi, checkCaptcha, getCaptcha } from '#/api/core/auth';
import type { AuthApi } from '#/api/core/auth';
import { computed, onMounted, ref } from 'vue';
import { AuthenticationLogin, Verification, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useAppConfig } from '@vben/hooks';
import { useAuthStore } from '#/store';
import { useAccessStore } from '@vben/stores';
import { useRoute, useRouter } from 'vue-router';
import { getTenantSimpleList, getTenantByWebsite } from '#/api/core/auth';
import { AuthenticationLogin, Verification, z } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
const { tenantEnable, captchaEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
import {
checkCaptcha,
getCaptcha,
getTenantByWebsite,
getTenantSimpleList,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'SocialLogin' });
const { tenantEnable, captchaEnable } = useAppConfig(
import.meta.env,
import.meta.env.PROD,
);
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { query } = useRoute();
@ -41,7 +49,7 @@ const fetchTenantList = async () => {
tenantList.value = await getTenantSimpleList();
// > store >
let tenantId: number | null = null;
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
@ -74,8 +82,8 @@ const tryLogin = async () => {
await router.replace({
query: {
...query,
redirect: encodeURIComponent(redirect)
}
redirect: encodeURIComponent(redirect),
},
});
}
@ -85,7 +93,7 @@ const tryLogin = async () => {
code: socialCode,
state: socialState,
});
}
};
/** 处理登录 */
const handleLogin = async (values: any) => {
@ -102,7 +110,7 @@ const handleLogin = async (values: any) => {
socialCode,
socialState,
});
}
};
/** 验证码通过,执行登录 */
const handleVerifySuccess = async ({ captchaVerification }: any) => {
@ -121,8 +129,8 @@ const handleVerifySuccess = async ({ captchaVerification }: any) => {
/** tricky: 配合 login.vue 中redirectUri 需要对参数进行 encode需要在回调后进行decode */
function getUrlValue(key: string): string {
const url = new URL(decodeURIComponent(location.href))
return url.searchParams.get(key) ?? ''
const url = new URL(decodeURIComponent(location.href));
return url.searchParams.get(key) ?? '';
}
/** 组件挂载时获取租户信息 */
@ -145,11 +153,7 @@ const formSchema = computed((): VbenFormSchema[] => {
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z
.number()
.nullable()
.refine((val) => val != null && val > 0, $t('authentication.tenantTip'))
.default(null),
rules: z.number().positive(),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,

View File

@ -1,11 +1,12 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import { computed, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { AuthenticationAuthTitle, VbenButton } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { computed, reactive, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { authorize, getAuthorize } from '#/api/system/oauth2/open';
defineOptions({ name: 'SSOLogin' });
@ -14,7 +15,7 @@ const { query } = useRoute(); // 路由参数
const client = ref({
name: '',
logo: ''
logo: '',
}); //
const queryParams = reactive({
@ -22,7 +23,7 @@ const queryParams = reactive({
clientId: '',
redirectUri: '',
state: '',
scopes: [] as string[] // query
scopes: [] as string[], // query
}); // URL client_idscope
const loading = ref(false); //
@ -30,7 +31,7 @@ const loading = ref(false); // 表单是否提交中
/** 初始化授权信息 */
const init = async () => {
//
if (typeof query.client_id === 'undefined') {
if (query.client_id === undefined) {
return;
}
//
@ -60,15 +61,20 @@ const init = async () => {
let scopes;
// params.scope scopes
if (queryParams.scopes.length > 0) {
scopes = data.scopes.filter(scope => queryParams.scopes.includes(scope.key));
scopes = data.scopes.filter((scope) =>
queryParams.scopes.includes(scope.key),
);
// params.scope 使 scopes
} else {
scopes = data.scopes;
queryParams.scopes = scopes.map(scope => scope.key);
queryParams.scopes = scopes.map((scope) => scope.key);
}
// 2.
formApi.setFieldValue('scopes', scopes.filter(scope => scope.value).map(scope => scope.key));
formApi.setFieldValue(
'scopes',
scopes.filter((scope) => scope.value).map((scope) => scope.key),
);
};
/** 处理授权的提交 */
@ -78,8 +84,11 @@ const handleSubmit = async (approved: boolean) => {
let uncheckedScopes: string[];
if (approved) {
//
checkedScopes = (await formApi.getValues()).scopes;
uncheckedScopes = queryParams.scopes.filter((item) => checkedScopes.indexOf(item) === -1);
const res = await formApi.getValues();
checkedScopes = res.scopes;
uncheckedScopes = queryParams.scopes.filter(
(item) => !checkedScopes.includes(item),
);
} else {
//
checkedScopes = [];
@ -101,7 +110,11 @@ const handleSubmit = async (approved: boolean) => {
};
/** 调用授权 API 接口 */
const doAuthorize = (autoApprove: boolean, checkedScopes: string[], uncheckedScopes: string[]) => {
const doAuthorize = (
autoApprove: boolean,
checkedScopes: string[],
uncheckedScopes: string[],
) => {
return authorize(
queryParams.responseType,
queryParams.clientId,
@ -109,7 +122,7 @@ const doAuthorize = (autoApprove: boolean, checkedScopes: string[], uncheckedSco
queryParams.state,
autoApprove,
checkedScopes,
uncheckedScopes
uncheckedScopes,
);
};
@ -118,12 +131,15 @@ const formatScope = (scope: string) => {
// scope 便
// demo "system_oauth2_scope" scope
switch (scope) {
case 'user.read':
case 'user.read': {
return '访问你的个人信息';
case 'user.write':
}
case 'user.write': {
return '修改你的个人信息';
default:
}
default: {
return scope;
}
}
};
@ -134,11 +150,11 @@ const formSchema = computed((): VbenFormSchema[] => {
label: '授权范围',
component: 'CheckboxGroup',
componentProps: {
options: queryParams.scopes.map(scope => ({
options: queryParams.scopes.map((scope) => ({
label: formatScope(scope),
value: scope
value: scope,
})),
class: 'flex flex-col gap-2'
class: 'flex flex-col gap-2',
},
},
];
@ -158,7 +174,7 @@ const [Form, formApi] = useVbenForm(
/** 初始化 */
onMounted(() => {
init();
})
});
</script>
<template>

View File

@ -1,9 +1,9 @@
export { default as AuthenticationAuthTitle } from './auth-title.vue';
export { default as AuthenticationCodeLogin } from './code-login.vue';
export { default as DocLink } from './doc-link.vue';
export { default as AuthenticationForgetPassword } from './forget-password.vue';
export { default as AuthenticationLoginExpiredModal } from './login-expired-modal.vue';
export { default as AuthenticationLogin } from './login.vue';
export { default as AuthenticationQrCodeLogin } from './qrcode-login.vue';
export { default as AuthenticationRegister } from './register.vue';
export { default as DocLink } from './doc-link.vue';
export { default as AuthenticationAuthTitle } from './auth-title.vue';
export type { AuthenticationProps } from './types';

View File

@ -14,8 +14,8 @@ import { useVbenForm } from '@vben-core/form-ui';
import { VbenButton, VbenCheckbox } from '@vben-core/shadcn-ui';
import Title from './auth-title.vue';
import ThirdPartyLogin from './third-party-login.vue';
import DocLink from './doc-link.vue';
import ThirdPartyLogin from './third-party-login.vue';
interface Props extends AuthenticationProps {
formSchema: VbenFormSchema[];
@ -179,7 +179,10 @@ defineExpose({
<!-- 第三方登录 -->
<slot name="third-party-login">
<ThirdPartyLogin v-if="showThirdPartyLogin" @third-login="handleThirdLogin" />
<ThirdPartyLogin
v-if="showThirdPartyLogin"
@third-login="handleThirdLogin"
/>
</slot>
<slot name="to-register">