'How to dynamically inject permission checking logic for RAILS_API method

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);
    }


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe