前后端分离(session管理)(三)前后端综合前端

前端复用的是之前springsercurity的前端项目(四)SpringBoot+dubbo+Spring Sercurity+VUE实例----(前端)_vue+dubbo-CSDN博客

这里简单做下记录:

一、config:

dev.env.js:(只改动了这一个地方,替换了后端项目地址)

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  BASE_API: '"http://localhost:7777/shirodemo/"',
  //BASE_API: '"http://localhost:9999/demo/"',
})

二、permisson.js全局拦截认证:

import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.authorities.length === 0) {
        // 拉取用户权限信息
        store.dispatch('GetInfo').then(res => {
          //获取当前登录用户
          store.dispatch('GetCurrentUser').then(res=>{})

          // 从后端获取的权限
          const authorities = res
          // 前端路由加载动态权限
          store.dispatch('GenerateRoutes', { authorities }).then(() => { // 生成可访问的路由表
            // alert('store.getters.addRouters' + store.getters.addRouters.length)
            router.addRoutes(store.getters.addRouters)// 添加动态路由

            next({ ...to })// hack方法 确保addRoutes已完成
          })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

三、util:

request.js请求util:

import axios from 'axios'
// 配置session跨域
axios.defaults.withCredentials = true
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['token'] = store.getters.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  //文件上传
  if (config.method === 'post') {
    if (config.upload) { // 上传图片则添加headers
      config.headers['Content-Type'] = 'multipart/form-data'
      config.timeout = 360000
    } 
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    const res = response.data
    // 下载请求
    //if (res instanceof Blob) {
      //return res
    //}

    if (res.code !== 200 && res.code !=300) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      // 401 token失效
      if (res.code === 401) {
        // MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('FedLogOut').then(() => {
        //     location.reload()// 为了重新实例化vue-router对象 避免bug
        //   })
        // })
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

四、api:

1、login.js:

import request from '@/utils/request'

//获取验证码
export function getCode(){
  return request({
    url: '/code/getCode',
    method: 'get'
  })
}

//登录
export function login(user) {
  return request({
    url: '/login',
    method: 'post',
    datatype:'application/json',
    data:user
  })
}


//获取我的权限列表
export function getMyAuthorities() {
  return request({
    url: '/user/getMyAuthorities',
    method: 'post'
  })
}


//退出登录
export function logout() {
  return request({
    url: '/user/logout',
    method: 'get'
  })
}

五、store:

1、inex:

import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import permission from './modules/permission'
import user from './modules/user'
import getters from './getters'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    permission,
    user
  },
  getters
})

export default store

2、getters.js:

const getters = {
  sidebar: state => state.app.sidebar,
  //token
  token: state => state.user.token,
  //用户名
  name: state => state.user.name,
  //角色
  roles: state => state.user.roles,
  //后台返回的权限code
  authorities:state =>state.user.authorities,
  //动态权限路由
  permission_routers: state => state.permission.routers,
  //固定权限路由
  addRouters: state => state.permission.addRouters
}
export default getters

 3、app.js:

import Cookies from 'js-cookie'

const app = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      withoutAnimation: false
    },
    device: 'desktop'
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
      Cookies.set('sidebarStatus', 1)
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
    TOGGLE_DEVICE: (state, device) => {
      state.device = device
    }
  },
  actions: {
    ToggleSideBar: ({ commit }) => {
      commit('TOGGLE_SIDEBAR')
    },
    CloseSideBar({ commit }, { withoutAnimation }) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    ToggleDevice({ commit }, device) {
      commit('TOGGLE_DEVICE', device)
    }
  }
}

export default app

4、permission.js:

import { asyncRouterMap, constantRouterMap } from '@/router/index'

/**
 * 通过meta.authority判断是否与当前用户权限匹配
 * @param authorities
 * @param route
 */
function hasPermission(authorities, route) {
  if (route.meta && route.meta.authority) {
    return authorities.some(authority => route.meta.authority.indexOf(authority) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表,返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param authorities
 */
function filterAsyncRouter(asyncRouterMap, authorities) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(authorities, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, authorities)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { authorities } = data
        let accessedRouters
        if (authorities.indexOf('admin') >= 0) {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, authorities)
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission

 5、user.js:

import { login, logout, getMyAuthorities } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import{getCurrentUser} from '@/api/user'

const user = {
  state: {
    token: getToken(),
    name: '',
    authorities: [],
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_PERMISSION: (state, authorities) => {
      state.authorities = authorities
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, user) {
      const userName = user.userName
      const pwd = user.password
      return new Promise((resolve, reject) => {
        login(user).then(response => {
          const data = response.data
          setToken(data)
          commit('SET_TOKEN', data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    //获取登录用户
    GetCurrentUser({ commit }) {
      return new Promise((resolve, reject) => {
        getCurrentUser().then(response => {
          const data = response.data
          commit('SET_NAME', data.userName)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户权限信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getMyAuthorities().then(response => {
          console.info('res' + response)
          const data = response.data
          var permissions = []
          data.forEach(item=>{
            permissions.push(item.authorityCode);
          })
          
          commit('SET_PERMISSION', permissions)

          resolve(permissions)
        }).catch(error => {
          reject(error)
        })
      })
    },


    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_PERMISSION', [])
          removeToken()
          logout().then(response=>{})
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user

六、router:

import Vue from 'vue'
import Router from 'vue-router'

// in development-env not use lazy-loading, because lazy-loading too many pages will cause webpack hot update too slow. so only in production use lazy-loading;
// detail: https://panjiachen.github.io/vue-element-admin-site/#/lazy-loading

Vue.use(Router)

/* Layout */
import Layout from '../views/layout/Layout'

export const constantRouterMap = [
  { path: '/404', component: () => import('@/views/404'), hidden: true },
  { path: '/login', component: () => import('@/views/login/index'), hidden: true },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    name: '首页',
    icon: '首页',
    hidden: true,
    children: [{
      path: '/dashboard',
      component: () => import('@/views/dashboard/index')
    }]
  }
]
/**
* hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
* alwaysShow: true               if set true, will always show the root menu, whatever its child routes length
*                                if not set alwaysShow, only more than one route under the children
*                                it will becomes nested mode, otherwise not show the root menu
* redirect: noredirect           if `redirect:noredirect` will no redirct in the breadcrumb
* name:'router-name'             the name is used by <keep-alive> (must set!!!)
* meta : {
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar,
  }
**/
export const asyncRouterMap = [
  // { path: '/login', component: () => import('@/views/login/index'), hidden: true },
  {
    path: '/roleManage',
    redirct: '/roleManage/index',
    name: 'roleManage',
    component: Layout,
    meta: { title: '角色管理', authority: ['role_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/roleManage/index'),
        meta: { title: '首页', authority: ['role_manage'], keepAlive: false }
      },
      {
        path: 'detail',
        name: 'detail',
        // hidden: true,
        component: () => import('@/views/roleManage/detail'),
        meta: { title: '详情', authority: ['role_manage'], keepAlive: false }
      }
    ]
  },
  {
    path: '/userManage',
    redirct: '/userManage/index',
    name: 'userManage',
    component: Layout,
    meta: { title: '用户管理', authority: ['user_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/userManage/index'),
        meta: { title: '用户管理', authority: ['user_manage'], keepAlive: false }
      }
    ]
  },
  //学校管理
  {
    path: '/schoolManage',
    redirct: '/schoolManage/schoolManage/index',
    name: 'schoolManage',
    component: Layout,
    meta: { title: '学校管理', authority: ['role_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/schoolManage/schoolManage/index'),
        meta: { title: '学校管理', authority: ['role_manage'], keepAlive: false }
      },
      {
        path: 'detail',
        name: 'detail',
        hidden:'true',
        component: () => import('@/views/schoolManage/schoolManage/detail'),
        meta: { title: '学校详情', authority: ['role_manage'], keepAlive: false }
      }
    ]
  },
  //测试
  {
    path: '/parent',
    redirct: '/test/parent',
    name: 'test',
    component: Layout,
    meta: { title: 'parent', authority: ['role_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'parent',
        name: 'parent',
        component: () => import('@/views/test/parent'),
        meta: { title: 'parent', authority: ['role_manage'], keepAlive: false }
      }
      // ,
      //  {
      //   path: 'child',
      //   name: 'child',
      //   hidden:'true',
      //   component: () => import('@/views/test/child'),
      //   meta: { title: 'child', authority: ['role_manage'], keepAlive: false }
      // } 
    ]
  },
   //map
  {
    path: '/map',
    redirct: '/map/index',
    name: 'map',
    component: Layout,
    meta: { title: 'parent', authority: ['role_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'map',
        name: 'map',
        component: () => import('@/views/map/index'),
        meta: { title: 'map', authority: ['role_manage'], keepAlive: false }
      }
     
    ]
  },

 
  //nav
  {
    path: '/navmenu/index',
    redirct: '/navmenu/index',
    name: 'navmenu',
    component: Layout,
    meta: { title: 'navmenu', authority: ['nav_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'navmenu',
        name: 'navmenu',
        component: () => import('@/views/navmenu/index'),
        meta: { title: 'navmenu', authority: ['nav_manage'], keepAlive: false }
      },
      {
        path: '/navmenu/menu1',
        name: 'menu1',
        hidden:true,
        component: () => import('@/views/navmenu/menu1'),
        meta: { title: 'menu1', authority: ['nav_manage'], keepAlive: false }
      }
     
    ]
  },
 



  //color
  {
    path: '/color',
    redirct: '/color/index',
    name: 'color',
    component: Layout,
    meta: { title: 'color', authority: ['user_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/color/index'),
        meta: { title: 'color', authority: ['user_manage'], keepAlive: false }
      }
    ]
  },

  //actiontable动态表格
  {
    path: '/actiontable',
    redirct: '/actiontable/index',
    name: 'actiontable',
    component: Layout,
    meta: { title: 'actiontable', authority: ['user_manage'] },
    noDropdown: true,
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/actiontable/index'),
        meta: { title: 'actiontable', authority: ['user_manage'], keepAlive: false }
      }
    ]
  },


]

export default new Router({
  // mode: 'history', // 后端支持可开
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

七、view:

1、login/index.vue:


<template>
<div class="main">
  <el-card class="loginform">
    <el-form >
      <el-row>
        <el-form-item label="用户名">
          <el-col span="6">
            <el-input v-model="user.userName"></el-input>
          </el-col>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="密码" prop="pass">
			 <label slot="label">密&nbsp;&nbsp;码:</label>
          <el-col span="6">
            <el-input v-model="user.password" type="password" auto-complete="off"></el-input>
          </el-col>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="验证码" prop="pass">
          <el-col span="4">
            <el-input v-model="user.code" type="code" auto-complete="off"></el-input>
          </el-col>
          <el-col span="2">
            <el-input v-model="code" readonly="readonly" ></el-input>
          </el-col>
        </el-form-item>
      </el-row>

      <el-row >
        <el-col span="6" offset="2">
          <el-form-item size="large">
            <el-button type="primary" @click="login()">登录</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</div>
</template>


<script>
import { login, getCode } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getDAes } from '@/utils/crypto';
export default {
  data() {
    return {
      code: "",
      user: {
        userName: "",
        password: "",
        code: ""
      }
    };
  },

  created() {
    this.getCode();
  },

  methods: {
    getCode() {
      getCode().then(res => {
        this.code = res.data;
      });
    },

    login() {
      this.user.password = getDAes(this.user.password),
      this.$store.dispatch("Login", this.user).then(() => {
        this.$router.push({ path: "/" });
      });
    }
  }
};
</script>


<style>
.main{
	height: 100%;
	width: 100%;
	margin: 0 0;
	background-color: burlywood;
}
.loginform {
	margin-left: 20%;
	margin-right: 20%;
	width: 60%;
   
}
</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值