小程序7天自动退出

7天自动退出的场景:
1、7天没有点击按钮,
2、7天没有请求服务器


解决思路:
1、登录成功,记录当前登录时间,并存在缓存中,
2、登录状态下,点击按钮和请求服务器时,
    a 先判断当前时间和登录时间差是否大于7天,
    a.1 大于,则清空用户登录缓存信息,提示用户登录,
    a.2 不大于,则把当前时间作为新的登录时间


源码:

1、在common.js中统一存、取、清登录时间缓存

const common = {
  // 设置用户登录时间
  setLogintimeInfo: function (time) {
  	uni.setStorageSync('loginTime', time);
  },
  getLogintimeInfo: function () {
  	return uni.getStorageSync('loginTime');
  },
  removeLogintimeInfo: function () {
  	uni.removeStorageSync('loginTime');
  },
}

export default common;

2、在login.vue页面登录成功时,存当前时间

// 记录登录成功时间戳
let timestamp = new Date().getTime();
common.setLogintimeInfo(timestamp);

3、在request.js文件中实现7天自动退出方法

// 7天未登录,自动退出
function autoLogoutFor7Days(){
  let loginstamp=common.getLogintimeInfo();
  let currentstamp = new Date().getTime();
  if(currentstamp-loginstamp>7*24*60*60*1000){//7天内未请求
    // 1 清除用户登录信息
    common.removeGlobalUserInfo();
    common.removeLogintimeInfo();
    common.removeStorage('location');
    // 2 提示去登录,跳转到登录界面
    uni.showModal({
      content: '您7天内未登录,请重新登录',
      confirmText: '去登录',
      showCancel:false,
      success(res) {
        uni.navigateTo({
          url:"/pages/login/login",
        });
      }
    });
    return true;
  }else{//7天内请求了,重置请求时间戳
    common.setLogintimeInfo(currentstamp);
    return false;
   }
}

4、点击按钮时,实现7天退出的判断

function pageNavigator(isUrl, noUrl) {
	if (noUrl === undefined) noUrl = ''
	if (common.isLogin()) { //用户名存在
    // 查看登录状态下,7天内未请求,自动退出
    if(autoLogoutFor7Days()){
      return
    }else{
      uni.navigateTo({
      	url: '/pages/' + isUrl
      })
    }
	} else { //用户名不存在,传递过去登录之后返回界面的url
      uni.navigateTo({
        url: '/pages/login/login?navUrl=' + noUrl
      })
	}
}

5、请求服务器时,实现7天退出的判断

function setRequest(url, data, showLoad = true, method = 'post', header = {}) {
  // 7天内未请求,自动退出排除一些不需要登录就可以请求的接口
  if(url.indexOf("getParkInfo")==-1&&url.indexOf("indexSlideShow")==-1){
    autoLogoutFor7Days();
  }

  uni.request({
	...
  })
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章