[英]How to structure authenticated routes when using Devise?
在我的问题中,当用户未登录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
问题是我不想对: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
Rails.application.routes.draw do
devise_for :users
resources :subjects do
resources :students
end
root "home#index"
end
当您希望对经过身份验证和未经身份验证的用户对同一路由有不同的响应时,使用经过authenticated
和unauthenticated
authenticated
unauthenticated
路由帮助程序将非常有用,但是您不应该以此方式构造应用程序。
如果仅在路由中使用经过authenticated
,则未经authenticated
验证的用户将收到404 Not Found响应,而不是提示登录。这没有帮助。
另外, resources :students, only: [:get]
根本不生成任何路由。 only
选择是限制动作(显示,索引,编辑,更新...),而不是HTTP方法。 使用rake routes
查看您应用中的路线。
这是构造经过身份验证和未经身份验证的路由的简单方法。
在app / controllers / application_controller.rb中,添加"before_action :authenticate_user!"
。
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
end
Rails.application.routes.draw do
devise_for :users
root "home#index"
devise_for :users, controllers: {
:sessions => "users/sessions",
:registrations => "users/registrations" }
authenticated :user do
resources :students
end
unauthenticated :user do
#Some route
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.