如何动态注入权限检查rails_api方法的逻辑

发布于 2025-01-26 05:20:51 字数 3029 浏览 2 评论 0原文

当前的项目采用前端和后端分离架构,前端由VUE实现,后端采用了铁轨。现在,我们需要解决前端和后端身份验证逻辑,并希望后端迫使每个API具有访问权限的前端身份验证。我希望有人可以帮助回答,以下是我的一些实施逻辑: 基类控制器逻辑:

  def collect_metrics
    start_time = (Time.now.to_f.round(3) * 1000).to_i
    # ap self.as_json
    yield
    end_time = (Time.now.to_f.round(3) * 1000).to_i
    duration = end_time - start_time
    # 日志转储
    save_logger(duration: duration, severity: "INFO")

    # 刷新用户操作时间
    update_user_online

    Rails.logger.debug("正在调用 API 接口:#{@api_operation},授权用户为 #{@current_user}")
end

用户协会权限词典:

 u.roles = ["log:list", "error:list", "online:list", "log:edit", "log_error:del", "user:offline", "user:list", "menu:list", "job:list", "role:list", "dept:list", "dict:list", "dept:edit", "dept:del", "dept:add", "dict:edit", "dict:del", "dict:add"]

每个操作绑定一个类变量:

    # 创建部门
  def create
    @api_operation = "创建部门"
    @api_authorize = "dept:add"
    pre_authorize

    data          = dept_params.except(:id, :isTop, :sub_count).as_json
    pid           = data.delete("pid")
    data[:parent] = SysDept.find(pid) if pid.to_i > 0
    dept          = SysDept.new data
    if dept.save
      render json: { content: "成功创建部门" }, status: :ok
    else
      render json: { content: "创建部门异常" }, status: :not_acceptable
    end
  end

    # 更新部门
  def update
    @api_operation = "更新部门"
    @api_authorize = "dept:edit"
    pre_authorize

    data = dept_params.except(:label, :hasChildren, :leaf, :isTop, :sub_count)
    id   = data.delete("id")
    if id.present? && SysDept.find(id).update!(data)
      render json: { message: "更新部门成功" }, status: :ok
    else
      render json: { message: "更新部门异常" }, status: :not_acceptable
    end
  end
    

这是Java的解决方案代码,我不知道如何将以下代码转换为Ruby样式。

    @Log("删除部门")
    @ApiOperation("删除部门")
    @DeleteMapping
    @PreAuthorize("@el.check('dept:del')")
    public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){
        Set<DeptDto> deptDtos = new HashSet<>();
        for (Long id : ids) {
            List<Dept> deptList = deptService.findByPid(id);
            deptDtos.add(deptService.findById(id));
            if(CollectionUtil.isNotEmpty(deptList)){
                deptDtos = deptService.getDeleteDepts(deptList, deptDtos);
            }
        }
        // 验证是否被角色或用户关联
        deptService.verification(deptDtos);
        deptService.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("修改部门")
    @ApiOperation("修改部门")
    @PutMapping
    @PreAuthorize("@el.check('dept:edit')")
    public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){
        deptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

The current project adopts the front-end and back-end separation architecture, the front-end is realized by VUE, and the back-end adopts RAILS. Now we need to solve the front-end and back-end authentication logic, and hope that the back-end will force the front-end authentication for each API to have access rights. I hope someone can help to answer, the following is some of my implementation logic:
Base class controller logic:

  def collect_metrics
    start_time = (Time.now.to_f.round(3) * 1000).to_i
    # ap self.as_json
    yield
    end_time = (Time.now.to_f.round(3) * 1000).to_i
    duration = end_time - start_time
    # 日志转储
    save_logger(duration: duration, severity: "INFO")

    # 刷新用户操作时间
    update_user_online

    Rails.logger.debug("正在调用 API 接口:#{@api_operation},授权用户为 #{@current_user}")
end

User association permission dictionary:

 u.roles = ["log:list", "error:list", "online:list", "log:edit", "log_error:del", "user:offline", "user:list", "menu:list", "job:list", "role:list", "dept:list", "dict:list", "dept:edit", "dept:del", "dept:add", "dict:edit", "dict:del", "dict:add"]

Each ACTION binds a class variable:

    # 创建部门
  def create
    @api_operation = "创建部门"
    @api_authorize = "dept:add"
    pre_authorize

    data          = dept_params.except(:id, :isTop, :sub_count).as_json
    pid           = data.delete("pid")
    data[:parent] = SysDept.find(pid) if pid.to_i > 0
    dept          = SysDept.new data
    if dept.save
      render json: { content: "成功创建部门" }, status: :ok
    else
      render json: { content: "创建部门异常" }, status: :not_acceptable
    end
  end

    # 更新部门
  def update
    @api_operation = "更新部门"
    @api_authorize = "dept:edit"
    pre_authorize

    data = dept_params.except(:label, :hasChildren, :leaf, :isTop, :sub_count)
    id   = data.delete("id")
    if id.present? && SysDept.find(id).update!(data)
      render json: { message: "更新部门成功" }, status: :ok
    else
      render json: { message: "更新部门异常" }, status: :not_acceptable
    end
  end
    

here is java's solution code,I don't know how to convert the following code into RUBY style。

    @Log("删除部门")
    @ApiOperation("删除部门")
    @DeleteMapping
    @PreAuthorize("@el.check('dept:del')")
    public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){
        Set<DeptDto> deptDtos = new HashSet<>();
        for (Long id : ids) {
            List<Dept> deptList = deptService.findByPid(id);
            deptDtos.add(deptService.findById(id));
            if(CollectionUtil.isNotEmpty(deptList)){
                deptDtos = deptService.getDeleteDepts(deptList, deptDtos);
            }
        }
        // 验证是否被角色或用户关联
        deptService.verification(deptDtos);
        deptService.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("修改部门")
    @ApiOperation("修改部门")
    @PutMapping
    @PreAuthorize("@el.check('dept:edit')")
    public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){
        deptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

四叶草在未来唯美盛开 2025-02-02 05:20:53

如果我理解您的问题,则可以在控制器中添加the the thecation_action:check_preauth,然后实现方法check_preauth检查用户执行操作的权限。

If I understand your problem, you can add a before_action :check_preauth in your controller, then implement the method check_preauth checking the user's permission to perform the action.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文