LoginForm.vue 11 KB

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