Преглед изворни кода

feat: :sparkles: 接入钉钉扫码登录

Zimo пре 3 недеља
родитељ
комит
6c13ee6989

+ 1 - 0
index.html

@@ -1,6 +1,7 @@
 <!doctype html>
 <html lang="en">
   <head>
+    <script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
     <meta charset="UTF-8" />
     <link rel="icon" type="image/png" href="/src/assets/imgs/logo.png" />
     <meta http-equiv="X-UA-Compatible" content="IE=edge" />

+ 3 - 5
src/api/login/index.ts

@@ -42,11 +42,9 @@ export function socialLogin(type: string, code: string, state: string) {
   return request.post({ url: '/system/auth/social-login', data: { type, code, state } })
 }
 
-// 社交授权的跳转
-export const socialAuthRedirect = (type: number, redirectUri: string) => {
-  return request.get({
-    url: `/system/auth/social-auth-redirect?type=${type}&redirectUri=${redirectUri}`,
-  })
+// 钉钉扫码登录,复用后端现有社交登录接口。state=22 是后端现有约定。
+export const dingTalkQrLogin = (code: string) => {
+  return socialLogin('20', code, '22')
 }
 
 // 通过短信重置密码

+ 5 - 0
src/locales/en.ts

@@ -346,6 +346,11 @@ export default {
     login: {
       backSignIn: 'Back sign in',
       signInFormTitle: 'Sign in',
+      ssoFormTitle: 'Third-party authorization',
+      dingTalkQrTitle: 'DingTalk QR login',
+      dingTalkQrInitFailed: 'Failed to initialize the DingTalk QR code. Please try again later.',
+      dingTalkQrLoginFailed: 'DingTalk QR login failed. Please scan again.',
+      dingTalkQrRetry: 'Generate QR code again',
       forgetFormTitle: 'Reset password',
 
       signInTitle: 'Backstage management system',

+ 4 - 0
src/locales/zh-CN.ts

@@ -347,6 +347,10 @@ export default {
       backSignIn: '返回',
       signInFormTitle: '登录',
       ssoFormTitle: '三方授权',
+      dingTalkQrTitle: '钉钉扫码登录',
+      dingTalkQrInitFailed: '钉钉二维码初始化失败,请稍后重试',
+      dingTalkQrLoginFailed: '钉钉扫码登录失败,请重新扫码',
+      dingTalkQrRetry: '重新生成二维码',
       forgetFormTitle: '重置密码',
       signInTitle: '开箱即用的中后台管理系统',
       signInDesc: '输入您的个人详细信息开始使用!',

+ 1 - 1
src/permission.ts

@@ -19,7 +19,7 @@ const { loadStart, loadDone } = usePageLoading()
 // 路由不重定向白名单
 const whiteList = [
   '/login',
-  '/social-login',
+  '/auth/dingtalk/callback',
   '/auth-redirect',
   '/bind',
   '/oauthLogin/gitee',

+ 4 - 4
src/router/modules/remaining.ts

@@ -98,10 +98,10 @@ const remainingRouter: AppRouteRecordRaw[] = [
     meta: { hidden: true, title: t('router.login'), noTagsView: true },
   },
   {
-    path: '/social-login',
-    component: () => import('@/views/Login/SocialLogin.vue'),
-    name: 'SocialLogin',
-    meta: { hidden: true, title: t('router.socialLogin'), noTagsView: true },
+    path: '/auth/dingtalk/callback',
+    component: () => import('@/views/Login/DingTalkCallback.vue'),
+    name: 'DingTalkCallback',
+    meta: { hidden: true, title: t('sys.login.dingTalkQrTitle'), noTagsView: true },
   },
   {
     path: '/403',

+ 102 - 0
src/views/Login/DingTalkCallback.vue

@@ -0,0 +1,102 @@
+<script lang="ts" setup>
+  import { defineOptions, onMounted, ref } from 'vue'
+
+  import * as LoginApi from '@/api/login'
+  import * as authUtil from '@/utils/auth'
+
+  defineOptions({ name: 'DingTalkCallback' })
+
+  const STATE_STORAGE_KEY = 'dingtalk_qr_login_state'
+  const route = useRoute()
+  const router = useRouter()
+  const { t } = useI18n()
+  const loading = ref(true)
+  const errorMessage = ref('')
+  const handled = ref(false)
+
+  const getStringQuery = (key: string) => {
+    const value = route.query[key]
+    return typeof value === 'string' ? value : ''
+  }
+
+  const getSafeRedirect = (redirect: unknown) => {
+    if (typeof redirect !== 'string' || !redirect.startsWith('/') || redirect.startsWith('//')) {
+      return '/'
+    }
+    return redirect
+  }
+
+  const ensureTenantId = async () => {
+    if (import.meta.env.VITE_APP_TENANT_ENABLE === 'false' || authUtil.getTenantId()) {
+      return
+    }
+
+    const tenantName = import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '芋道源码'
+    const tenantId = await LoginApi.getTenantIdByName(tenantName)
+    authUtil.setTenantId(tenantId)
+  }
+
+  const readLoginState = () => {
+    const rawState = sessionStorage.getItem(STATE_STORAGE_KEY)
+    if (!rawState) return null
+
+    try {
+      const state = JSON.parse(rawState)
+      if (
+        typeof state?.state !== 'string'
+        || typeof state?.createdAt !== 'number'
+        || Date.now() - state.createdAt > 10 * 60 * 1000
+      ) {
+        return null
+      }
+      return state as { state: string; redirect?: string; createdAt: number }
+    } catch {
+      return null
+    }
+  }
+
+  const handleCallback = async () => {
+    if (handled.value) return
+    handled.value = true
+
+    const code = getStringQuery('code')
+    const returnedState = getStringQuery('state')
+    const pendingState = readLoginState()
+    sessionStorage.removeItem(STATE_STORAGE_KEY)
+
+    if (!code || !returnedState || !pendingState || returnedState !== pendingState.state) {
+      throw new Error('Invalid DingTalk login callback')
+    }
+
+    await ensureTenantId()
+    const token = await LoginApi.dingTalkQrLogin(code)
+    authUtil.setToken(token)
+    await router.replace(getSafeRedirect(pendingState.redirect))
+  }
+
+  onMounted(async () => {
+    try {
+      await handleCallback()
+    } catch (error) {
+      errorMessage.value = t('sys.login.dingTalkQrLoginFailed')
+      console.error('DingTalk QR login callback failed:', error)
+    } finally {
+      loading.value = false
+    }
+  })
+</script>
+
+<template>
+  <div class="p-20px flex h-full items-center justify-center">
+    <el-card class="text-center w-420px">
+      <el-result v-if="loading" icon="info" :title="t('sys.login.dingTalkQrTitle')" />
+      <el-result v-else-if="errorMessage" icon="error" :title="errorMessage">
+        <template #extra>
+          <el-button type="primary" @click="router.replace('/login')">
+            {{ t('sys.login.backSignIn') }}
+          </el-button>
+        </template>
+      </el-result>
+    </el-card>
+  </div>
+</template>

+ 3 - 1
src/views/Login/Login.vue

@@ -7,7 +7,7 @@
   import { ThemeSwitch } from '@/layout/components/ThemeSwitch'
   import { LocaleDropdown } from '@/layout/components/LocaleDropdown'
 
-  import { ForgetPasswordForm, LoginForm, SSOLoginVue } from './components'
+  import { ForgetPasswordForm, LoginForm, QrCodeForm, SSOLoginVue } from './components'
 
   defineOptions({ name: 'Login' })
 
@@ -51,6 +51,8 @@
             class="m-auto flex h-[calc(100%-60px)] w-[100%] items-center at-2xl:max-w-500px at-lg:max-w-500px at-md:max-w-500px at-xl:max-w-500px">
             <!-- 账号登录 -->
             <LoginForm class="m-auto p-20px h-auto lt-xl:(rounded-3xl light:bg-white)" />
+            <!-- 钉钉扫码登录 -->
+            <QrCodeForm class="m-auto p-20px h-auto lt-xl:(rounded-3xl light:bg-white)" />
             <!-- 三方登录 -->
             <SSOLoginVue class="m-auto p-20px h-auto lt-xl:(rounded-3xl light:bg-white)" />
             <!-- 忘记密码 -->

+ 0 - 314
src/views/Login/SocialLogin.vue

@@ -1,314 +0,0 @@
-<script lang="ts" setup>
-  import { defineOptions } from 'vue'
-  import { ElLoading } from 'element-plus'
-
-  import router from '@/router'
-  import * as LoginApi from '@/api/login'
-  import * as authUtil from '@/utils/auth'
-  import { underlineToHump } from '@/utils'
-  import { useIcon } from '@/hooks/web/useIcon'
-  import { useDesign } from '@/hooks/web/useDesign'
-  import { useAppStore } from '@/store/modules/app'
-  import { ThemeSwitch } from '@/layout/components/ThemeSwitch'
-  import { usePermissionStore } from '@/store/modules/permission'
-  import { LocaleDropdown } from '@/layout/components/LocaleDropdown'
-
-  import LoginFormTitle from './components/LoginFormTitle.vue'
-  import { LoginStateEnum, useFormValid, useLoginState } from './components/useLogin'
-
-  defineOptions({ name: 'SocialLogin' })
-
-  const { t } = useI18n()
-  const route = useRoute()
-
-  const appStore = useAppStore()
-  const { getPrefixCls } = useDesign()
-  const prefixCls = getPrefixCls('login')
-  const iconHouse = useIcon({ icon: 'ep:house' })
-  const iconAvatar = useIcon({ icon: 'ep:avatar' })
-  const iconLock = useIcon({ icon: 'ep:lock' })
-  const formLogin = ref<any>()
-  const { validForm } = useFormValid(formLogin)
-  const { getLoginState } = useLoginState()
-  const { push } = useRouter()
-  const permissionStore = usePermissionStore()
-  const loginLoading = ref(false)
-
-  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)
-
-  const LoginRules = { tenantName: [required], username: [required], password: [required] }
-  const loginData = reactive({
-    isShowPassword: false,
-    tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE !== 'false',
-    loginForm: {
-      tenantName: '芋道源码',
-      username: 'admin',
-      password: 'admin123',
-      rememberMe: false,
-    },
-  })
-
-  const loading = ref() // ElLoading.service 返回的实例
-
-  //获取租户ID
-  const getTenantId = async () => {
-    if (loginData.tenantEnable) {
-      const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
-      authUtil.setTenantId(res)
-    }
-  }
-
-  // 登录
-  const handleLogin = async () => {
-    loginLoading.value = true
-    try {
-      await getTenantId()
-      const data = await validForm()
-      if (!data) {
-        return
-      }
-
-      let redirect = getUrlValue('redirect')
-
-      const type = getUrlValue('type')
-      const code = route?.query?.code as string
-      const state = route?.query?.state as string
-
-      const loginDataLoginForm = { ...loginData.loginForm }
-      const res = await LoginApi.login({
-        // 账号密码登录
-        username: loginDataLoginForm.username,
-        password: loginDataLoginForm.password,
-        // 社交登录
-        socialCode: code,
-        socialState: state,
-        socialType: type,
-      })
-      if (!res) {
-        return
-      }
-      loading.value = ElLoading.service({
-        lock: true,
-        text: '正在加载系统中...',
-        background: 'rgba(0, 0, 0, 0.7)',
-      })
-      if (loginDataLoginForm.rememberMe) {
-        authUtil.setLoginForm(loginDataLoginForm)
-      } else {
-        authUtil.removeLoginForm()
-      }
-      authUtil.setToken(res)
-      if (!redirect) {
-        redirect = '/'
-      }
-      // 判断是否为SSO登录
-      if (redirect.includes('sso')) {
-        window.location.href = window.location.href.replace('/login?redirect=', '')
-      } else {
-        push({ path: redirect || permissionStore.addRouters[0].path })
-      }
-    } finally {
-      loginLoading.value = false
-      loading.value.close()
-    }
-  }
-
-  const handleSubmit = async () => {
-    await handleLogin()
-  }
-
-  // 记住我
-  const getCookie = () => {
-    const loginForm = authUtil.getLoginForm()
-    if (loginForm) {
-      loginData.loginForm = {
-        ...loginData.loginForm,
-        username: loginForm.username ? loginForm.username : loginData.loginForm.username,
-        password: loginForm.password ? loginForm.password : loginData.loginForm.password,
-        rememberMe: !!loginForm.rememberMe,
-        tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName,
-      }
-    }
-  }
-
-  // tricky: 配合LoginForm.vue中redirectUri需要对参数进行encode,需要在回调后进行decode
-  function getUrlValue(key: string): string {
-    const url = new URL(decodeURIComponent(location.href))
-    return url.searchParams.get(key) ?? ''
-  }
-
-  // 尝试登录: 当账号已经绑定,socialLogin会直接获得token
-  const tryLogin = async () => {
-    try {
-      const type = getUrlValue('type')
-      const redirect = getUrlValue('redirect')
-      const code = route?.query?.code as string
-      const state = route?.query?.state as string
-
-      const res = await LoginApi.socialLogin(type, code, state)
-      authUtil.setToken(res)
-
-      router.push({ path: redirect || '/' })
-    } catch (err) {}
-  }
-
-  onMounted(() => {
-    getCookie()
-    tryLogin()
-  })
-</script>
-
-<template>
-  <div
-    :class="prefixCls"
-    class="h-[100%] relative lt-md:px-10px lt-sm:px-10px lt-xl:px-10px lt-xl:px-10px">
-    <div class="mx-auto flex h-full relative">
-      <div
-        :class="`${prefixCls}__left flex-1 bg-gray-500 bg-opacity-20 relative p-30px lt-xl:hidden overflow-x-hidden overflow-y-auto`">
-        <!-- 左上角的 logo + 系统标题 -->
-        <div class="text-white flex items-center relative">
-          <img alt="" class="mr-10px h-48px w-48px" src="@/assets/imgs/logo.png" />
-          <span class="text-20px font-bold">{{ underlineToHump(appStore.getTitle) }}</span>
-        </div>
-        <!-- 左边的背景图 + 欢迎语 -->
-        <div class="flex h-[calc(100%-60px)] items-center justify-center">
-          <TransitionGroup
-            appear
-            enter-active-class="animate__animated animate__bounceInLeft"
-            tag="div">
-            <img key="1" alt="" class="w-350px" src="@/assets/svgs/login-box-bg.svg" />
-            <div key="2" class="text-3xl text-white">{{ t('login.welcome') }}</div>
-            <div key="3" class="text-14px text-white font-normal mt-5">
-              {{ t('login.message') }}
-            </div>
-          </TransitionGroup>
-        </div>
-      </div>
-      <div
-        class="p-30px flex-1 relative overflow-x-hidden overflow-y-auto lt-sm:p-10px dark:bg-[var(--login-bg-color)]">
-        <!-- 右上角的主题、语言选择 -->
-        <div
-          class="text-white flex items-center justify-between at-2xl:justify-end at-xl:justify-end">
-          <div class="flex items-center at-2xl:hidden at-xl:hidden">
-            <img alt="" class="mr-10px h-48px w-48px" src="@/assets/imgs/logo.png" />
-            <span class="text-20px font-bold">{{ underlineToHump(appStore.getTitle) }}</span>
-          </div>
-          <div class="flex h-48px items-center justify-end space-x-10px">
-            <ThemeSwitch />
-            <LocaleDropdown class="dark:text-white lt-xl:text-white" />
-          </div>
-        </div>
-        <!-- 右边的登录界面 -->
-        <Transition appear enter-active-class="animate__animated animate__bounceInRight">
-          <div
-            class="m-auto flex h-[calc(100%-60px)] w-[100%] items-center at-2xl:max-w-500px at-lg:max-w-500px at-md:max-w-500px at-xl:max-w-500px">
-            <!-- 账号登录 -->
-            <el-form
-              v-show="getShow"
-              ref="formLogin"
-              :model="loginData.loginForm"
-              :rules="LoginRules"
-              class="login-form"
-              label-position="top"
-              label-width="120px"
-              size="large">
-              <el-row style="margin-right: -10px; margin-left: -10px">
-                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
-                  <el-form-item>
-                    <LoginFormTitle style="width: 100%" />
-                  </el-form-item>
-                </el-col>
-                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
-                  <el-form-item v-if="loginData.tenantEnable" prop="tenantName">
-                    <el-input
-                      v-model="loginData.loginForm.tenantName"
-                      :placeholder="t('login.tenantNamePlaceholder')"
-                      :prefix-icon="iconHouse"
-                      link
-                      type="primary" />
-                  </el-form-item>
-                </el-col>
-                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
-                  <el-form-item prop="username">
-                    <el-input
-                      v-model="loginData.loginForm.username"
-                      :placeholder="t('login.usernamePlaceholder')"
-                      :prefix-icon="iconAvatar" />
-                  </el-form-item>
-                </el-col>
-                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
-                  <el-form-item prop="password">
-                    <el-input
-                      v-model="loginData.loginForm.password"
-                      :placeholder="t('login.passwordPlaceholder')"
-                      :prefix-icon="iconLock"
-                      show-password
-                      type="password"
-                      @keyup.enter="handleSubmit" />
-                  </el-form-item>
-                </el-col>
-                <el-col
-                  :span="24"
-                  style="
-                    padding-right: 10px;
-                    padding-left: 10px;
-                    margin-top: -20px;
-                    margin-bottom: -20px;
-                  ">
-                  <el-form-item>
-                    <el-row justify="space-between" style="width: 100%">
-                      <el-col :span="6">
-                        <el-checkbox v-model="loginData.loginForm.rememberMe">
-                          {{ t('login.remember') }}
-                        </el-checkbox>
-                      </el-col>
-                      <el-col :offset="6" :span="12">
-                        <el-link style="float: right" type="primary">
-                          {{ t('login.forgetPassword') }}
-                        </el-link>
-                      </el-col>
-                    </el-row>
-                  </el-form-item>
-                </el-col>
-                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
-                  <el-form-item>
-                    <el-button
-                      :loading="loginLoading"
-                      class="w-[100%]"
-                      type="primary"
-                      @click="handleSubmit">
-                      {{ t('login.login') }}
-                    </el-button>
-                  </el-form-item>
-                </el-col>
-              </el-row>
-            </el-form>
-          </div>
-        </Transition>
-      </div>
-    </div>
-  </div>
-</template>
-
-<style lang="scss" scoped>
-  $prefix-cls: #{$namespace}-login;
-
-  .#{$prefix-cls} {
-    overflow: auto;
-
-    &__left {
-      &::before {
-        position: absolute;
-        top: 0;
-        left: 0;
-        z-index: -1;
-        width: 100%;
-        height: 100%;
-        background-image: url('@/assets/svgs/login-bg.svg');
-        background-position: center;
-        background-repeat: no-repeat;
-        content: '';
-      }
-    }
-  }
-</style>

+ 7 - 52
src/views/Login/components/LoginForm.vue

@@ -15,7 +15,6 @@
   defineOptions({ name: 'LoginForm' })
 
   const { t } = useI18n()
-  const message = useMessage()
   const iconAvatar = useIcon({ icon: 'ep:avatar' })
   const iconLock = useIcon({ icon: 'ep:lock' })
   const formLogin = ref()
@@ -41,8 +40,6 @@
     },
   })
 
-  const socialList = [{ icon: 'ant-design:dingtalk-circle-filled', type: 20 }]
-
   const loading = ref() // ElLoading.service 返回的实例
 
   // 获取租户 ID
@@ -122,38 +119,6 @@
     }
   }
 
-  // 社交登录
-  const doSocialLogin = async (type: number) => {
-    if (type === 0) {
-      message.error('此方式未配置')
-    } else {
-      loginLoading.value = true
-      if (loginData.tenantEnable === 'true') {
-        await getTenantId()
-        if (!authUtil.getTenantId()) {
-          try {
-            const data = await message.prompt('请输入租户名称', t('common.reminder'))
-            if (data?.action !== 'confirm') throw new Error('cancel')
-            const res = await LoginApi.getTenantIdByName(data.value)
-            authUtil.setTenantId(res)
-          } catch (error) {
-            if (error === 'cancel') return
-          } finally {
-            loginLoading.value = false
-          }
-        }
-      }
-      const redirectUri = `${location.origin}/social-login?${encodeURIComponent(
-        `type=${type}&redirect=${redirect.value || '/'}`
-      )}`
-
-      window.location.href = await LoginApi.socialAuthRedirect(
-        type,
-        encodeURIComponent(redirectUri)
-      )
-    }
-  }
-
   watch(
     () => currentRoute.value,
     (route: RouteLocationNormalizedLoaded) => {
@@ -231,15 +196,13 @@
         <el-divider content-position="center">{{ t('login.otherLogin') }}</el-divider>
         <el-col :span="24" class="px-10px">
           <el-form-item>
-            <div class="flex w-full justify-between">
-              <Icon
-                v-for="(item, key) in socialList"
-                :key="key"
-                :icon="item.icon"
-                :size="30"
-                class="anticon cursor-pointer"
-                color="#999"
-                @click="doSocialLogin(item.type)" />
+            <div class="flex w-full">
+              <el-button
+                class="w-full"
+                type="primary"
+                @click="setLoginState(LoginStateEnum.QR_CODE)">
+                {{ t('sys.login.dingTalkQrTitle') }}
+              </el-button>
             </div>
           </el-form-item>
         </el-col>
@@ -247,11 +210,3 @@
     </el-row>
   </el-form>
 </template>
-
-<style lang="scss" scoped>
-  :deep(.anticon) {
-    &:hover {
-      color: var(--el-color-primary) !important;
-    }
-  }
-</style>

+ 1 - 0
src/views/Login/components/LoginFormTitle.vue

@@ -12,6 +12,7 @@
       [LoginStateEnum.RESET_PASSWORD]: t('sys.login.forgetFormTitle'),
       [LoginStateEnum.LOGIN]: t('sys.login.signInFormTitle'),
       [LoginStateEnum.SSO]: t('sys.login.ssoFormTitle'),
+      [LoginStateEnum.QR_CODE]: t('sys.login.dingTalkQrTitle'),
     }
     return titleObj[unref(getLoginState)]
   })

+ 174 - 0
src/views/Login/components/QrCodeForm.vue

@@ -0,0 +1,174 @@
+<script lang="ts" setup>
+  import { defineOptions, nextTick, onBeforeUnmount, ref, watch } from 'vue'
+
+  import LoginFormTitle from './LoginFormTitle.vue'
+  import { LoginStateEnum, useLoginState } from './useLogin'
+
+  defineOptions({ name: 'QrCodeForm' })
+
+  const STATE_STORAGE_KEY = 'dingtalk_qr_login_state'
+  const QR_CONTAINER_ID = 'dingtalk_qr_login_container'
+  const DINGTALK_LOGIN_ORIGIN = 'https://login.dingtalk.com'
+  const DINGTALK_AUTHORIZE_URL = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize'
+
+  const { t } = useI18n()
+  const route = useRoute()
+  const { getLoginState, handleBackLogin } = useLoginState()
+  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.QR_CODE)
+  const initialized = ref(false)
+  const initializing = ref(false)
+  const errorMessage = ref('')
+  const messageHandler = ref<((event: MessageEvent) => void) | null>(null)
+
+  const getRedirect = () => {
+    const redirect = route.query.redirect
+    if (typeof redirect !== 'string' || !redirect.startsWith('/') || redirect.startsWith('//')) {
+      return '/'
+    }
+    return redirect
+  }
+
+  const createState = () => {
+    if (crypto.randomUUID) {
+      return crypto.randomUUID()
+    }
+    const bytes = new Uint8Array(16)
+    crypto.getRandomValues(bytes)
+    return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
+  }
+
+  const saveLoginState = (state: string) => {
+    sessionStorage.setItem(
+      STATE_STORAGE_KEY,
+      JSON.stringify({ state, redirect: getRedirect(), createdAt: Date.now() })
+    )
+  }
+
+  const clearLoginState = () => {
+    sessionStorage.removeItem(STATE_STORAGE_KEY)
+  }
+
+  const getRedirectUri = () => {
+    return (
+      import.meta.env.VITE_DD_REDIRECT_URI || `${window.location.origin}/auth/dingtalk/callback`
+    )
+  }
+
+  const destroyDingTalkLogin = () => {
+    if (messageHandler.value) {
+      window.removeEventListener('message', messageHandler.value)
+      messageHandler.value = null
+    }
+
+    const container = document.getElementById(QR_CONTAINER_ID)
+    if (container) {
+      container.innerHTML = ''
+    }
+    initialized.value = false
+  }
+
+  const initDingTalkLogin = async () => {
+    if (initializing.value) return
+
+    initializing.value = true
+    errorMessage.value = ''
+    destroyDingTalkLogin()
+
+    try {
+      const appId = import.meta.env.VITE_DD_APPID
+      const ddLogin = window.DDLogin
+      if (!appId) {
+        throw new Error('VITE_DD_APPID is not configured')
+      }
+      if (!ddLogin) {
+        throw new Error('DingTalk QR script is unavailable')
+      }
+
+      const state = createState()
+      const redirectUri = getRedirectUri()
+      const authorizeUrl = new URL(DINGTALK_AUTHORIZE_URL)
+      authorizeUrl.searchParams.set('appid', appId)
+      authorizeUrl.searchParams.set('response_type', 'code')
+      authorizeUrl.searchParams.set('scope', 'snsapi_login')
+      authorizeUrl.searchParams.set('state', state)
+      authorizeUrl.searchParams.set('redirect_uri', redirectUri)
+      saveLoginState(state)
+
+      await nextTick()
+      if (!getShow.value) return
+
+      ddLogin({
+        id: QR_CONTAINER_ID,
+        goto: encodeURIComponent(authorizeUrl.toString()),
+        style: 'border:none;background-color:#FFFFFF;',
+        width: '100%',
+        height: 290,
+      })
+
+      const handleMessage = (event: MessageEvent) => {
+        if (event.origin !== DINGTALK_LOGIN_ORIGIN) return
+
+        const loginTmpCode = typeof event.data === 'string' ? event.data : event.data?.loginTmpCode
+        if (!loginTmpCode) return
+
+        const authorizeWithTmpCode = new URL(authorizeUrl)
+        authorizeWithTmpCode.searchParams.set('loginTmpCode', loginTmpCode)
+        window.removeEventListener('message', handleMessage)
+        messageHandler.value = null
+        window.location.assign(authorizeWithTmpCode.toString())
+      }
+
+      messageHandler.value = handleMessage
+      window.addEventListener('message', handleMessage)
+      initialized.value = true
+    } catch (error) {
+      clearLoginState()
+      errorMessage.value = t('sys.login.dingTalkQrInitFailed')
+      console.error('DingTalk QR login initialization failed:', error)
+    } finally {
+      initializing.value = false
+    }
+  }
+
+  watch(
+    getShow,
+    show => {
+      if (show && !initialized.value) {
+        void initDingTalkLogin()
+      } else if (!show && initialized.value) {
+        destroyDingTalkLogin()
+        clearLoginState()
+      }
+    },
+    { immediate: true }
+  )
+
+  onBeforeUnmount(() => {
+    destroyDingTalkLogin()
+    clearLoginState()
+  })
+</script>
+
+<template>
+  <el-row v-show="getShow" class="login-form" style="margin-right: -10px; margin-left: -10px">
+    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
+      <LoginFormTitle class="w-full" />
+    </el-col>
+    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
+      <el-card class="mb-10px text-center" shadow="hover">
+        <div v-if="errorMessage" class="py-20px">
+          <el-alert :closable="false" :title="errorMessage" show-icon type="error" />
+          <el-button class="mt-15px" type="primary" @click="initDingTalkLogin">
+            {{ t('sys.login.dingTalkQrRetry') }}
+          </el-button>
+        </div>
+        <div v-else :id="QR_CONTAINER_ID" class="min-h-290px" />
+      </el-card>
+    </el-col>
+    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
+      <el-button class="w-full" @click="handleBackLogin">
+        {{ t('sys.login.backSignIn') }}
+      </el-button>
+    </el-col>
+  </el-row>
+</template>

+ 2 - 1
src/views/Login/components/index.ts

@@ -1,6 +1,7 @@
 import LoginForm from './LoginForm.vue'
 import SSOLoginVue from './SSOLogin.vue'
+import QrCodeForm from './QrCodeForm.vue'
 import LoginFormTitle from './LoginFormTitle.vue'
 import ForgetPasswordForm from './ForgetPasswordForm.vue'
 
-export { ForgetPasswordForm, LoginForm, LoginFormTitle, SSOLoginVue }
+export { ForgetPasswordForm, LoginForm, LoginFormTitle, QrCodeForm, SSOLoginVue }

+ 1 - 0
src/views/Login/components/useLogin.ts

@@ -4,6 +4,7 @@ export enum LoginStateEnum {
   LOGIN,
   RESET_PASSWORD,
   SSO,
+  QR_CODE,
 }
 
 const currentState = ref(LoginStateEnum.LOGIN)

+ 2 - 0
types/env.d.ts

@@ -18,6 +18,8 @@ interface ImportMetaEnv {
   readonly VITE_BASE_URL: string
   readonly VITE_API_URL: string
   readonly VITE_BASE_PATH: string
+  readonly VITE_DD_APPID?: string
+  readonly VITE_DD_REDIRECT_URI?: string
   readonly VITE_DROP_DEBUGGER: string
   readonly VITE_DROP_CONSOLE: string
   readonly VITE_SOURCEMAP: string

+ 8 - 3
types/global.d.ts

@@ -22,6 +22,13 @@ declare global {
   interface Window {
     _hmt?: any[]
     bpmnInstances?: any
+    DDLogin?: (options: {
+      id: string
+      goto: string
+      style?: string
+      width?: string | number
+      height?: string | number
+    }) => unknown
   }
 
   type SummaryMethodProps<T extends Recordable = Recordable> = Parameters<
@@ -29,9 +36,7 @@ declare global {
   >[0]
 
   type AxiosHeaders =
-    | 'application/json'
-    | 'application/x-www-form-urlencoded'
-    | 'multipart/form-data'
+    'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'
 
   type AxiosMethod = 'get' | 'post' | 'delete' | 'put' | 'GET' | 'POST' | 'DELETE' | 'PUT'