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

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 … Read more

How to write controller tests when you override devise registration controller?

The problem is that Devise is unable to map routes from the test back to the original controller. That means that while your app actually works fine if you open it in the browser, your controller tests will still fail. The solution is to add the devise mapping to the request before each test like … Read more

Where to override current_user helper method of devise gem

According to the module Devise::Controllers::Helpers, current_user (together with all other devise helpers) is added to ApplicationController, which means that you can override it in this way: # in application_controller.rb def devise_current_user @devise_current_user ||= warden.authenticate(scope: :user) end def current_user if params[:user_id].blank? devise_current_user else User.find(params[:user_id]) end end

Rails 5 ActionController::InvalidAuthenticityToken error

As indicated in Devise documentation notes for Rails 5 For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in “Can’t verify CSRF token authenticity.” To resolve this, either change the order in which you call them, or use … Read more

What’s the most secure possible Devise configuration?

Peppers: yes you are correct. There is not much additional security achieved with a pepper if you are using salt. Stretches: 12 is reasonable, however bcrypt only ensures a constant time. You should consider using the newer scrypt as it allows you to specify both a constant time and the amount of memory to use. … Read more

Setting roles through rolify in FactoryBot definition

I would rather use FactoryBot’s after(:create) callback to create roles (also see this issue for Rolify). Furthermore the method has_role? is used to check if a user has a specific role, to set a specific role you should use the add_role method. FactoryBot.define do factory :user do name ‘Test User’ email ‘[email protected]’ password ‘please’ password_confirmation … Read more

tech