sso.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { message } from 'antd'
  2. import router from '../router/index.tsx'
  3. import http from './index'
  4. import {
  5. userLogin, sendVerificationCode, loginPhone,
  6. } from './api.ts'
  7. type UserInfo = {
  8. channel: string,
  9. contactName: string,
  10. createTimestamp: number,
  11. id: number,
  12. identity: number,
  13. name: string,
  14. telNum: string,
  15. token: string
  16. }
  17. export function getUserInfo(): UserInfo {
  18. const activeUser = localStorage.getItem('userInfo')
  19. return activeUser ? JSON.parse(activeUser) : {}
  20. }
  21. export function getAccessToken(): string {
  22. const userInfo = getUserInfo()
  23. return userInfo.token
  24. }
  25. export function setUserInfo(userInfo: UserInfo): void {
  26. localStorage.removeItem('userInfo')
  27. localStorage.setItem('userInfo', JSON.stringify(userInfo))
  28. }
  29. export function clearUserInfo() {
  30. localStorage.removeItem('userInfo')
  31. }
  32. export function login(account: string, password: string) {
  33. return http.post<UserInfo>(userLogin, {
  34. telNum: account,
  35. password: window.btoa(password)
  36. }).then((res: ApiResponse<UserInfo>) => {
  37. const { code, msg, data } = res
  38. if (code === 0) {
  39. message.success('登录成功')
  40. setUserInfo(data)
  41. location.href = '/cooperationAccount/gzh'
  42. return true
  43. }
  44. message.error(msg)
  45. return false
  46. }).catch(() => {})
  47. }
  48. export function sendCode(phone: string) {
  49. return http.post(sendVerificationCode, {
  50. telNum: phone
  51. }).then(res => {
  52. const { code, msg = '发送失败' } = res
  53. if (code === 0) {
  54. message.success('短信已发送,请注意查收')
  55. return true
  56. }
  57. message.error(msg)
  58. return false
  59. }).catch(() => {})
  60. }
  61. export function loginBySendCode(telNum: string, verifyCode: string) {
  62. return http.post(loginPhone, {
  63. telNum,
  64. verifyCode
  65. }).then(res => {
  66. const { code, msg, data } = res as { code: number, msg: string, data: UserInfo }
  67. if (code === 0 && data) {
  68. message.success('登录成功')
  69. setUserInfo(data)
  70. router.navigate('/cooperationAccount/gzh')
  71. return true
  72. }
  73. message.error(msg)
  74. return false
  75. }).catch((err) => {
  76. console.log(err)
  77. })
  78. }
  79. export function logout() {
  80. message.success('已退出登录')
  81. clearUserInfo()
  82. router.navigate('/login')
  83. return true
  84. }
  85. export default {
  86. getUserInfo,
  87. setUserInfo,
  88. clearUserInfo,
  89. login,
  90. sendCode,
  91. loginBySendCode,
  92. logout,
  93. }