我已经将rails 4应用程序更新为Rails 5,但我无法在rails 5上设置经过身份验证和未经验证的路由。
在rails 4中:
unauthenticated do
root to: "home#index", as: :unauthenticated_root
end
authenticated :user do
root :to => "home#dashboard"
end但是如何为rails 5应用程序设置
发布于 2019-02-07 16:58:32
对于使用路由约束,这是一个很好的应用程序。请考虑以下几点:
# routes.rb
scope module: 'authenticated', constraints: AuthConstraint.new { |user| user.present? } do
# Management dashboard
root 'dashboards#index'
end
root 'home#index'约束是在app/constraints/auth_constraint.rb文件中定义的,可以根据需要进行配置。例如。
# app/constraints/auth_constraint.rb
class AuthConstraint
def initialize(&block)
@block = block || ->(_) { true }
end
def matches?(req)
user = current_user(req)
user.present? && @block.call(user)
end
def current_user(req)
User.find_by_id(session[:user_id])
end
end这是一种基于任何期望变量(角色、auth等)定义路由访问的灵活方法。
下面是Rails文档中约束的链接:https://guides.rubyonrails.org/routing.html#specifying-constraints
发布于 2018-02-20 05:20:21
我认为您找到了解决方案,如果user_signed_in然后重定向到home#dashboard think "home#index",对吗?然后
首先,看看这个解决方案,它设计的如何:为已登录的用户定义不同的根路由说,如果它不起作用,然后转到下面。
routes.rb
root to: "home#index", as: :unauthenticated_root
get 'dashboard', to: "home#dashboard" #=> dashboard_path在索引操作中使用如下所示
def index
redirect_to dashboard_path if user_signed_in?
end使用控制器的顶部
before_action :authenticate_user!, except: [:index]它将被设置为dashboard和除index以外的其他操作的需要身份验证,您也可以这样使用
before_action :authenticate_user!, only: [:dashboard]它将被设置为只对dashboard操作需要身份验证。
user_signed_in?和authenticate_user!是回调方法--如果您使用devise,那么它默认存在,如果您不使用devise,那么我相信您有您自己的回调方法--只需替换它。
在注释后完全格式化
class HomeController < ApplicationController
before_action :authenticate_user!, except: [:index]
def index
redirect_to dashboard_path if user_signed_in?
end
def dashboard
end
def other_action
end
.....
end后耙路线
unauthenticated_root GET / home#index
dashboard GET /dashboard(.:format) home#dashboard如果您有ajax登录,那么遵循下面的所以问题
您应该重写devise方法,并通过适当的视图呈现来管理那里的情况,否则,正如您在默认的session创建方法中所看到的那样,如果没有执行会话创建,它将只是重定向而不呈现create.js。
您可以在控制器文件夹中覆盖devise控制器,名为registrations_controller.rb,如下所示
class RegistrationsController < Devise::RegistrationsController
# POST /resource
def create
super
end
end而且路线看上去就像
devise_for :users, :controllers => {:registrations => 'registrations'}希望它能帮上忙
发布于 2021-10-30 11:05:20
示例以保护拆分仪表板(用于A/B测试的gem ):
# config/routes.rb
require "split/dashboard"
class AuthConstraint
def initialize(&block)
@block = block
end
def matches?(request)
@block.call(current_user(request))
end
def current_user(request)
return if request.session[:user_id].blank?
User.find_by(id: request.session[:user_id])
end
end
Rails.application.routes.draw do
scope constraints: AuthConstraint.new { |user| user&.dorian? } do
mount Split::Dashboard, at: "split"
end
endhttps://stackoverflow.com/questions/48877617
复制相似问题