mcya / JavaScriptExperience

👮 JavaScript Experience for web(JavaScript归类:简单入门+数组+经典循环+字符串+函数+Date日期+简单对象+BOM+DOM) +[ Issues(js实用技巧)]
29 stars 8 forks source link

控制登录 #54

Open mcya opened 5 years ago

mcya commented 5 years ago

登录/退出 系列

mcya commented 5 years ago

react+antd - xsSystem

参考项目地址: react-antd-DEMO-Project

验证方式 - 添加一个的登录或者登出的标记, 再在router的中验证。 - router.js

import Cookies from 'js-cookie' // npm install js-cookie  -  "js-cookie": "^2.1.1"

export const setCookieItem = (name, value) => { //set Cookies
  Cookies.set(name, value);
}
export const getCookieItem = (name) => { //get Cookies
  const value = Cookies.get(name);
  return value === undefined || value === 'undefined' ? null : value;
}
export const removeCookieItem = (name) => { //remove Cookies
  Cookies.remove(name);
}

/*获取缓存在cookie的登录标记*/
export const getUserAuth = () => {
  return getCookieItem(USER_AUTH);
}
/*缓存用户登录后的信息*/
export const cacheLoginInfo = (res) => {
  setCookieItem(USER_AUTH, true);
}
/*session过期或退出登录之后,清除用户登录信息*/
export const cleanLoginInfo = () => {
  Cookies.remove(USER_AUTH);
}
// 在路由群载入时做 filter 处理, 即在 <Route>中都需要调用 validate
function validate(store, [nextState, replace]) {
  const userInfo = getUserAuth();
  if (!userInfo) {
    cleanLoginInfo();
    replace('/login');
  }
}

// 路由 demo
const Routes = ({ history, store }) =>
<Router history={history}>
  <Route
    path="login"
    getComponent={(location, cb)=> {
       require.ensure([], require => { cb(null, require('../apps/login')) }, 'login')
     }}
   />

    <Route path="/"
      component={App}
      onEnter={(...args) => {validate(store, args);}}
      onChange={(prevState, nextState) => {
        if (nextState.location.action !== 'POP') { window.scrollTo(0, 0);} //路由切换新界面时,重置滚动条位置
      }}
    >
    <IndexRedirect to="workBench" />
        {/* import { generateRoutes } from './myrouters.js' 其他的路由 */}
        { generateRoutes() }
     </Route>

    <Route path="*" component={NotFound} />
</Router>;
mcya commented 5 years ago

vue-project

同样的原理,添加登录成功标记后需要在router进行验证拦截 - main.js

// 登录成功后, 保存登录信息到 store 中
this.$store.commit('isLogin', true);

// 路由拦截 - main.js
router.beforeEach(function (to, from, next) {
  //不需要授权的页面,放行
  if(to.meta.isIgnoreAuth==true){
    next();
    return;
  }

  let isLoginSuccess=store.state.core.isLogin;
  //没有登录,需要跳到登录页面
  if(isLoginSuccess==true||isLoginSuccess=='true'){
     //已经登录,往下走
    next();
  }else{
    next('/login')
  }

})

/******************拦截器设置请参考这部分(开始)******************/

Vue.http.interceptors.push(function(request, next) {

  let url=request.url;
  let loginInfo=this.$store.state.core.loginInfo;

  //请求时,加上token
  let isLoginSuccess=this.$store.state.core.isLogin;

    this.$vux.loading.show({text: '数据加载中', width:'200px'});// 显示Loading

  if(isLoginSuccess==true||isLoginSuccess=='true'){
      if(loginInfo!=null){
        request.body.token=loginInfo.token;
      }
   }
      next((response) => {
        this.$vux.loading.hide();
          return response;
      });

});

/******************拦截器设置请参考这部分(结束)******************/
router.beforeEach(function (to,from,next) {
    //不需要授权的页面,放行
    if(to.meta.isIgnoreAuth==true){
        next();
        return;
    }
  let isLoginSuccess=store.state.core.isLogin;

  //没有登录,需要跳到登录页面
  if(isLoginSuccess==true||isLoginSuccess=='true'){
     //已经登录,往下走
    next();
  }else{
    next('/login')
  }

})
import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'
import Vuex from 'vuex'
import FastClick from 'fastclick'

import { ToastPlugin } from 'vux'
import vuexI18n from 'vuex-i18n'
import store from './store/store'
import { ConfirmPlugin } from 'vux' //弹框
import { LoadingPlugin } from 'vux' //加载状态显示Loading

Vue.use(router)
Vue.use(VueResource)
let store1 = new Vuex.Store({
    modules: {
        i18n: vuexI18n.store
    }
})
Vue.use(vuexI18n.plugin, store1)
Vue.use(LoadingPlugin)
Vue.use(ConfirmPlugin)
Vue.use(ToastPlugin) //提示窗口

FastClick.attach(document.body)

Vue.config.productionTip = false

Vue.http.options.emulateJSON = true;
Vue.http.options.crossOrigin = true;
Vue.http.options.emulateHTTP = true;

Vue.prototype.HOST = '/api' //开发的时候用到

/******************拦截器设置请参考这部分(开始)******************/
Vue.http.interceptors.push(function(request, next) {

  let url=request.url;
  let loginInfo=this.$store.state.core.loginInfo;

  //请求时,加上token
  let isLoginSuccess=this.$store.state.core.isLogin;

    this.$vux.loading.show({text: '数据加载中', width:'200px'});// 显示Loading

  if(isLoginSuccess==true||isLoginSuccess=='true'){
      if(loginInfo!=null){
        request.body.token=loginInfo.token;
      }
   }
      next((response) => {
        this.$vux.loading.hide();
          return response;
      });

});

/******************拦截器设置请参考这部分(结束)******************/
router.beforeEach(function (to,from,next) {
    //不需要授权的页面,放行
    if(to.meta.isIgnoreAuth==true){
        next();
        return;
    }
  let isLoginSuccess=store.state.core.isLogin;

  //没有登录,需要跳到登录页面
  if(isLoginSuccess==true||isLoginSuccess=='true'){
     //已经登录,往下走
    next();
  }else{
    next('/login')
  }
})

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app-box')