user.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. resolve(true);
  45. // util.checkSession().then(() => {
  46. // resolve(true);
  47. // }).catch(() => {
  48. // reject(false); //session过期
  49. // });
  50. } else {
  51. reject(false); //没有登陆过
  52. }
  53. });
  54. }
  55. function checkLoginAndNav() {
  56. return new Promise(function(resolve, reject) {
  57. if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
  58. resolve(true);
  59. } else {
  60. wx.navigateTo({
  61. url: '/pages/auth/auth'
  62. })
  63. reject(false); //没有登陆过
  64. }
  65. });
  66. }
  67. /**
  68. * 判断用户是否已授权获取userInfo
  69. */
  70. function checkUserAuth() {
  71. return new Promise(function(resolve, reject) {
  72. wx.getSetting({
  73. success: res => {
  74. if (res.authSetting['scope.userInfo']) {
  75. // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
  76. resolve(true);
  77. } else {
  78. reject(false);
  79. }
  80. }
  81. })
  82. })
  83. }
  84. module.exports = {
  85. loginByWeixin,
  86. checkLogin,
  87. checkUserAuth,
  88. checkLoginAndNav,
  89. };