login.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {
  2. CACHE_USERINFO,
  3. CACHE_TOKEN,
  4. CACHE_EXPIRES_TIME
  5. } from '../config.js';
  6. import {
  7. login_simple,
  8. } from '../api/user.js';
  9. // 新的登录逻辑实现文件
  10. // 新的逻辑要求尽量减少用户授权确认,用户只有在首次注册时和以后定期不定期的才需要确认(用于获取用户微信头像等资料)上传资料用于注册、系统同步更新用户资料。
  11. // 静默登录,不再需要用户授权。
  12. // 用于小程序启动后,token 过期的情况下,后台静默登录。如果失败,则不用处理,等待后续的用户授权过程。
  13. export function loginSilently() {
  14. return new Promise((resolve, reject) => {
  15. wx.login({
  16. success: (login_res) => {
  17. login_simple({
  18. code: login_res.code
  19. }).then((simple_res) => {
  20. if (simple_res.data.status == 1) {
  21. // 需要提交用户资料,此时必须有 cache_key
  22. if (simple_res.data.cache_key) {
  23. wx.setStorage({
  24. key: 'cache_key',
  25. data: simple_res.data.cache_key
  26. });
  27. } else {
  28. reject({
  29. err: '登录失败'
  30. });
  31. }
  32. reject({
  33. status: 1,
  34. err: ''
  35. });
  36. } else if (simple_res.data.status == 0) {
  37. // todo: clear cache_key
  38. wx.removeStorage({
  39. key: 'cache_key',
  40. });
  41. var app = getApp();
  42. app.globalData.token = simple_res.data.token;
  43. app.globalData.isLog = true;
  44. app.globalData.userInfo = simple_res.data.userInfo;
  45. app.globalData.expiresTime = simple_res.data.expires_time;
  46. wx.setStorageSync(CACHE_TOKEN, simple_res.data.token);
  47. wx.setStorageSync(CACHE_EXPIRES_TIME, simple_res.data.expires_time);
  48. wx.setStorageSync(CACHE_USERINFO, JSON.stringify(simple_res.data.userInfo));
  49. resolve(simple_res.data);
  50. }
  51. }).catch((err) => {
  52. reject({
  53. err: err
  54. });
  55. })
  56. },
  57. fail: (err) => {
  58. reject({
  59. err: err
  60. })
  61. }
  62. })
  63. });
  64. }