feat:增加 social-login.vue 社交登录

pull/70/MERGE
YunaiV 2025-04-10 22:23:41 +08:00
parent 2c105a21aa
commit 9fc51f085d
8 changed files with 310 additions and 14 deletions

View File

@ -7,6 +7,10 @@ export namespace AuthApi {
password?: string;
username?: string;
captchaVerification?: string;
// 绑定社交登录时,需要传递如下参数
socialType?: number;
socialCode?: string;
socialState?: string;
}
/** 登录接口返回值 */
@ -49,6 +53,12 @@ export namespace AuthApi {
code: string;
}
/** 社交快捷登录接口参数 */
export interface SocialLoginParams {
type: number;
code: string;
state: string;
}
}
/** 登录 */
@ -117,4 +127,19 @@ export const register = (data: AuthApi.RegisterParams) => {
/** 通过短信重置密码 */
export const smsResetPassword = (data: AuthApi.ResetPasswordParams) => {
return requestClient.post('/system/auth/reset-password', data)
}
}
/** 社交授权的跳转 */
export const socialAuthRedirect = (type: number, redirectUri: string) => {
return requestClient.get('/system/auth/social-auth-redirect', {
params: {
type,
redirectUri,
},
});
}
/** 社交快捷登录 */
export const socialLogin = (data: AuthApi.SocialLoginParams) => {
return requestClient.post<AuthApi.LoginResult>('/system/auth/social-login', data);
}

View File

@ -89,6 +89,14 @@ const coreRoutes: RouteRecordRaw[] = [
title: $t('page.auth.register'),
},
},
{
name: 'SocialLogin',
path: 'social-login',
component: () => import('#/views/_core/authentication/social-login.vue'),
meta: {
title: $t('page.auth.login'),
},
},
],
},
];

View File

@ -9,7 +9,7 @@ import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { type AuthApi, getAuthPermissionInfoApi, loginApi, logoutApi, smsLogin, register } from '#/api';
import { type AuthApi, getAuthPermissionInfoApi, loginApi, logoutApi, smsLogin, register, socialLogin } from '#/api';
import { $t } from '#/locales';
export const useAuthStore = defineStore('auth', () => {
@ -27,7 +27,7 @@ export const useAuthStore = defineStore('auth', () => {
* @param onSuccess
*/
async function authLogin(
type: 'mobile' | 'username' | 'register',
type: 'mobile' | 'username' | 'register' | 'social',
params: Recordable<any>,
onSuccess?: () => Promise<void> | void,
) {
@ -37,6 +37,7 @@ export const useAuthStore = defineStore('auth', () => {
loginLoading.value = true;
const { accessToken, refreshToken } = type === 'mobile' ? await smsLogin(params as AuthApi.SmsLoginParams)
: type === 'register' ? await register(params as AuthApi.RegisterParams)
: type === 'social' ? await socialLogin(params as AuthApi.SocialLoginParams)
: await loginApi(params);
// 如果成功获取到 accessToken

View File

@ -1,6 +1,6 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import { type AuthApi, checkCaptcha, getCaptcha } from '#/api/core/auth';
import { type AuthApi, checkCaptcha, getCaptcha, socialAuthRedirect } from '#/api/core/auth';
import { computed, onMounted, ref } from 'vue';
@ -10,12 +10,16 @@ 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';
const { tenantEnable, captchaEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
defineOptions({ name: 'Login' });
const { query } = useRoute();
const authStore = useAuthStore();
const accessStore = useAccessStore();
@ -82,6 +86,27 @@ const handleVerifySuccess = async ({ captchaVerification }: any) => {
}
};
/** 处理第三方登录 */
const redirect = query?.redirect;
const handleThirdLogin = async (type: number) => {
if (type <= 0) {
return;
}
try {
// redirectUri
// tricky: typeredirect encode social-login.vue#getUrlValue() 使
const redirectUri =
location.origin +
'/auth/social-login?' +
encodeURIComponent(`type=${type}&redirect=${redirect || '/'}`)
//
window.location.href = await socialAuthRedirect(type, redirectUri)
} catch (error) {
console.error('第三方登录处理失败:', error);
}
};
/** 组件挂载时获取租户信息 */
onMounted(() => {
fetchTenantList();
@ -150,6 +175,7 @@ const formSchema = computed((): VbenFormSchema[] => {
:form-schema="formSchema"
:loading="authStore.loginLoading"
@submit="handleLogin"
@third-login="handleThirdLogin"
/>
<Verification
ref="verifyRef"

View File

@ -0,0 +1,213 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import { type AuthApi, checkCaptcha, getCaptcha } 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';
const { tenantEnable, captchaEnable } = useAppConfig(import.meta.env, import.meta.env.PROD);
defineOptions({ name: 'Login' });
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { query } = useRoute();
const router = useRouter();
const loginRef = ref();
const verifyRef = ref();
const captchaType = 'blockPuzzle'; // 'blockPuzzle' | 'clickWord'
/** 获取租户列表,并默认选中 */
const tenantList = ref<AuthApi.TenantResult[]>([]); //
const fetchTenantList = async () => {
if (!tenantEnable) {
return;
}
try {
//
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
// > store >
let tenantId: number | null = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
}
// store
if (!tenantId && accessStore.tenantId) {
tenantId = accessStore.tenantId;
}
// 使
if (!tenantId && tenantList.value?.[0]?.id) {
tenantId = tenantList.value[0].id;
}
//
accessStore.setTenantId(tenantId);
loginRef.value.getFormApi().setFieldValue('tenantId', tenantId);
} catch (error) {
console.error('获取租户列表失败:', error);
}
};
/** 尝试登录当账号已经绑定socialLogin 会直接获得 token */
const socialType = Number(getUrlValue('type'));
const redirect = getUrlValue('redirect');
const socialCode = query?.code as string;
const socialState = query?.state as string;
const tryLogin = async () => {
// redirect
if (redirect) {
await router.replace({
query: {
...query,
redirect: encodeURIComponent(redirect)
}
});
}
//
await authStore.authLogin('social', {
type: socialType,
code: socialCode,
state: socialState,
});
}
/** 处理登录 */
const handleLogin = async (values: any) => {
//
if (captchaEnable) {
verifyRef.value.show();
return;
}
//
await authStore.authLogin('username', {
...values,
socialType,
socialCode,
socialState,
});
}
/** 验证码通过,执行登录 */
const handleVerifySuccess = async ({ captchaVerification }: any) => {
try {
await authStore.authLogin('username', {
...(await loginRef.value.getFormApi().getValues()),
captchaVerification,
socialType,
socialCode,
socialState,
});
} catch (error) {
console.error('Error in handleLogin:', error);
}
};
/** tricky: 配合 login.vue 中redirectUri 需要对参数进行 encode需要在回调后进行decode */
function getUrlValue(key: string): string {
const url = new URL(decodeURIComponent(location.href))
return url.searchParams.get(key) ?? ''
}
/** 组件挂载时获取租户信息 */
onMounted(async () => {
await fetchTenantList();
await tryLogin();
});
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id,
})),
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),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
trigger(values) {
if (values.tenantId) {
accessStore.setTenantId(values.tenantId);
}
},
},
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.usernameTip'),
},
fieldName: 'username',
label: $t('authentication.username'),
rules: z
.string()
.min(1, { message: $t('authentication.usernameTip') })
.default(import.meta.env.VITE_APP_DEFAULT_USERNAME),
},
{
component: 'VbenInputPassword',
componentProps: {
placeholder: $t('authentication.passwordTip'),
},
fieldName: 'password',
label: $t('authentication.password'),
rules: z
.string()
.min(1, { message: $t('authentication.passwordTip') })
.default(import.meta.env.VITE_APP_DEFAULT_PASSWORD),
},
];
});
</script>
<template>
<div>
<AuthenticationLogin
ref="loginRef"
:form-schema="formSchema"
:loading="authStore.loginLoading"
:show-code-login="false"
:show-qrcode-login="false"
:show-third-party-login="false"
:show-register="false"
@submit="handleLogin"
/>
<Verification
ref="verifyRef"
v-if="captchaEnable"
:captcha-type="captchaType"
:check-captcha-api="checkCaptcha"
:get-captcha-api="getCaptcha"
:img-size="{ width: '400px', height: '200px' }"
mode="pop"
@on-success="handleVerifySuccess"
/>
</div>
</template>

View File

@ -44,6 +44,7 @@ const props = withDefaults(defineProps<Props>(), {
const emit = defineEmits<{
submit: [Recordable<any>];
thirdLogin: [type: number];
}>();
const [Form, formApi] = useVbenForm(
@ -80,6 +81,15 @@ function handleGo(path: string) {
router.push(path);
}
/**
* 处理第三方登录
*
* @param type 第三方平台类型
*/
function handleThirdLogin(type: number) {
emit('thirdLogin', type);
}
onMounted(() => {
if (localUsername) {
formApi.setFieldValue('username', localUsername);
@ -168,7 +178,7 @@ defineExpose({
<!-- 第三方登录 -->
<slot name="third-party-login">
<ThirdPartyLogin v-if="showThirdPartyLogin" />
<ThirdPartyLogin v-if="showThirdPartyLogin" @third-login="handleThirdLogin" />
</slot>
<slot name="to-register">

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { MdiGithub, MdiGoogle, MdiQqchat, MdiWechat } from '@vben/icons';
import { MdiGithub, MdiQqchat, MdiWechat, AntdDingTalk } from '@vben/icons';
import { $t } from '@vben/locales';
import { VbenIconButton } from '@vben-core/shadcn-ui';
@ -7,6 +7,19 @@ import { VbenIconButton } from '@vben-core/shadcn-ui';
defineOptions({
name: 'ThirdPartyLogin',
});
const emit = defineEmits<{
thirdLogin: [type: number];
}>();
/**
* 处理第三方登录点击
*
* @param type 第三方平台类型
*/
function handleThirdLogin(type: number) {
emit('thirdLogin', type);
}
</script>
<template>
@ -20,18 +33,18 @@ defineOptions({
</div>
<div class="mt-4 flex flex-wrap justify-center">
<VbenIconButton class="mb-3">
<VbenIconButton class="mb-3" @click="handleThirdLogin(30)">
<MdiWechat />
</VbenIconButton>
<VbenIconButton class="mb-3">
<VbenIconButton class="mb-3" @click="handleThirdLogin(20)">
<AntdDingTalk />
</VbenIconButton>
<VbenIconButton class="mb-3" @click="handleThirdLogin(0)">
<MdiQqchat />
</VbenIconButton>
<VbenIconButton class="mb-3">
<VbenIconButton class="mb-3" @click="handleThirdLogin(0)">
<MdiGithub />
</VbenIconButton>
<VbenIconButton class="mb-3">
<MdiGoogle />
</VbenIconButton>
</div>
</div>
</template>

View File

@ -8,10 +8,10 @@ export const MdiWechat = createIconifyIcon('mdi:wechat');
export const MdiGithub = createIconifyIcon('mdi:github');
export const MdiGoogle = createIconifyIcon('mdi:google');
export const MdiQqchat = createIconifyIcon('mdi:qqchat');
export const AntdDingTalk = createIconifyIcon('ant-design:dingtalk')
export const MdiCheckboxMarkedCircleOutline = createIconifyIcon(
'mdi:checkbox-marked-circle-outline',
);