aks*_*aks 3 ruby-on-rails devise warden
在我的问题中,如何在用户未登录 Rails 时拥有 root 视图?max 回答说,authenticated只有当某人通过身份验证时,我们才能使用路由。我有一个问题,我该如何构建这个:
Rails.application.routes.draw do
devise_for :users
authenticated :user do
# when authenticated allow all action on student
resources :subjects do
resources :students
end
end
# when not only allow read on student
resources :subjects do
resources :students, only: [:get]
end
root "home#index"
end
Run Code Online (Sandbox Code Playgroud)
问题是我不想允许任何未经身份验证的操作:subjects来阻止它?
如果你想限制对主题的访问,你应该在控制器层上做——而不是在路由中。使用before_action :authenticate_user!将给出401 Unauthorized响应并重定向到登录。
class ApplicationController
# secure by default
before_action :authenticate_user!, unless: :devise_controller?
end
class SubjectsController < ApplicationController
# whitelist actions that should not require authentication
skip_before_action :authenticate_user!, only: [:show, :index]
# ...
end
Run Code Online (Sandbox Code Playgroud)
Rails.application.routes.draw do
devise_for :users
resources :subjects do
resources :students
end
root "home#index"
end
Run Code Online (Sandbox Code Playgroud)
当您希望对经过身份验证和未经身份验证的用户的同一路由有不同的响应时,使用authenticated和unauthenticated路由助手很有用,但这不是您应该如何构建应用程序。
如果您只是authenticated在您的路线中使用未经身份验证的用户将收到 404 Not Found 响应,而不是被提示登录。这没有帮助。
也resources :students, only: [:get]根本不生成任何路线。该only选项用于限制操作(显示、索引、编辑、更新...)而不是 HTTP 方法。使用rake routes看到您的应用程序的路由。
| 归档时间: |
|
| 查看次数: |
2496 次 |
| 最近记录: |