LoginForm.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <template>
  2. <el-form
  3. v-show="getShow"
  4. ref="formLogin"
  5. :model="loginData.loginForm"
  6. :rules="LoginRules"
  7. class="login-form"
  8. label-position="top"
  9. label-width="120px"
  10. size="large"
  11. >
  12. <el-row class="mx-[-10px]">
  13. <el-col :span="24" class="px-10px">
  14. <el-form-item>
  15. <LoginFormTitle class="w-full" />
  16. </el-form-item>
  17. </el-col>
  18. <el-col :span="24" class="px-10px">
  19. <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
  20. <el-input
  21. v-model="loginData.loginForm.tenantName"
  22. :placeholder="t('login.tenantNamePlaceholder')"
  23. :prefix-icon="iconHouse"
  24. link
  25. type="primary"
  26. />
  27. </el-form-item>
  28. </el-col>
  29. <el-col :span="24" class="px-10px">
  30. <el-form-item prop="username">
  31. <el-input
  32. v-model="loginData.loginForm.username"
  33. :placeholder="t('login.usernamePlaceholder')"
  34. :prefix-icon="iconAvatar"
  35. />
  36. </el-form-item>
  37. </el-col>
  38. <el-col :span="24" class="px-10px">
  39. <el-form-item prop="password">
  40. <el-input
  41. v-model="loginData.loginForm.password"
  42. :placeholder="t('login.passwordPlaceholder')"
  43. :prefix-icon="iconLock"
  44. show-password
  45. type="password"
  46. @keyup.enter="getCode()"
  47. />
  48. </el-form-item>
  49. </el-col>
  50. <el-col :span="24" class="px-10px mt-[-20px] mb-[-20px]">
  51. <el-form-item>
  52. <el-row justify="space-between" style="width: 100%">
  53. <el-col :span="6">
  54. <el-checkbox v-model="loginData.loginForm.rememberMe">
  55. {{ t('login.remember') }}
  56. </el-checkbox>
  57. </el-col>
  58. <el-col :offset="6" :span="12">
  59. <el-link
  60. class="float-right"
  61. type="primary"
  62. @click="setLoginState(LoginStateEnum.RESET_PASSWORD)"
  63. >
  64. {{ t('login.forgetPassword') }}
  65. </el-link>
  66. </el-col>
  67. </el-row>
  68. </el-form-item>
  69. </el-col>
  70. <el-col :span="24" class="px-10px">
  71. <el-form-item>
  72. <XButton
  73. :loading="loginLoading"
  74. :title="t('login.login')"
  75. class="w-full"
  76. type="primary"
  77. @click="getCode()"
  78. />
  79. </el-form-item>
  80. </el-col>
  81. <Verify
  82. v-if="loginData.captchaEnable === 'true'"
  83. ref="verify"
  84. :captchaType="captchaType"
  85. :imgSize="{ width: '400px', height: '200px' }"
  86. mode="pop"
  87. @success="handleLogin"
  88. />
  89. <el-col :span="24" class="px-10px">
  90. <el-form-item>
  91. <el-row :gutter="5" justify="space-between" style="width: 100%">
  92. <el-col :span="8">
  93. <XButton
  94. :title="t('login.btnMobile')"
  95. class="w-full"
  96. @click="setLoginState(LoginStateEnum.MOBILE)"
  97. />
  98. </el-col>
  99. <el-col :span="8">
  100. <XButton
  101. :title="t('login.btnQRCode')"
  102. class="w-full"
  103. @click="setLoginState(LoginStateEnum.QR_CODE)"
  104. />
  105. </el-col>
  106. <el-col :span="8">
  107. <XButton
  108. :title="t('login.btnRegister')"
  109. class="w-full"
  110. @click="setLoginState(LoginStateEnum.REGISTER)"
  111. />
  112. </el-col>
  113. </el-row>
  114. </el-form-item>
  115. </el-col>
  116. <el-divider content-position="center">{{ t('login.otherLogin') }}</el-divider>
  117. <el-col :span="24" class="px-10px">
  118. <el-form-item>
  119. <div class="w-full flex justify-between">
  120. <Icon
  121. v-for="(item, key) in socialList"
  122. :key="key"
  123. :icon="item.icon"
  124. :size="30"
  125. class="anticon cursor-pointer"
  126. color="#999"
  127. @click="doSocialLogin(item.type)"
  128. />
  129. </div>
  130. </el-form-item>
  131. </el-col>
  132. <el-divider content-position="center">萌新必读</el-divider>
  133. <el-col :span="24" class="px-10px">
  134. <el-form-item>
  135. <div class="w-full flex justify-between">
  136. <el-link href="https://doc.iocoder.cn/" target="_blank">📚开发指南</el-link>
  137. <el-link href="https://doc.iocoder.cn/video/" target="_blank">🔥视频教程</el-link>
  138. <el-link href="https://www.iocoder.cn/Interview/good-collection/" target="_blank">
  139. ⚡面试手册
  140. </el-link>
  141. <el-link href="http://static.yudao.iocoder.cn/mp/Aix9975.jpeg" target="_blank">
  142. 🤝外包咨询
  143. </el-link>
  144. </div>
  145. </el-form-item>
  146. </el-col>
  147. </el-row>
  148. </el-form>
  149. </template>
  150. <script lang="ts" setup>
  151. import { ElLoading } from 'element-plus'
  152. import LoginFormTitle from './LoginFormTitle.vue'
  153. import type { RouteLocationNormalizedLoaded } from 'vue-router'
  154. import { useIcon } from '@/hooks/web/useIcon'
  155. import * as authUtil from '@/utils/auth'
  156. import { usePermissionStore } from '@/store/modules/permission'
  157. import * as LoginApi from '@/api/login'
  158. import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
  159. defineOptions({ name: 'LoginForm' })
  160. const { t } = useI18n()
  161. const message = useMessage()
  162. const iconHouse = useIcon({ icon: 'ep:house' })
  163. const iconAvatar = useIcon({ icon: 'ep:avatar' })
  164. const iconLock = useIcon({ icon: 'ep:lock' })
  165. const formLogin = ref()
  166. const { validForm } = useFormValid(formLogin)
  167. const { setLoginState, getLoginState } = useLoginState()
  168. const { currentRoute, push } = useRouter()
  169. const permissionStore = usePermissionStore()
  170. const redirect = ref<string>('')
  171. const loginLoading = ref(false)
  172. const verify = ref()
  173. const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字 pictureWord 文字验证码
  174. const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)
  175. const LoginRules = {
  176. tenantName: [required],
  177. username: [required],
  178. password: [required]
  179. }
  180. const loginData = reactive({
  181. isShowPassword: false,
  182. captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  183. tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  184. loginForm: {
  185. tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
  186. username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
  187. password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
  188. captchaVerification: '',
  189. rememberMe: true // 默认记录我。如果不需要,可手动修改
  190. }
  191. })
  192. const socialList = [
  193. { icon: 'ant-design:wechat-filled', type: 30 },
  194. { icon: 'ant-design:dingtalk-circle-filled', type: 20 },
  195. { icon: 'ant-design:github-filled', type: 0 },
  196. { icon: 'ant-design:alipay-circle-filled', type: 0 }
  197. ]
  198. // 获取验证码
  199. const getCode = async () => {
  200. // 情况一,未开启:则直接登录
  201. if (loginData.captchaEnable === 'false') {
  202. await handleLogin({})
  203. } else {
  204. // 情况二,已开启:则展示验证码;只有完成验证码的情况,才进行登录
  205. // 弹出验证码
  206. verify.value.show()
  207. }
  208. }
  209. // 获取租户 ID
  210. const getTenantId = async () => {
  211. if (loginData.tenantEnable === 'true') {
  212. const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
  213. authUtil.setTenantId(res)
  214. }
  215. }
  216. // 记住我
  217. const getLoginFormCache = () => {
  218. const loginForm = authUtil.getLoginForm()
  219. if (loginForm) {
  220. loginData.loginForm = {
  221. ...loginData.loginForm,
  222. username: loginForm.username ? loginForm.username : loginData.loginForm.username,
  223. password: loginForm.password ? loginForm.password : loginData.loginForm.password,
  224. rememberMe: loginForm.rememberMe,
  225. tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
  226. }
  227. }
  228. }
  229. // 根据域名,获得租户信息
  230. const getTenantByWebsite = async () => {
  231. if (loginData.tenantEnable === 'true') {
  232. const website = location.host
  233. const res = await LoginApi.getTenantByWebsite(website)
  234. if (res) {
  235. loginData.loginForm.tenantName = res.name
  236. authUtil.setTenantId(res.id)
  237. }
  238. }
  239. }
  240. const loading = ref() // ElLoading.service 返回的实例
  241. // 登录
  242. const handleLogin = async (params: any) => {
  243. loginLoading.value = true
  244. try {
  245. await getTenantId()
  246. const data = await validForm()
  247. if (!data) {
  248. return
  249. }
  250. const loginDataLoginForm = { ...loginData.loginForm }
  251. loginDataLoginForm.captchaVerification = params.captchaVerification
  252. const res = await LoginApi.login(loginDataLoginForm)
  253. if (!res) {
  254. return
  255. }
  256. loading.value = ElLoading.service({
  257. lock: true,
  258. text: '正在加载系统中...',
  259. background: 'rgba(0, 0, 0, 0.7)'
  260. })
  261. if (loginDataLoginForm.rememberMe) {
  262. authUtil.setLoginForm(loginDataLoginForm)
  263. } else {
  264. authUtil.removeLoginForm()
  265. }
  266. authUtil.setToken(res)
  267. if (!redirect.value) {
  268. redirect.value = '/'
  269. }
  270. // 判断是否为SSO登录
  271. if (redirect.value.indexOf('sso') !== -1) {
  272. window.location.href = window.location.href.replace('/login?redirect=', '')
  273. } else {
  274. await push({ path: redirect.value || permissionStore.addRouters[0].path })
  275. }
  276. } finally {
  277. loginLoading.value = false
  278. loading.value.close()
  279. }
  280. }
  281. // 社交登录
  282. const doSocialLogin = async (type: number) => {
  283. if (type === 0) {
  284. message.error('此方式未配置')
  285. } else {
  286. loginLoading.value = true
  287. if (loginData.tenantEnable === 'true') {
  288. // 尝试先通过 tenantName 获取租户
  289. await getTenantId()
  290. // 如果获取不到,则需要弹出提示,进行处理
  291. if (!authUtil.getTenantId()) {
  292. try {
  293. const data = await message.prompt('请输入租户名称', t('common.reminder'))
  294. if (data?.action !== 'confirm') throw 'cancel'
  295. const res = await LoginApi.getTenantIdByName(data.value)
  296. authUtil.setTenantId(res)
  297. } catch (error) {
  298. if (error === 'cancel') return
  299. } finally {
  300. loginLoading.value = false
  301. }
  302. }
  303. }
  304. // 计算 redirectUri
  305. // 注意: type、redirect 需要先 encode 一次,否则钉钉回调会丢失。
  306. // 配合 social-login.vue#getUrlValue() 使用
  307. const redirectUri =
  308. location.origin +
  309. '/social-login?' +
  310. encodeURIComponent(`type=${type}&redirect=${redirect.value || '/'}`)
  311. // 进行跳转
  312. window.location.href = await LoginApi.socialAuthRedirect(type, encodeURIComponent(redirectUri))
  313. }
  314. }
  315. watch(
  316. () => currentRoute.value,
  317. (route: RouteLocationNormalizedLoaded) => {
  318. redirect.value = route?.query?.redirect as string
  319. },
  320. {
  321. immediate: true
  322. }
  323. )
  324. onMounted(() => {
  325. getLoginFormCache()
  326. getTenantByWebsite()
  327. })
  328. </script>
  329. <style lang="scss" scoped>
  330. :deep(.anticon) {
  331. &:hover {
  332. color: var(--el-color-primary) !important;
  333. }
  334. }
  335. .login-code {
  336. float: right;
  337. width: 100%;
  338. height: 38px;
  339. img {
  340. width: 100%;
  341. height: auto;
  342. max-width: 100px;
  343. vertical-align: middle;
  344. cursor: pointer;
  345. }
  346. }
  347. </style>