login.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import store from "../store";
  2. import Cache from '../utils/cache';
  3. // #ifdef H5 || APP-PLUS
  4. import {
  5. isWeixin
  6. } from "../utils";
  7. import auth from './wechat';
  8. // #endif
  9. import {
  10. LOGIN_STATUS,
  11. USER_INFO,
  12. EXPIRES_TIME,
  13. STATE_R_KEY
  14. } from './../config/cache';
  15. function prePage() {
  16. let pages = getCurrentPages();
  17. let prePage = pages[pages.length - 2];
  18. // #ifdef H5
  19. return prePage;
  20. // #endif
  21. return prePage.$vm;
  22. }
  23. export function toLogin(push, pathLogin) {
  24. // store.commit("LOGOUT");
  25. let path = prePage();
  26. if (path) {
  27. path = path.router;
  28. if (path == undefined) {
  29. path = location.pathname;
  30. }
  31. }
  32. // #ifdef H5
  33. else {
  34. path = location.pathname;
  35. }
  36. // #endif
  37. if (!pathLogin)
  38. pathLogin = '/page/users/login/index'
  39. Cache.set('login_back_url', path);
  40. // #ifdef H5 || APP-PLUS
  41. if (isWeixin()) {
  42. auth.oAuth();
  43. } else {
  44. if (path !== pathLogin) {
  45. push ? uni.navigateTo({
  46. url: '/pages/users/login/index'
  47. }) : uni.reLaunch({
  48. url: '/pages/users/login/index'
  49. });
  50. }
  51. }
  52. // #endif
  53. // #ifdef MP
  54. // #endif
  55. }
  56. export function checkLogin() {
  57. let token = Cache.get(LOGIN_STATUS);
  58. let expiresTime = Cache.get(EXPIRES_TIME);
  59. let newTime = Math.round(new Date() / 1000);
  60. if (expiresTime < newTime || !token) {
  61. Cache.clear(LOGIN_STATUS);
  62. Cache.clear(EXPIRES_TIME);
  63. Cache.clear(USER_INFO);
  64. Cache.clear(STATE_R_KEY);
  65. return false;
  66. } else {
  67. store.commit('UPDATE_LOGIN', token);
  68. let userInfo = Cache.get(USER_INFO, true);
  69. if (userInfo) {
  70. store.commit('UPDATE_USERINFO', userInfo);
  71. }
  72. return true;
  73. }
  74. }