如何在rails 7中为特定用户设置路线

问题描述 投票:0回答:4

我遇到了 Rails_admin 的问题。 Rails_admin 已成功添加到应用程序并且工作正常。

问题是当我尝试将路由设置到特定角色用户时。

我的应用程序由多个角色组成,如用户、客户端、管理员等。 我在这里想要的是只有具有“admin”角色的用户可以通过使用“link_to 'rails_admin_path'”或http://127.0.0.1:3000/admin访问rails_admin部分。

我已经有一个管理部分,所以我不想为rails_admin添加任何其他登录部分,只需要我的管理中的rails_admin的功能。

我有一个名为“check_admin”的方法,它将检查当前用户的角色是否为管理员

current_user.check_admin

#routes.rb

Rails.application.routes.draw do
   mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
end

我的要求是,给定的路由只能由管理员用户访问

提示:check_admin 或 current_user.roles.admin.present?

ruby-on-rails routes admin rails-admin ruby-on-rails-7
4个回答
2
投票

解决方案

路线.rb

authenticate :user, -> (u) { u.roles.admin.present? } do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
end

在检查特定角色的情况下更改路由,在我的例子中是“admin”。

因此其他非管理员用户无论如何都无法访问rails_admin


2
投票

我很确定这就是 constraints 的用途

https://guides.rubyonrails.org/routing.html#advanced-constraints.

https://www.mikewilson.dev/posts/rails-vanity-urls-with-route-constraints/

我们可以在用户路由上使用路由约束,这样如果 :id 由于路由与我们系统中的用户名不匹配,我们返回 false Rails 将继续下一条路线。

解释一下路线约束轨道

基本上是这样的

lib/role.rb

class Roles   
    def initialize(&block)
       @block = block || lambda { |user| true }  
    end
        
     def matches?(request)
      user = current_user(request)
      user.present? && @block.call(user)  
     end
        
    def current_user(request)
#my users cookies are stored in A model called ActiveSessions
#what ever your Session cookies is goes here
      active = ActiveSession.find_by(id: 
       request.session[:current_active_session_id])
#then find user from that cookie
     User.find_by_id(active.user.id)   
    end 
end

然后在路线中:

constraints Roles.new { |user| user.roles == "ROLE" } do
#what ever routes you want access to based on constraint
end

编辑:

现在还要补充一点,我必须处理这个问题,如果您打算访问

**cookie**
,而不是
session
,进行查询,您将必须这样做:

request.cookie_jar.encrypted[:whatever_name_here]

注意

ROLE
是您想要根据列属性授予访问权限的角色;即管理员、会员、客户等


1
投票

根据要求,扩展我之前的评论......

class AdminController < ApplicationController
  before_action :reject_non_admins

  def index
  end

  def show
  end

# etc... all the admin CRUD actions

private
  def reject_non_admins
    unless current_user.check_admin
      render "unauthorized.html" and return
    end
  end

end

因此,非管理员用户不会被阻止访问敏感的管理页面,但他们只会看到一个页面,告诉他们不允许他们查看内容。

# app/views/admin/unauthorized.html

<p>Sorry, only admins can see this page</p>

0
投票

路由配置不正确,无法阻止非管理员用户访问该页面。路由配置没有 current_user 的概念。

应该在控制器中完成。

def show
  unless current_user.roles.admin.present?
    render "unauthorized"
  end
  # default "show.html will render
end
   
© www.soinside.com 2019 - 2024. All rights reserved.