login.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {
  2. silentLogin
  3. } from '@/api/app';
  4. import {
  5. isWeixinClient,
  6. currentPage,
  7. trottle
  8. } from './tools'
  9. import store from '@/store'
  10. import Cache from './cache'
  11. import {
  12. BACK_URL,
  13. INVITE_CODE
  14. } from '@/config/cachekey'
  15. import wechath5 from './wechath5'
  16. import {router} from '@/router'
  17. // 获取登录凭证(code)
  18. export function getWxCode() {
  19. return new Promise((resolve, reject) => {
  20. uni.login({
  21. success(res) {
  22. resolve(res.code);
  23. },
  24. fail(res) {
  25. reject(res);
  26. }
  27. });
  28. });
  29. }
  30. //小程序获取用户信息
  31. export function getUserProfile() {
  32. return new Promise((resolve, reject) => {
  33. uni.getUserProfile({
  34. desc: '获取用户信息,完善用户资料 ',
  35. success: (res) => {
  36. resolve(res);
  37. },
  38. fail(res) {}
  39. })
  40. })
  41. }
  42. //小程序静默授权
  43. export async function wxMnpLogin() {
  44. const code = await getWxCode()
  45. const {
  46. code: loginCode,
  47. data: loginData
  48. } = await silentLogin({
  49. code
  50. })
  51. const {
  52. options,
  53. onLoad,
  54. onShow,
  55. route
  56. } = currentPage()
  57. if (loginCode != 1) return
  58. if (loginData.token) {
  59. store.commit('login', loginData)
  60. // 绑定邀请码
  61. const inviteCode = Cache.get(INVITE_CODE)
  62. const optionsSync = Cache.get('OptionsSync')
  63. if (inviteCode) {
  64. Cache.remove(INVITE_CODE)
  65. Cache.remove('OptionsSync')
  66. }
  67. // 刷新页面
  68. onLoad && onLoad(options)
  69. onShow && onShow()
  70. }
  71. }
  72. export const toLogin = trottle(_toLogin, 1000)
  73. function _toLogin() {
  74. //#ifdef MP-WEIXIN
  75. // wxMnpLogin()
  76. // #endif
  77. //#ifndef MP-WEIXIN
  78. const {currentRoute} = router
  79. if(currentRoute.meta.auth) {
  80. router.push('/pages/login/login')
  81. }
  82. // #endif
  83. }