auth.js 2.0 KB

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