login.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. url: '/pages/users/login/index'
  37. })
  38. }
  39. }
  40. } else {
  41. if (['/pages/user/index'].indexOf(login_back_url) === -1) {
  42. uni.navigateTo({
  43. url: '/pages/users/login/index'
  44. })
  45. }
  46. }
  47. // #endif
  48. if (['pages/user/index','/pages/user/index'].indexOf(login_back_url) === -1) {
  49. // #ifdef MP
  50. uni.navigateTo({
  51. url: '/pages/users/wechat_login/index'
  52. // url: '/pages/users/login/index'
  53. })
  54. // #endif
  55. }
  56. }
  57. export function checkLogin()
  58. {
  59. let token = Cache.get(LOGIN_STATUS);
  60. let expiresTime = Cache.get(EXPIRES_TIME);
  61. let newTime = Math.round(new Date() / 1000);
  62. if (expiresTime < newTime || !token){
  63. Cache.clear(LOGIN_STATUS);
  64. Cache.clear(EXPIRES_TIME);
  65. Cache.clear(USER_INFO);
  66. Cache.clear(STATE_R_KEY);
  67. return false;
  68. }else{
  69. store.commit('UPDATE_LOGIN',token);
  70. let userInfo = Cache.get(USER_INFO,true);
  71. if(userInfo){
  72. store.commit('UPDATE_USERINFO',userInfo);
  73. }
  74. return true;
  75. }
  76. }