Redirect to log in page if user is not authenticated with Devise

丶灬走出姿态 提交于 2019-11-27 20:29:19

Just simple add this method to application_controller.rb

  protected
  def authenticate_user!
    if user_signed_in?
      super
    else
      redirect_to login_path, :notice => 'if you want to add a notice'
      ## if you want render 404 page
      ## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
    end
  end

And you can call this method on before_filter another controllers you want.

e.g :

class HomesController < ApplicationController
  before_filter :authenticate_user!
  ## if you want spesific action for require authentication
  ## before_filter :authenticate_user!, :only => [:action1, :action2]
end

Don't forget add login_path into routes.rb

devise_scope :user do
  match '/sign-in' => "devise/sessions#new", :as => :login
end

note : I always use this way when play with devise for my apps authentication.. (rails 3.2 and rails 4.0.1)

You can do just like GeekTol wrote, or just put

before_action :authenticate_user!

in your controller.

In this case, devise uses the default authenticate_user! method, that will redirect to the "user_session_path" and use the default flash message.

It's not necessary to rewrite authenticate_user! method, unless you want to customize it.

I thought you could just add: before_action :authenticate_user! to each controller that required the user to be logged in.

I'm a Rails beginner but I found this in my own searches and it works well in my application.

You should refer to Devise's own How To: How To: Redirect to a specific page when the user can not be authenticated.

Another alternative I can think of is creating a routing Constraint wrapping your protected routes. You'd better stick to Devise's way, but here is an example:

#On your routes.rb
constraints(Constraints::LoginRequired) do
  get '/example' 
end

#Somewhere like lib/constraints/login_required.rb
module Constraints
  class LoginRequired
    def self.matches?(request)
      #some devise code that checks if the user is logged in
    end 
  end
end

Add this code in your config/routes.rb devise_for :users and resources :users and you can generate devise in views.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!