我正在使用 Rails 8 并通过以下方式生成身份验证:
rails generate authentication
我想限制对某些路由的访问,这样它们就不会暴露给未经身份验证的用户。
在 Devise 中,有一个像这样的约束助手:
ruby
authenticated :user do
# Allow all actions on subjects and nested students only for authenticated users
resources :subjects do
resources :students
end
end
Rails 8 中有内置方法可以实现此目的吗?
有没有办法为新的生成器添加它?
没有内置方法。您必须将身份验证逻辑移至中间件中,并在路线中使用
constraints
帮助器:
# config/initializers/auth_middleware.rb
class UnauthorizedError < StandardError
end
class AuthMiddleware
def initialize app
@app = app
end
def call env
request = ActionDispatch::Request.new(env)
Current.session = Session.find_by(id: request.cookie_jar.signed[:session_id])
@app.call(env)
rescue UnauthorizedError
[302, {Location: "/session/new"}, []]
end
end
Rails.application.config.middleware.use AuthMiddleware
由于
Current.session
已经设置,您需要更新 Authentication
关注:
# app/controllers/concerns/authentication.rb
def resume_session
# Current.session = find_session_by_cookie
Current.session
end
# def find_session_by_cookie
# Session.find_by(id: cookies.signed[:session_id])
# end
并在您的路线中使用它:
# config/routes.rb
class AuthenticatedUser
def self.call
Current.session || raise(UnauthorizedError)
end
end
Rails.application.routes.draw do
# 404 for unauthorized users
constraints -> { Current.user } do
# your routes
end
# redirect to login for unauthorized users
constraints -> { Current.user || raise(UnauthorizedError) } do
# your routes
end
# make it a bit more reusable
constraints AuthenticatedUser do
# your routes
end
end