繁体   English   中英

在Rails应用程序中适当使用Authority

[英]Appropriate use of Authority in rails app

我正在遵循Michael Hartl RoR教程,但是在此过程中实现了Rollify和Authority。 我以前从未使用过Authority,所以我想知道以下before_action是否适合使用Authority

# 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

def logged_in_user放在ApplicationAuthorizer类中以供将来使用是“良好的编程习惯”吗?

logged_in_user放入ApplicationAuthorizer是“良好的编程习惯”

没有。

AuthenticationAuthorization之间有区别

  • 身份验证-用户已登录?
  • 授权-用户可以这样做吗?

差异是微小的,但很重要-您希望认证授权之前进行 ,或者至少独立进行。

一个很好的类比是, 身份验证是指您可以访问秘密方(密码)。 授权是您可以坐在哪个桌子上。

如果您使用了一种预卷式身份验证系统( DeviseSorcery ), user_signed_in?处理身份验证,并为您提供诸如user_signed_in?这样的帮助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

-

您要尝试的是针对current_user.id评估@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM