auth.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. loginNew: !!wx.getUserProfile,
  12. canIUse: wx.canIUse('button.open-type.getUserInfo')
  13. },
  14. attached() {
  15. this.callback = () => {
  16. this.setData({show: !getApp().globalData.loginProps.isLogin})
  17. // let pages = getCurrentPages()
  18. // let currPage = pages[pages.length - 1].route
  19. // if (currPage === 'pages/discover/discover') {
  20. // this.setData({bottom: '50px'})
  21. // } else {
  22. // this.setData({bottom: 0})
  23. // }
  24. }
  25. this.callback()
  26. getApp().addLoginListener(this.callback)
  27. getSubOpen()
  28. },
  29. detached() {
  30. getApp().removeLoginListener(this.callback)
  31. },
  32. methods: {
  33. quitHandle: function() {
  34. getApp().setLoginProps(true)
  35. },
  36. getCode: function() {
  37. return new Promise(r => {
  38. wx.login({
  39. success: function(res) {
  40. if (res.code) {
  41. r(res.code)
  42. }
  43. }
  44. });
  45. })
  46. },
  47. authLogin() {
  48. this.triggerEvent('login')
  49. },
  50. bindGetUserInfo: async function(e) {
  51. if (this.data.loginNew) {
  52. let info = await new Promise(resolve => {
  53. wx.getUserProfile({
  54. desc: '获取用户昵称头像用作共享',
  55. success: resolve,
  56. fail(e) {
  57. console.error(e)
  58. }
  59. })
  60. })
  61. e.detail = info
  62. console.log('-----------------', e)
  63. }
  64. let code = await this.getCode()
  65. //登录远程服务器
  66. util.request(api.AuthLoginByWeixin, {
  67. code: code,
  68. userInfo: e.detail
  69. }, 'POST', 'application/json').then(res => {
  70. if (res.errno === 0) {
  71. //存储用户信息
  72. res.data.userInfo.userId = res.data.userId
  73. wx.setStorageSync('userInfo', res.data.userInfo);
  74. wx.setStorageSync('token', res.data.token);
  75. wx.setStorageSync('userId', res.data.userId);
  76. wx.setStorageSync('isLogin', true);
  77. getApp().setLoginProps(true)
  78. this.authLogin()
  79. getSubOpen()
  80. } else {
  81. // util.showErrorToast(res.errmsg)
  82. // wx.showModal({
  83. // title: '提示',
  84. // content: res.errmsg,
  85. // showCancel: false
  86. // });
  87. }
  88. });
  89. },
  90. }
  91. })