user.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * 用户相关服务
  3. */
  4. const util = require('../utils/util.js');
  5. const api = require('../config/api.js');
  6. var app = getApp();
  7. /**
  8. * 调用微信登录
  9. */
  10. function loginByWeixin() {
  11. let code = null;
  12. return new Promise(function(resolve, reject) {
  13. return util.login().then((res) => {
  14. code = res.code;
  15. return util.getUserInfo(); //接口改了,用不了
  16. }).then((userInfo) => {
  17. //登录远程服务器
  18. util.request(api.AuthLoginByWeixin, {
  19. code: code,
  20. userInfo: userInfo
  21. }, 'POST').then(res => {
  22. if (res.errno === 0) {
  23. //存储用户信息
  24. wx.setStorageSync('userInfo', res.data.userInfo);
  25. wx.setStorageSync('token', res.data.token);
  26. resolve(res);
  27. } else {
  28. reject(res);
  29. }
  30. }).catch((err) => {
  31. reject(err);
  32. });
  33. }).catch((err) => {
  34. reject(err);
  35. })
  36. });
  37. }
  38. /**
  39. * 判断用户是否登录
  40. */
  41. function checkLogin() {
  42. return new Promise(function(resolve, reject) {
  43. if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
  44. util.checkSession().then(() => {
  45. resolve(true);
  46. }).catch(() => {
  47. reject(false); //session过期
  48. });
  49. } else {
  50. reject(false); //没有登陆过
  51. }
  52. });
  53. }
  54. /**
  55. * 判断用户是否已授权获取userInfo
  56. */
  57. function checkUserAuth() {
  58. return new Promise(function(resolve, reject) {
  59. wx.getSetting({
  60. success: res => {
  61. if (res.authSetting['scope.userInfo']) {
  62. // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
  63. resolve(true);
  64. }else{
  65. reject(false);
  66. }
  67. }
  68. })
  69. })
  70. }
  71. module.exports = {
  72. loginByWeixin,
  73. checkLogin,
  74. checkUserAuth,
  75. };