动态控制页面操作按钮显示

package com.java1234.common.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java1234.entity.R;
import com.java1234.entity.SysMenu;
import com.java1234.entity.SysRole;
import com.java1234.entity.SysUser;
import com.java1234.service.SysMenuService;
import com.java1234.service.SysRoleService;
import com.java1234.service.SysUserService;
import com.java1234.util.JwtUtils;
import com.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录成功处理
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username = authentication.getName();
        String token = JwtUtils.genJwtToken(username);

        SysUser currentUser = sysUserService.getByUsername(username);

        //根据用户id获取所有的角色信息
        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "SELECT role_id FROM sys_user_role WHERE user_id=" + currentUser.getId()));

        StringBuffer permsStr = new StringBuffer();

        //遍历所有的角色 获取所有菜单权限 而且不重复
        Set<SysMenu> menuSet = new HashSet<>();
        for(SysRole sysRole : roleList){
            List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "SELECT menu_id FROM sys_role_menu WHERE role_id =" + sysRole.getId()));
            for(SysMenu sysMenu : sysMenuList){
                menuSet.add(sysMenu);
                permsStr.append(sysMenu.getPerms()+",");
            }
        }

        String perms[] = StringUtils.tokenizeToStringArray(permsStr.toString(), ",");

        currentUser.setRoles(roleList.stream().map(SysRole::getName).collect(Collectors.joining(",")));

        List<SysMenu> sysMenuList = new ArrayList<>(menuSet);

        //排序
        sysMenuList.sort(Comparator.comparing(SysMenu::getOrderNum));

        //转菜单树
        List<SysMenu> menuList = sysMenuService.buildTreeMenu(sysMenuList);

        outputStream.write(JSONUtil.toJsonStr(R.ok("登录成功").put("authorization",token).put("perms",perms).put("currentUser",currentUser).put("menuList",menuList)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}

<template>
  <div class="app-container">

    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input placeholder="请输入用户名..." v-model="queryForm.query" clearable ></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initRoleList">搜索</el-button>
      <el-button type="success" :icon="DocumentAdd" @click="handleDialogValue()" v-if="hasAuth('system:role:add')">新增</el-button>


      <el-popconfirm title="您确定批量删除这些记录吗?" @confirm="handleDelete(null)">
        <template #reference>
          <el-button type="danger" :disabled="delBtnStatus" :icon="Delete" v-if="hasAuth('system:role:delete')">批量删除</el-button>
        </template>
      </el-popconfirm>
    </el-row>

    <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="rolename" label="角色名"  width="100" align="center"/>
      <el-table-column prop="code" label="权限字符" width="200" align="center"/>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center"/>
      <el-table-column prop="remark" label="备注"  />
      <el-table-column prop="action" label="操作" width="400" fixed="right" align="center">
        <template v-slot="scope" >
          <el-button  type="primary" :icon="Tools" @click="handleMenuDialogValue(scope.row.id)" v-if="hasAuth('system:role:menu')">分配权限</el-button>

          <el-button v-if="scope.row.code!='admin' && hasAuth('system:role:edit')" type="primary" :icon="Edit" @click="handleDialogValue(scope.row.id)" />

            <el-popconfirm  v-if="scope.row.code!='admin'" title="您确定要删除这条记录吗?" @confirm="handleDelete(scope.row.id)">
              <template #reference>
                 <el-button  type="danger" :icon="Delete" v-if="hasAuth('system:role:delete')"/>
              </template>
            </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>


    <el-pagination
        v-model:currentPage="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <Dialog v-model:dialogVisible="dialogVisible" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle" @initRoleList="initRoleList"/>
    <MenuDialog v-model="menuDialogVisible" :menuDialogVisible="menuDialogVisible"  :id="id" @initRoleList="initRoleList"></MenuDialog>
</template>

<script setup>
import {ref} from 'vue';
import requestUtil,{getServerUrl} from "@/util/request";
import { Search ,Delete,DocumentAdd ,Edit, Tools, RefreshRight} from '@element-plus/icons-vue'
import Dialog from './components/dialog'
import { ElMessage, ElMessageBox } from 'element-plus'
import MenuDialog from './components/menuDialog'

const tableData=ref({})

const total=ref(0)

const queryForm=ref({
  query:'',
  pageNum:1,
  pageSize:10
})

const dialogVisible=ref(false)

const dialogTitle=ref("")

const id=ref(-1)

const delBtnStatus=ref(true)

const multipleSelection=ref([])

const sysRoleList=ref([])

const menuDialogVisible=ref(false)

const handleSelectionChange=(selection)=>{
  console.log("勾选了")
  console.log(selection)
  multipleSelection.value=selection;
  delBtnStatus.value=selection.length==0;
}

const handleMenuDialogValue=(roleId)=>{
  console.log("roleId="+roleId)
  id.value=roleId;
  menuDialogVisible.value=true
}

const initRoleList=async()=>{
  const res=await requestUtil.post("sys/role/list",queryForm.value);
  tableData.value=res.data.roleList;
  total.value=res.data.total;
}

initRoleList();

const handleSizeChange=(pageSize)=>{
  queryForm.value.pageNum=1;
  queryForm.value.pageSize=pageSize;
  initRoleList();
}

const handleCurrentChange=(pageNum)=>{
  queryForm.value.pageNum=pageNum;
  initRoleList();
}

const handleDialogValue=(roleId)=>{
  if(roleId){
    id.value=roleId;
    dialogTitle.value="用户修改"
  }else{
    id.value=-1;
    dialogTitle.value="用户添加"
  }
  dialogVisible.value=true
}

const handleDelete=async (id)=>{
  var ids = []
  if(id){
    ids.push(id)
  }else{
    multipleSelection.value.forEach(row=>{
      ids.push(row.id)
    })
  }
  const res=await requestUtil.post("sys/role/delete",ids)
  if(res.data.code==200){
    ElMessage({
      type: 'success',
      message: '执行成功!'
    })
    initRoleList();
  }else{
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
  }
}

const handleResetPassword=async (id)=>{
  const res=await requestUtil.get("sys/role/resetPassword/"+id)
  if(res.data.code==200){
    ElMessage({
      type: 'success',
      message: '执行成功!'
    })
    initRoleList();
  }else{
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
  }
}

const statusChangeHandle=async (row)=>{
  let res=await requestUtil.get("sys/role/updateStatus/"+row.id+"/status/"+row.status);
  if(res.data.code==200){
    ElMessage({
      type: 'success',
      message: '执行成功!'
    })
  }else{
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
    initRoleList();
  }
}

</script>

<style lang="scss" scoped>

.header{
  padding-bottom: 16px;
  box-sizing: border-box;
}

.el-pagination{
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

::v-deep th.el-table__cell{
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 13px;

}

.el-tag--small {
  margin-left: 5px;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Shiro-Vue 可以帮助我们在Vue.js项目中实现按钮的权限控制。以下是控制按钮操作的步骤: 1. 首先,我们需要在后端的权限管理系统中配置按钮的权限信息。这可以包括按钮的唯一标识符、所属菜单或页面、权限标识符等。 2. 在前端的Vue.js项目中,我们需要使用Shiro-Vue提供的指令来控制按钮显示或隐藏。比如,在按钮的HTML代码中添加v-permission指令: ``` <el-button v-permission="btn_add">新增按钮</el-button> ``` 这里的btn_add就是在后端配置的按钮权限标识符。 3. 在Vue.js组件中,我们需要引入Shiro-Vue提供的mixin,以便在组件中使用权限控制指令。可以在组件的script标签中添加如下代码: ``` import { ShiroPlugin } from 'shiro-vue'; export default { mixins: [ShiroPlugin], // ... } ``` 4. 接下来,我们可以在组件的mounted钩子函数中调用Shiro-Vue的init方法,从后端获取当前用户的权限信息。获取到权限信息后,Shiro-Vue会自动根据权限配置来控制按钮显示或隐藏。 ``` mounted() { this.init(); // 初始化权限信息 } ``` 5. 最后,我们可以根据具体的业务需求,在按钮的点击事件处理函数中做权限判断。比如,在新增按钮的点击事件中,可以使用checkPermission方法来判断当前用户是否有权限执行该操作。 ``` methods: { handleAdd() { if (this.checkPermission('btn_add')) { // 执行新增操作 } else { // 没有权限,给出提示或采取其他操作 } } } ``` 通过以上步骤,我们可以实现在Vue.js项目中对按钮的权限控制。当用户没有权限时,按钮将被隐藏或禁用,从而保证了系统的安全性和稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值