[英]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
是“良好的編程習慣”
沒有。
Authentication
和Authorization
之間有區別 :
差異是微小的,但很重要-您希望認證在授權之前進行 ,或者至少獨立進行。
一個很好的類比是, 身份驗證是指您可以訪問秘密方(密碼)。 授權是您可以坐在哪個桌子上。
如果您使用了一種預卷式身份驗證系統( Devise
或Sorcery
), 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.