auth.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // component/auth/auth.js
  2. const api = require('../../config/api')
  3. const util = require('../../utils/util.js');
  4. import {getSubOpen} from './api'
  5. Component({
  6. /**
  7. * 页面的初始数据
  8. */
  9. data: {
  10. show: false,
  11. canIUse: wx.canIUse('button.open-type.getUserInfo')
  12. },
  13. attached() {
  14. this.callback = () => {
  15. this.setData({show: !getApp().globalData.loginProps.isLogin})
  16. let pages = getCurrentPages()
  17. let currPage = pages[pages.length - 1].route
  18. if (currPage === 'pages/discover/discover') {
  19. this.setData({bottom: '50px'})
  20. } else {
  21. this.setData({bottom: 0})
  22. }
  23. }
  24. this.callback()
  25. getApp().addLoginListener(this.callback)
  26. getSubOpen()
  27. },
  28. detached() {
  29. getApp().removeLoginListener(this.callback)
  30. },
  31. methods: {
  32. quitHandle: function() {
  33. getApp().setLoginProps(true)
  34. },
  35. getCode: function() {
  36. return new Promise(r => {
  37. wx.login({
  38. success: function(res) {
  39. if (res.code) {
  40. r(res.code)
  41. }
  42. }
  43. });
  44. })
  45. },
  46. authLogin() {
  47. this.triggerEvent('login')
  48. },
  49. bindGetUserInfo: async function(e) {
  50. let code = await this.getCode()
  51. //登录远程服务器
  52. util.request(api.AuthLoginByWeixin, {
  53. code: code,
  54. userInfo: e.detail
  55. }, 'POST', 'application/json').then(res => {
  56. if (res.errno === 0) {
  57. //存储用户信息
  58. res.data.userInfo.userId = res.data.userId
  59. res.data.userInfo.sessionKey = res.data.sessionKey
  60. console.log('-------', res.data.userInfo)
  61. wx.setStorageSync('userInfo', res.data.userInfo);
  62. wx.setStorageSync('token', res.data.token);
  63. wx.setStorageSync('userId', res.data.userId);
  64. wx.setStorageSync('isLogin', true);
  65. getApp().setLoginProps(true)
  66. this.authLogin()
  67. getSubOpen()
  68. } else {
  69. // util.showErrorToast(res.errmsg)
  70. // wx.showModal({
  71. // title: '提示',
  72. // content: res.errmsg,
  73. // showCancel: false
  74. // });
  75. }
  76. });
  77. },
  78. }
  79. })