如何自定义设备以在会话中存储用户角色信息?

时间:2017-07-15 02:05:27

标签: ruby-on-rails devise ruby-on-rails-5 pundit

目前,我们正在为用户和角色使用两个单独的表。

我正在使用权威进行授权并设计身份验证

我正在许多地方current_user.roles来获取用户的角色。主要是在专家政策文件中。

我希望在用户登录时将用户角色存储在会话中。这样我每次都不会查询db来获取角色。

任何快速解决方案都将受到高度赞赏?

1 个答案:

答案 0 :(得分:3)

由于Pundit没有选项,要传递session或其他参数({1}}除外并检查current_user),您可以改为使用entity

Rails.cache

要使Devise缓存当前角色,您需要覆盖Devise的session_controller

# app/models/user.rb
class User < ActiveRecord::Base
  # ...
  def cached_roles
    Rails.cache.fetch "user.#{self.id}.roles" do
      roles.pluck(:name)
    end
  end

  def clear_cached_roles
    Rails.cache.delete "user.#{self.id}.roles"
  end
end


# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
  # ...

  def admin?
    user.cached_roles.include? 'admin'
  end

  def reader?
    user.cached_roles.include? 'reader'
  end
end

我创建了此demo rails application,您可以使用它:在rails_cache_solution分支或拉取请求中查看我的解决方案变体# app/controllers/users/sessions_controller.rb class Users::SessionsController < Devise::SessionsController def create super current_user.cached_roles end def destroy current_user.clear_cached_roles super end end

另请参阅这些文件以获取更多详细信息:

  • Rails.cache
  • app/controllers/users/sessions_controller.rb
  • spec/controllers/posts_controller_spec.rb
  • app/policies/post_policy.rb
  • app/models/user.rb