login.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import store from "../store";
  2. import Cache from '../utils/cache';
  3. import { Debounce } from '@/utils/validate.js'
  4. // #ifdef H5
  5. import { isWeixin } from "../utils";
  6. import auth from './wechat';
  7. // #endif
  8. import { LOGIN_STATUS, USER_INFO, EXPIRES_TIME, STATE_R_KEY, BACK_URL} from './../config/cache';
  9. function prePage(){
  10. let pages = getCurrentPages();
  11. let prePage = pages[pages.length - 1];
  12. return prePage.route;
  13. }
  14. export const toLogin = Debounce(_toLogin,800)
  15. export function _toLogin(push, pathLogin) {
  16. store.commit("LOGOUT");
  17. let path = prePage();
  18. let login_back_url = Cache.get(BACK_URL);
  19. // #ifdef H5
  20. // path = location.href;
  21. path = location.pathname + location.search;
  22. // #endif
  23. if(!pathLogin){
  24. pathLogin = '/page/users/login/index'
  25. Cache.set('login_back_url',path);
  26. }
  27. // #ifdef H5
  28. if (isWeixin()) {
  29. let urlData = location.pathname + location.search
  30. if (!Cache.has('snsapiKey')) {
  31. auth.oAuth('snsapi_base', urlData);
  32. } else {
  33. if (['/pages/user/index'].indexOf(login_back_url) === -1) {
  34. uni.navigateTo({
  35. url: '/pages/users/wechat_login/index'
  36. })
  37. }
  38. }
  39. } else {
  40. if (['/pages/user/index'].indexOf(login_back_url) === -1) {
  41. uni.navigateTo({
  42. url: '/pages/users/login/index'
  43. })
  44. }
  45. }
  46. // #endif
  47. if (['pages/user/index','/pages/user/index'].indexOf(login_back_url) === -1) {
  48. // #ifdef MP
  49. uni.navigateTo({
  50. url: '/pages/users/wechat_login/index'
  51. })
  52. // #endif
  53. }
  54. }
  55. export function checkLogin()
  56. {
  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. }