在 rails 应用程序中适当使用权限

Appropriate use of Authority in rails app

我正在学习 Michael Hartl RoR 教程,但同时实施了 Rollify 和 Authority。我以前从未使用过权限,我想知道以下 before_action 是否适合权限使用

# app/controllers/users_controller.rb 
class UsersController < ApplicationController
  before_action :logged_in_user, only: [:edit, :update]
  .
  .
  .
  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    # Before filters

    # Confirms a logged-in user.
    def logged_in_user
      unless logged_in?
        flash[:danger] = "Please log in."
        redirect_to login_url
      end
    end
end

是否可以 "good programming practice" 将 def logged_in_user 放入 ApplicationAuthorizer class 以备将来使用?

Would it be "good programming practice" to put logged_in_user inside ApplicationAuthorizer

没有

AuthenticationAuthorization之间有一个difference

  • 身份验证 -- 用户已登录?
  • 授权 -- 用户可以执行吗?

差异很细微但很重要 - 您会希望身份验证发生在之前 授权,或者至少是独立发生。

一个很好的类比是 身份验证 是当您可以访问秘密聚会(密码)时; 授权 是table 你可以坐的地方。

如果您使用了其中一种预滚动身份验证系统(Devise or Sorcery), you'd have your authentication handled, providing you with such helpers as user_signed_in?


要回答您的问题,考虑到您已经推出了自己的身份验证,您当前的模式就足够了。

如果您使用 Devise,您需要使用以下内容:

#config/routes.rb
authenticate :user do
  resource :profile, controller: :users, only: [:show, :update] #-> url.com/profile
end

#app/controllers/users_controller.rb
class UsersController < ApplicationController
  def show
    @user = current_user
  end

  def update
    @user = current_user.update update_params
  end
end

--

您要做的是评估 @user.idcurrent_user.id:

#app/models/user.rb
class User < ActiveRecord::Base
  include Authority::UserAbilities
  before_action :logged_in_user, only: [:edit, :update]

  def edit
     @user = User.find params[:id]
     redirect_to root_path, notice: "Can't edit this user" unless current_user.can_edit?(@user)
  end

  def update
    @user = User.find params[:id]
    if current_user.can_update?(@user)
       @user.update ...
    else
      # redirect
    end
  end

  private

  def logged_in_user
    redirect_to login_url, error: "Please log in." unless logged_in?
  end
end

# app/authorizers/user_authorizer.rb
class UserAuthorizer < ApplicationAuthorizer

  def self.editable_by?(user)
    user.id = self.id
  end

  def self.updatable_by?(user)
    user.id = self.id
  end
end