Pārlūkot izejas kodu

!33 feat: 新增图形验证码功能,支持滑块和文字点击
Merge pull request !33 from 熊猫大侠/master-panda-dev

芋道源码 4 mēneši atpakaļ
vecāks
revīzija
87821086ef

+ 1 - 0
package.json

@@ -113,6 +113,7 @@
     "@dcloudio/uni-mp-xhs": "3.0.0-4070620250821001",
     "@dcloudio/uni-quickapp-webview": "3.0.0-4070620250821001",
     "abortcontroller-polyfill": "^1.7.8",
+    "crypto-js": "^4.2.0",
     "dayjs": "1.11.10",
     "pinia": "2.0.36",
     "pinia-plugin-persistedstate": "3.2.1",

+ 57 - 48
src/api/login.ts

@@ -6,106 +6,115 @@ import type {
   IUpdateInfo,
   IUpdatePassword,
   IUserInfoRes,
-} from "./types/login";
-import { http } from "@/http/http";
+} from './types/login'
+import { http } from '@/http/http'
 
 /**
  * 登录表单
  */
 export interface ILoginForm {
-  type: "username" | "register" | "sms";
-  username?: string;
-  password?: string;
-  nickname?: string;
-  captchaVerification?: string;
-  mobile?: string;
-  code?: string;
+  type: 'username' | 'register' | 'sms'
+  username?: string
+  password?: string
+  nickname?: string
+  captchaVerification?: string
+  mobile?: string
+  code?: string
 }
 
 /** 账号密码登录 Request VO */
 export interface AuthLoginReqVO {
-  password?: string;
-  username?: string;
-  captchaVerification?: string;
+  password?: string
+  username?: string
+  captchaVerification?: string
   // 绑定社交登录时,需要传递如下参数
-  socialType?: number;
-  socialCode?: string;
-  socialState?: string;
+  socialType?: number
+  socialCode?: string
+  socialState?: string
 }
 
 /** 注册 Request VO */
 export interface AuthRegisterReqVO {
-  username: string;
-  password: string;
-  captchaVerification: string;
+  username: string
+  password: string
+  captchaVerification: string
 }
 
 /** 短信登录 Request VO */
 export interface AuthSmsLoginReqVO {
-  mobile: string;
-  code: string;
+  mobile: string
+  code: string
 }
 
 /** 发送短信验证码 Request VO */
 export interface AuthSmsSendReqVO {
-  mobile: string;
-  scene: number;
+  mobile: string
+  scene: number
 }
 
 /** 租户信息 */
 export interface TenantVO {
-  id: number;
-  name: string;
+  id: number
+  name: string
 }
 
 /** 重置密码 Request VO */
 export interface AuthResetPasswordReqVO {
-  mobile: string;
-  code: string;
-  password: string;
+  mobile: string
+  code: string
+  password: string
 }
 
 /**
  * 获取验证码
  * @returns ICaptcha 验证码
  */
-export function getCode() {
-  return http.get<ICaptcha>("/user/getCode");
+export function getCode(data: any) {
+  return http.post<ICaptcha>('/system/captcha/get', data, null, null, { original: true })
+}
+
+/**
+ * 校验验证码
+ * @param data 验证码校验参数
+ * @returns Promise 包含校验结果
+ */
+export function checkCaptcha(data: any) {
+  return http.post<boolean>('/system/captcha/check', data, null, null, { original: true })
 }
 
 /** 使用账号密码登录 */
 export function login(data: AuthLoginReqVO) {
-  return http.post<IAuthLoginRes>("/system/auth/login", data);
+  return http.post<IAuthLoginRes>('/system/auth/login', data)
 }
 
 /** 注册用户 */
 export function register(data: AuthRegisterReqVO) {
-  return http.post<IAuthLoginRes>("/system/auth/register", data);
+  return http.post<IAuthLoginRes>('/system/auth/register', data)
 }
 
 /** 短信登录 */
 export function smsLogin(data: AuthSmsLoginReqVO) {
-  return http.post<IAuthLoginRes>("/system/auth/sms-login", data);
+  return http.post<IAuthLoginRes>('/system/auth/sms-login', data)
 }
 
 /** 发送短信验证码 */
 export function sendSmsCode(data: AuthSmsSendReqVO) {
-  return http.post<boolean>("/system/auth/send-sms-code", data);
+  return http.post<boolean>('/system/auth/send-sms-code', data)
 }
 
 /** 获取租户简单列表 */
 export function getTenantSimpleList() {
-  return http.get<TenantVO[]>("/system/tenant/simple-list");
+  return http.get<TenantVO[]>('/system/tenant/simple-list')
 }
 
 /** 根据租户域名获取租户信息 */
 export function getTenantByWebsite(website: string) {
-  return http.get<TenantVO>(`/system/tenant/get-by-website?website=${website}`);
+  return http.get<TenantVO>(`/system/tenant/get-by-website?website=${website}`)
 }
 
 /** 通过短信重置密码 */
 export function smsResetPassword(data: AuthResetPasswordReqVO) {
-  return http.post<boolean>("/system/auth/reset-password", data);
+  return http.post<boolean>('/system/auth/reset-password', data)
 }
 
 /**
@@ -113,40 +122,40 @@ export function smsResetPassword(data: AuthResetPasswordReqVO) {
  * @param refreshToken 刷新token
  */
 export function refreshToken(refreshToken: string) {
-  return http.post<IDoubleTokenRes>(`/system/auth/refresh-token?refreshToken=${refreshToken}`);
+  return http.post<IDoubleTokenRes>(`/system/auth/refresh-token?refreshToken=${refreshToken}`)
 }
 
 /**
  * 获取用户信息
  */
 export function getUserInfo() {
-  return http.get<IUserInfoRes>("/user/info");
+  return http.get<IUserInfoRes>('/user/info')
 }
 
 /**
  * 获取权限信息
  */
 export function getAuthPermissionInfo() {
-  return http.get<AuthPermissionInfo>("/system/auth/get-permission-info");
+  return http.get<AuthPermissionInfo>('/system/auth/get-permission-info')
 }
 
 /** 退出登录 */
 export function logout() {
-  return http.post<void>("/system/auth/logout");
+  return http.post<void>('/system/auth/logout')
 }
 
 /**
  * 修改用户信息
  */
 export function updateInfo(data: IUpdateInfo) {
-  return http.post("/user/updateInfo", data);
+  return http.post('/user/updateInfo', data)
 }
 
 /**
  * 修改用户密码
  */
 export function updateUserPassword(data: IUpdatePassword) {
-  return http.post("/user/updatePassword", data);
+  return http.post('/user/updatePassword', data)
 }
 
 /**
@@ -156,11 +165,11 @@ export function updateUserPassword(data: IUpdatePassword) {
 export function getWxCode() {
   return new Promise<UniApp.LoginRes>((resolve, reject) => {
     uni.login({
-      provider: "weixin",
-      success: (res) => resolve(res),
-      fail: (err) => reject(new Error(err)),
-    });
-  });
+      provider: 'weixin',
+      success: res => resolve(res),
+      fail: err => reject(new Error(err)),
+    })
+  })
 }
 
 /**
@@ -169,5 +178,5 @@ export function getWxCode() {
  * @returns Promise 包含登录结果
  */
 export function wxLogin(data: { code: string }) {
-  return http.post<IAuthLoginRes>("/auth/wxLogin", data);
+  return http.post<IAuthLoginRes>('/auth/wxLogin', data)
 }

+ 6 - 4
src/http/http.ts

@@ -64,8 +64,7 @@ export function http<T>(options: CustomRequestOptions) {
               })
               // 将任务队列的所有任务重新请求
               taskQueue.forEach(task => task())
-            }
-            catch (refreshErr) {
+            } catch (refreshErr) {
               console.error('刷新 token 失败:', refreshErr)
               refreshing = false
               // 刷新 token 失败,跳转到登录页
@@ -90,8 +89,7 @@ export function http<T>(options: CustomRequestOptions) {
                 }
                 toLoginPage({ queryString })
               }, 2000)
-            }
-            finally {
+            } finally {
               // 不管刷新 token 成功与否,都清空任务队列
               taskQueue = []
             }
@@ -102,6 +100,10 @@ export function http<T>(options: CustomRequestOptions) {
 
         // 处理其他成功状态(HTTP状态码200-299)
         if (res.statusCode >= 200 && res.statusCode < 300) {
+          // add by panda 25.12.10:如果设置了 original 为 true,则返回原始数据
+          if (options.original) {
+            return resolve(responseData as unknown as T)
+          }
           // 处理业务逻辑错误
           if (code !== ResultEnum.Success0 && code !== ResultEnum.Success200) {
             // add by 芋艿:后端返回的 msg 提示

+ 2 - 1
src/http/types.ts

@@ -5,6 +5,8 @@ export type CustomRequestOptions = UniApp.RequestOptions & {
   query?: Record<string, any>
   /** 出错时是否隐藏错误提示 */
   hideErrorToast?: boolean
+  /** 是否返回原始数据 add by panda 25.12.10 */
+  original?: boolean
 } & IUniUploadFileOptions // 添加uni.uploadFile参数类型
 
 // 通用响应格式(兼容 msg + message 字段)
@@ -32,6 +34,5 @@ export interface PageResult<T> {
   list: T[]
   total: number
 }
-
 /** 加载状态枚举 - 从 wot-design-uni 重新导出 */
 export type { LoadMoreState } from 'wot-design-uni/components/wd-loadmore/types'

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 432 - 0
src/pages/auth/components/Verifition/Verify.vue


+ 251 - 0
src/pages/auth/components/Verifition/Verify/VerifyPoints.vue

@@ -0,0 +1,251 @@
+<template>
+  <view style="position: relative">
+    <view class="verify-img-out">
+      <view
+        :style="{
+          'width': setSize.imgWidth,
+          'height': setSize.imgHeight,
+          'background-size': `${setSize.imgWidth} ${setSize.imgHeight}`,
+          'margin-bottom': `${pSpace}px`,
+        }" class="verify-img-panel"
+      >
+        <view v-show="showRefresh" class="verify-refresh" style="z-index: 3" @click="refresh">
+          <i class="iconfont icon-refresh" />
+        </view>
+        <img
+          id="image" ref="canvas" :src="`data:image/png;base64,${pointBackImgBase}`"
+          alt="" style="display: block; width: 100%; height: 100%"
+          @click="bindingClick ? canvasClick($event) : undefined"
+        >
+
+        <view
+          v-for="(tempPoint, index) in tempPoints" :key="index" :style="{
+            'background-color': '#1abd6c',
+            'color': '#fff',
+            'z-index': 9999,
+            'width': '20px',
+            'height': '20px',
+            'text-align': 'center',
+            'line-height': '20px',
+            'border-radius': '50%',
+            'position': 'absolute',
+            'top': `${parseInt(tempPoint.y - 10)}px`,
+            'left': `${parseInt(tempPoint.x - 10)}px`,
+          }" class="point-area"
+        >
+          {{ index + 1 }}
+        </view>
+      </view>
+    </view>
+    <!-- 'height': this.barSize.height, -->
+    <view
+      :style="{
+        'width': setSize.imgWidth,
+        'color': barAreaColor,
+        'border-color': barAreaBorderColor,
+        'line-height': barSize.height,
+      }" class="verify-bar-area"
+    >
+      <span class="verify-msg">{{ text }}</span>
+    </view>
+  </view>
+</template>
+
+<script setup type="text/babel" name="VerifyPoints">
+import { getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs } from 'vue'
+import { checkCaptcha, getCode } from '@/api/login'
+/**
+ * VerifyPoints
+ * @description 点选
+ */
+import { aesEncrypt } from './../utils/ase'
+
+const props = defineProps({
+  // 弹出式pop,固定fixed
+  mode: {
+    type: String,
+    default: 'fixed',
+  },
+  captchaType: {
+    type: String,
+  },
+  // 间隔
+  pSpace: {
+    type: Number,
+    default: 5,
+  },
+  imgSize: {
+    type: Object,
+    default() {
+      return {
+        width: '310px',
+        height: '155px',
+      }
+    },
+  },
+  barSize: {
+    type: Object,
+    default() {
+      return {
+        width: '310px',
+        height: '40px',
+      }
+    },
+  },
+})
+
+const emit = defineEmits(['error', 'ready', 'success'])
+const { mode, captchaType } = toRefs(props)
+const { proxy } = getCurrentInstance()
+const secretKey = ref('') // 后端返回的ase加密秘钥
+const checkNum = ref(3) // 默认需要点击的字数
+const fontPos = reactive([]) // 选中的坐标信息
+const checkPosArr = reactive([]) // 用户点击的坐标
+const num = ref(1) // 点击的记数
+const pointBackImgBase = ref('') // 后端获取到的背景图片
+const poinTextList = reactive([]) // 后端返回的点击字体顺序
+const backToken = ref('') // 后端返回的token值
+const setSize = reactive({
+  imgHeight: 0,
+  imgWidth: 0,
+  barHeight: 0,
+  barWidth: 0,
+})
+const tempPoints = reactive([])
+const text = ref('')
+const barAreaColor = ref(undefined)
+const barAreaBorderColor = ref(undefined)
+const showRefresh = ref(true)
+const bindingClick = ref(true)
+const imgLeft = ref('')
+const imgTop = ref('')
+
+function init() {
+  // 加载页面
+  fontPos.splice(0, fontPos.length)
+  checkPosArr.splice(0, checkPosArr.length)
+  num.value = 1
+  getPictrue()
+  nextTick(() => {
+    setSize.imgHeight = props.imgSize.height
+    setSize.imgWidth = props.imgSize.width
+    setSize.barHeight = props.barSize.height
+    setSize.barWidth = props.barSize.width
+    emit('ready', proxy)
+  })
+}
+onMounted(() => {
+  // 禁止拖拽
+  init()
+  proxy.$el.onselectstart = function () {
+    return false
+  }
+})
+const canvas = ref(null)
+const instance = getCurrentInstance()
+function canvasClick(e) {
+  const query = uni.createSelectorQuery().in(instance.proxy)
+  query.select('#image').boundingClientRect((rect) => {
+    imgLeft.value = Math.ceil(rect.left)
+    imgTop.value = Math.ceil(rect.top)
+
+    checkPosArr.push(getMousePos(canvas, e))
+    if (num.value === checkNum.value) {
+      num.value = createPoint(getMousePos(canvas, e))
+      // 按比例转换坐标值
+      const arr = pointTransfrom(checkPosArr, setSize)
+      checkPosArr.length = 0
+      checkPosArr.push(...arr)
+      // 等创建坐标执行完
+      setTimeout(() => {
+        // var flag = this.comparePos(this.fontPos, this.checkPosArr);
+        // 发送后端请求
+        const captchaVerification = secretKey.value
+          ? aesEncrypt(`${backToken.value}---${JSON.stringify(checkPosArr)}`, secretKey.value)
+          : `${backToken.value}---${JSON.stringify(checkPosArr)}`
+        const data = {
+          captchaType: captchaType.value,
+          pointJson: secretKey.value
+            ? aesEncrypt(JSON.stringify(checkPosArr), secretKey.value)
+            : JSON.stringify(checkPosArr),
+          token: backToken.value,
+        }
+        checkCaptcha(data).then((res) => {
+          if (res.repCode === '0000') {
+            barAreaColor.value = '#4cae4c'
+            barAreaBorderColor.value = '#5cb85c'
+            text.value = '验证成功'
+            bindingClick.value = false
+            if (mode.value === 'pop') {
+              setTimeout(() => {
+                proxy.$parent.clickShow = false
+                refresh()
+              }, 1500)
+            }
+            emit('success', { captchaVerification })
+          } else {
+            emit('error', proxy)
+            barAreaColor.value = '#d9534f'
+            barAreaBorderColor.value = '#d9534f'
+            text.value = '验证失败'
+            setTimeout(() => {
+              refresh()
+            }, 700)
+          }
+        })
+      }, 400)
+    }
+    if (num.value < checkNum.value) {
+      num.value = createPoint(getMousePos(canvas, e))
+    }
+  }).exec()
+}
+// 获取坐标,H5用offsetX,Y,小程序用clientX,Y,pageX,Y,x,y
+function getMousePos(obj, e) {
+  const x = e?.offsetX ? e.offsetX : Math.ceil(e?.detail.clientX || e?.detail.pageX || e?.detail.x || 0) - imgLeft.value
+  const y = e?.offsetY ? e.offsetY : Math.ceil(e?.detail.clientY || e?.detail.pageY || e?.detail.y || 0) - imgTop.value
+  return { x, y }
+}
+// 创建坐标点
+function createPoint(pos) {
+  tempPoints.push(Object.assign({}, pos))
+  return num.value + 1
+}
+async function refresh() {
+  tempPoints.splice(0, tempPoints.length)
+  barAreaColor.value = '#000'
+  barAreaBorderColor.value = '#ddd'
+  bindingClick.value = true
+  fontPos.splice(0, fontPos.length)
+  checkPosArr.splice(0, checkPosArr.length)
+  num.value = 1
+  await getPictrue()
+  showRefresh.value = true
+}
+
+// 请求背景图片和验证图片
+async function getPictrue() {
+  const data = {
+    captchaType: captchaType.value,
+  }
+  const res = await getCode(data)
+  if (res.repCode === '0000') {
+    pointBackImgBase.value = res.repData.originalImageBase64
+    backToken.value = res.repData.token
+    secretKey.value = res.repData.secretKey
+    poinTextList.value = res.repData.wordList
+    text.value = `请依次点击` + `【${poinTextList.value.join(',')}】`
+  } else {
+    text.value = res.repMsg
+  }
+}
+// 坐标转换函数
+function pointTransfrom(pointArr, imgSize) {
+  const newPointArr = pointArr.map((p) => {
+    const x = Math.round((310 * p.x) / Number.parseInt(imgSize.imgWidth))
+    const y = Math.round((155 * p.y) / Number.parseInt(imgSize.imgHeight))
+    return { x, y }
+  })
+  return newPointArr
+}
+</script>

+ 345 - 0
src/pages/auth/components/Verifition/Verify/VerifySlide.vue

@@ -0,0 +1,345 @@
+<template>
+  <view style="position: relative">
+    <view v-if="type === '2'" :style="{ height: `${parseInt(setSize.imgHeight) + pSpace}px` }" class="verify-img-out">
+      <view :style="{ width: setSize.imgWidth, height: setSize.imgHeight }" class="verify-img-panel">
+        <img :src="`data:image/png;base64,${backImgBase}`" alt="" style="display: block; width: 100%; height: 100%">
+        <view v-show="showRefresh" class="verify-refresh" @click="refresh">
+          <view class="iconfont icon-refresh" />
+        </view>
+        <transition name="tips">
+          <text v-if="tipWords" :class="passFlag ? 'suc-bg' : 'err-bg'" class="verify-tips">
+            {{ tipWords }}
+          </text>
+        </transition>
+      </view>
+    </view>
+    <!-- 公共部分 -->
+    <view
+      :style="{ 'width': setSize.imgWidth, 'height': barSize.height, 'line-height': barSize.height }"
+      class="verify-bar-area"
+    >
+      <text class="verify-msg">{{ text }}</text>
+      <view
+        :style="{
+          'width': leftBarWidth !== undefined ? leftBarWidth : barSize.height,
+          'height': barSize.height,
+          'border-color': leftBarBorderColor,
+          'transaction': transitionWidth,
+        }" class="verify-left-bar"
+      >
+        <text class="verify-msg">{{ finishText }}</text>
+        <view
+          v-if="type === '2'" :style="{
+            'width': barSize.height,
+            'height': barSize.height,
+            'background-color': moveBlockBackgroundColor,
+            'left': moveBlockLeft,
+            'transition': transitionLeft,
+          }" class="verify-move-block" @touchstart="start" @touchend="end" @touchmove="move" @mouseup="end"
+        >
+          <view class="verify-icon iconfont" :class="[iconClass]" :style="{ color: iconColor }" />
+          <view
+            v-if="type === '2'" :style="{
+              'width': `${Math.floor((parseInt(setSize.imgWidth) * 47) / 310)}px`,
+              'height': setSize.imgHeight,
+              'top': `-${parseInt(setSize.imgHeight) + pSpace}px`,
+              'background-size': `${setSize.imgWidth} ${setSize.imgHeight}`,
+            }" class="verify-sub-block"
+          >
+            <img
+              :src="`data:image/png;base64,${blockBackImgBase}`" alt=""
+              style="display: block; width: 100%; height: 100%; -webkit-user-drag: none"
+            >
+          </view>
+        </view>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script setup name="VerifySlide">
+import { computed, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs, watch } from 'vue'
+import { checkCaptcha, getCode } from '@/api/login'
+/**
+ * VerifySlide
+ * @description 滑块
+ */
+import { aesEncrypt } from './../utils/ase'
+
+const props = defineProps({
+  captchaType: {
+    type: String,
+  },
+  type: {
+    type: String,
+    default: '1',
+  },
+  // 弹出式pop,固定fixed
+  mode: {
+    type: String,
+    default: 'fixed',
+  },
+  pSpace: {
+    type: Number,
+    default: 5,
+  },
+  explain: {
+    type: String,
+    default: '',
+  },
+  imgSize: {
+    type: Object,
+    default() {
+      return {
+        width: '310px',
+        height: '155px',
+      }
+    },
+  },
+  blockSize: {
+    type: Object,
+    default() {
+      return {
+        width: '50px',
+        height: '50px',
+      }
+    },
+  },
+  barSize: {
+    type: Object,
+    default() {
+      return {
+        width: '310px',
+        height: '30px',
+      }
+    },
+  },
+})
+
+// 父级传递来的函数,用于回调
+const emit = defineEmits(['success', 'error', 'ready'])
+
+// const { t } = useI18n()
+const { mode, captchaType, type, blockSize, explain } = toRefs(props)
+const { proxy } = getCurrentInstance()
+const secretKey = ref('') // 后端返回的ase加密秘钥
+const passFlag = ref('') // 是否通过的标识
+const backImgBase = ref('') // 验证码背景图片
+const blockBackImgBase = ref('') // 验证滑块的背景图片
+const backToken = ref('') // 后端返回的唯一token值
+const startMoveTime = ref('') // 移动开始的时间
+const endMovetime = ref('') // 移动结束的时间
+const tipWords = ref('')
+const text = ref('')
+const finishText = ref('')
+const setSize = reactive({
+  imgHeight: 0,
+  imgWidth: 0,
+  barHeight: 0,
+  barWidth: 0,
+})
+const moveBlockLeft = ref(0)
+const leftBarWidth = ref(0)
+// 移动中样式
+const moveBlockBackgroundColor = ref(undefined)
+const leftBarBorderColor = ref('#ddd')
+const iconColor = ref(undefined)
+const iconClass = ref('icon-right')
+const status = ref(false) // 鼠标状态
+const isEnd = ref(false) // 是够验证完成
+const showRefresh = ref(true)
+const transitionLeft = ref('')
+const transitionWidth = ref('')
+const startLeft = ref(0)
+const instance = getCurrentInstance()
+const barArea = computed(() => {
+  const query = uni.createSelectorQuery().in(instance.proxy)
+  return query.select('.verify-bar-area')
+})
+const rectData = ref() // 布局数据
+function init() {
+  if (explain.value === '') {
+    text.value = '向右滑动完成验证'
+  } else {
+    text.value = explain.value
+  }
+  getPictrue()
+  nextTick(() => {
+    // let { imgHeight, imgWidth, barHeight, barWidth } = props.value.imgSize
+    setSize.imgHeight = props.imgSize.height
+    setSize.imgWidth = props.imgSize.width
+    setSize.barHeight = props.barSize.height
+    setSize.barWidth = props.barSize.width
+    emit('ready', proxy)
+  })
+}
+watch(type, () => {
+  init()
+})
+onMounted(() => {
+  // 禁止拖拽
+  init()
+  proxy.$el.onselectstart = function () {
+    return false
+  }
+})
+// 鼠标按下
+function start(e) {
+  e = e || window.event
+  let x = 0
+  if (!e.touches) {
+    // 兼容PC端
+    x = e.clientX
+  } else {
+    // 兼容移动端
+    x = e.touches[0].pageX
+  }
+  barArea.value.boundingClientRect((rect) => {
+    rectData.value = rect
+    startLeft.value = Math.floor(x - rect.left)
+  }).exec()
+  startMoveTime.value = +new Date() // 开始滑动的时间
+  if (isEnd.value === false) {
+    text.value = ''
+    moveBlockBackgroundColor.value = '#337ab7'
+    leftBarBorderColor.value = '#337AB7'
+    iconColor.value = '#fff'
+    e.stopPropagation()
+    status.value = true
+  }
+}
+// 鼠标移动
+function move(e) {
+  e = e || window.event
+  if (status.value && isEnd.value === false) {
+    let x = 0
+    if (!e.touches) {
+      // 兼容PC端
+      x = e.clientX
+    } else {
+      // 兼容移动端
+      x = e.touches[0].pageX
+    }
+    if (rectData.value) {
+      const bar_area_left = Math.ceil(rectData.value.left)
+      const barArea_offsetWidth = Math.ceil(rectData.value.width)
+      let move_block_left = x - bar_area_left // 小方块相对于父元素的left值
+      if (move_block_left
+        >= barArea_offsetWidth - Number.parseInt(Number.parseInt(blockSize.value.width) / 2) - 2
+      ) {
+        move_block_left
+          = barArea_offsetWidth - Number.parseInt(Number.parseInt(blockSize.value.width) / 2) - 2
+      }
+      if (move_block_left <= 0) {
+        move_block_left = Number.parseInt(Number.parseInt(blockSize.value.width) / 2)
+      }
+      // 拖动后小方块的left值
+      moveBlockLeft.value = `${move_block_left - Number.parseInt(Number.parseInt(blockSize.value.width) / 2)
+      }px`
+      leftBarWidth.value = `${move_block_left - Number.parseInt(Number.parseInt(blockSize.value.width) / 2)
+      }px`
+    }
+  }
+}
+
+// 鼠标松开
+function end() {
+  endMovetime.value = +new Date()
+  // 判断是否重合
+  if (status.value && isEnd.value === false) {
+    let moveLeftDistance = Number.parseInt((moveBlockLeft.value || '0').replace('px', ''))
+    moveLeftDistance = (moveLeftDistance * 310) / Number.parseInt(setSize.imgWidth)
+    const data = {
+      captchaType: captchaType.value,
+      pointJson: secretKey.value
+        ? aesEncrypt(JSON.stringify({ x: moveLeftDistance, y: 5.0 }), secretKey.value)
+        : JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
+      token: backToken.value,
+    }
+    checkCaptcha(data).then((res) => {
+      if (res.repCode === '0000') {
+        moveBlockBackgroundColor.value = '#5cb85c'
+        leftBarBorderColor.value = '#5cb85c'
+        iconColor.value = '#fff'
+        iconClass.value = 'icon-check'
+        showRefresh.value = false
+        isEnd.value = true
+        if (mode.value === 'pop') {
+          setTimeout(() => {
+            proxy.$parent.clickShow = false
+            refresh()
+          }, 1500)
+        }
+        passFlag.value = true
+        tipWords.value = `${((endMovetime.value - startMoveTime.value) / 1000).toFixed(2)}s 验证成功`
+        const captchaVerification = secretKey.value
+          ? aesEncrypt(
+              `${backToken.value}---${JSON.stringify({ x: moveLeftDistance, y: 5.0 })}`,
+              secretKey.value,
+            )
+          : `${backToken.value}---${JSON.stringify({ x: moveLeftDistance, y: 5.0 })}`
+        setTimeout(() => {
+          tipWords.value = ''
+          emit('success', { captchaVerification })
+        }, 1000)
+      } else {
+        moveBlockBackgroundColor.value = '#d9534f'
+        leftBarBorderColor.value = '#d9534f'
+        iconColor.value = '#fff'
+        iconClass.value = 'icon-close'
+        passFlag.value = false
+        setTimeout(() => {
+          refresh()
+        }, 1000)
+        emit('error', proxy)
+        tipWords.value = '验证失败'
+        setTimeout(() => {
+          tipWords.value = ''
+        }, 1000)
+      }
+    })
+    status.value = false
+  }
+}
+
+async function refresh() {
+  showRefresh.value = true
+  finishText.value = ''
+
+  transitionLeft.value = 'left .3s'
+  moveBlockLeft.value = 0
+
+  leftBarWidth.value = 0
+  transitionWidth.value = 'width .3s'
+
+  leftBarBorderColor.value = '#ddd'
+  moveBlockBackgroundColor.value = '#fff'
+  iconColor.value = '#000'
+  iconClass.value = 'icon-right'
+  isEnd.value = false
+
+  await getPictrue()
+  setTimeout(() => {
+    transitionWidth.value = ''
+    transitionLeft.value = ''
+    text.value = explain.value
+  }, 300)
+}
+
+// 请求背景图片和验证图片
+async function getPictrue() {
+  const data = {
+    captchaType: captchaType.value,
+  }
+  const res = await getCode(data)
+
+  if (res.repCode === '0000') {
+    backImgBase.value = res.repData.originalImageBase64
+    blockBackImgBase.value = res.repData.jigsawImageBase64
+    backToken.value = res.repData.token
+    secretKey.value = res.repData.secretKey
+  } else {
+    tipWords.value = res.repMsg
+  }
+}
+</script>

+ 14 - 0
src/pages/auth/components/Verifition/utils/ase.ts

@@ -0,0 +1,14 @@
+import CryptoJS from 'crypto-js'
+/**
+ * @word 要加密的内容
+ * @keyWord String  服务器随机返回的关键字
+ */
+export function aesEncrypt(word, keyWord = 'XwKsGlMcdPMEhR1B') {
+  const key = CryptoJS.enc.Utf8.parse(keyWord)
+  const srcs = CryptoJS.enc.Utf8.parse(word)
+  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
+    mode: CryptoJS.mode.ECB,
+    padding: CryptoJS.pad.Pkcs7,
+  })
+  return encrypted.toString()
+}

+ 65 - 40
src/pages/auth/login.vue

@@ -27,7 +27,12 @@
           no-border
         />
       </view>
-
+      <view v-if="captchaEnabled">
+        <Verify
+          ref="verifyRef" :captcha-type="captchaType" explain="向右滑动完成验证"
+          :img-size="{ width: '300px', height: '150px' }" mode="pop" @success="verifySuccess"
+        />
+      </view>
       <!-- 登录按钮 -->
       <view class="mb-2 mt-2 flex justify-between">
         <text class="text-28rpx text-[#1890ff]" @click="goToSmsLogin">
@@ -70,107 +75,127 @@
 </template>
 
 <script lang="ts" setup>
-import { reactive, ref } from "vue";
-import { useToast } from "wot-design-uni";
+import { reactive, ref } from 'vue'
+import { useToast } from 'wot-design-uni'
 import {
   CODE_LOGIN_PAGE,
   FORGET_PASSWORD_PAGE,
   REGISTER_PAGE,
-} from "@/router/config";
-import { useTokenStore } from "@/store/token";
-import { ensureDecodeURIComponent, redirectAfterLogin } from "@/utils";
-import Header from "./components/header.vue";
-import TenantPicker from "./components/tenant-picker.vue";
+} from '@/router/config'
+import { useTokenStore } from '@/store/token'
+import { ensureDecodeURIComponent, redirectAfterLogin } from '@/utils'
+import Header from './components/header.vue'
+import TenantPicker from './components/tenant-picker.vue'
+import Verify from './components/Verifition/Verify.vue'
 
 defineOptions({
-  name: "LoginPage",
+  name: 'LoginPage',
   style: {
-    navigationStyle: "custom",
+    navigationStyle: 'custom',
   },
-});
+})
 
 definePage({
   style: {
-    navigationStyle: "custom",
+    navigationStyle: 'custom',
   },
-});
+})
 
-const toast = useToast();
-const loading = ref(false); // 加载状态
-const redirectUrl = ref<string>(); // 重定向地址
-const tenantPickerRef = ref<InstanceType<typeof TenantPicker>>(); // 租户选择器引用
+const toast = useToast()
+const loading = ref(false) // 加载状态
+const redirectUrl = ref<string>() // 重定向地址
+const tenantPickerRef = ref<InstanceType<typeof TenantPicker>>() // 租户选择器引用
+const captchaEnabled = import.meta.env.VITE_APP_CAPTCHA_ENABLE === 'true' // 验证码开关
+const verifyRef = ref()
+const captchaType = ref('blockPuzzle') // 滑块验证码 blockPuzzle|clickWord
 
 const formData = reactive({
-  username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || "",
-  password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || "",
-}); // 表单数据
+  username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
+  password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
+  captchaVerification: '', // 验证码校验值
+}) // 表单数据
 
 /** 页面加载时处理重定向 */
 onLoad((options) => {
   if (options?.redirect) {
-    redirectUrl.value = ensureDecodeURIComponent(options.redirect);
+    redirectUrl.value = ensureDecodeURIComponent(options.redirect)
+  }
+})
+
+/** 获取验证码 */
+async function getCode() {
+  // 情况一,未开启:则直接登录
+  if (!captchaEnabled) {
+    await verifySuccess({})
+  } else {
+    // 情况二,已开启:则展示验证码;只有完成验证码的情况,才进行登录
+    // 弹出验证码
+    verifyRef.value.show()
   }
-});
+}
 
 /** 登录处理 */
 async function handleLogin() {
   if (!tenantPickerRef.value?.validate()) {
-    return;
+    return
   }
   if (!formData.username) {
-    toast.warning("请输入用户名");
-    return;
+    toast.warning('请输入用户名')
+    return
   }
   if (!formData.password) {
-    toast.warning("请输入密码");
-    return;
+    toast.warning('请输入密码')
+    return
   }
-
-  loading.value = true;
+  await getCode()
+}
+async function verifySuccess(params) {
+  loading.value = true
   try {
     // 调用登录接口
-    const tokenStore = useTokenStore();
+    const tokenStore = useTokenStore()
+    formData.captchaVerification = params.captchaVerification
     await tokenStore.login({
-      type: "username",
+      type: 'username',
       ...formData,
-    });
+    })
     // 处理跳转
-    redirectAfterLogin(redirectUrl.value);
+    redirectAfterLogin(redirectUrl.value)
   } finally {
-    loading.value = false;
+    loading.value = false
   }
 }
 
 /** 跳转到注册页面 */
 function goToRegister() {
-  uni.navigateTo({ url: REGISTER_PAGE });
+  uni.navigateTo({ url: REGISTER_PAGE })
 }
 
 /** 跳转到验证码登录 */
 function goToSmsLogin() {
-  uni.navigateTo({ url: CODE_LOGIN_PAGE });
+  uni.navigateTo({ url: CODE_LOGIN_PAGE })
 }
 
 /** 跳转到忘记密码 */
 function goToForgetPassword() {
-  uni.navigateTo({ url: FORGET_PASSWORD_PAGE });
+  uni.navigateTo({ url: FORGET_PASSWORD_PAGE })
 }
 
 /** 微信登录 */
 // TODO @芋艿:后续开发
 function handleWechatLogin() {
-  toast.info("微信登录功能开发中");
+  toast.info('微信登录功能开发中')
 }
 
 /** 钉钉登录 */
 // TODO @芋艿:后续开发
 function handleDingTalkLogin() {
-  toast.info("钉钉登录功能开发中");
+  toast.info('钉钉登录功能开发中')
 }
 </script>
 
 <style lang="scss" scoped>
-@import "./styles/auth.scss";
+@import './styles/auth.scss';
 
 // 第三方登录图标
 .icon-item {