简体   繁体   中英

In my rails app using Devise, when an unsigned in user visits root they are redirected to /users/sign_in instead of the root path?

In my rails app using Devise, when an unsigned in user visits root they are redirected to /users/sign_in instead of the root path; root path works fine with signed in users. The same thing happens when I click the navbar logo which is a link with the home_path which is root, I am redirected to /users/sign_in just like when visiting root. Here are my routes:

  get 'home' => 'static_pages#home', as: "home"

  devise_for :users, :controllers => { registrations: 'registrations' }

  root 'static_pages#home'

The link that takes me to /users/sign_in instead of home_path/root_path in navbar template:

<a class="navbar-brand" href="<%= home_path %>">Brand</a>

I am using angular on the front end so this is what the path looks like when a signed in user visits root:

http://localhost:3000/home#/

If if I manually change the url to /home#/ or /home I am still redirected to users/sign_in.

I can't think of any other information to include. Is this just default behavior by Devise that I need to override? Can't seem to find anything on automatic redirecting in the docs. Thanks for the help.

Application controller:

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  protect_from_forgery with: :exception


  def after_sign_in_path_for(user)
    home_path
  end
end

static_pages controller:

class StaticPagesController < ApplicationController
  def home
  end
end

This is because the helper authenticate_user! only allows signed in users to access the web pages. You need to add skip_before_action :authenticate_user! to the statics_controller in order to let the non-loggedin users to access the home page

class StaticPagesController < ApplicationController
  skip_before_action :authenticate_user!

  def home
  end
end

In your ApplicationController, which StaticPagesController subclasses, you set before_action :authenticate_user! , which will be triggered for all actions, which attempts to authenticate a User.

This means, that when a User isn't signed in, the authentication check will fail, and you will be redirected to the User sign in route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM