2020年3月1日 星期日

Rails 限定admin管理者才能取用的兩個方法

如何做出require_is_admin?

方法1.在controller中做

用beforeaction
使用範圍比較侷限。當然也可以放在application controller中增加使用範圍。
controller中
before_action :require_is_admin

privite
  def require_is_admin
    if current_user.email != 'lisa@google.com'
      flash[:alert] = 'You are not admin'
      redirect_to root_path
    end
  end

方法2.在model中做

一開始使用範圍就比較廣了,因為可以取用model的地方很多。
user model>>
  def admin?
    email == 'lisa@google.com'
  end
controller>>
unless current_user.admin?
      flash[:alert] = 'You are not admin'
      redirect_to root_path
end
controller>>
def admin_required
  if !current_user.admin?
    redirect_to "/", alert: "You are not admin."
  end
end

沒有留言:

張貼留言

cloud9上面開發rails

 使用IAM身分登入,以免有資安問題。(用admin帳號登入,創建iam使用者,然後在上面的連結登入) 選擇 ubuntu18.04 減少查詢成本。 已經是超級使用者了,sudo 什麼都不需要輸入密碼了。 $ ruby -v  檢查 ruby使用的版本>>2.6.3,...