Question

I'm new to ruby and Rails. I'm Using Devise and CanCan along with Rails_Admin in my app. I'm trying to do -> If a user is already logged in, and it's an admin, redirect to rails_admin_path if it's not an admin but just a user then redirect to 'upload_path', if it's not logged in then redirect to sign_in path, however probably due to my lack of knoledge, I'm creating an infinite redirect loop. Even if I try to access sign_in without the "require_login" filter.

Here's what I've done so far: application_controller.rb

class ApplicationController < ActionController::Base
  before_filter :require_login
  protect_from_forgery

 #IDEA 1
 #def require_login
 #   if current_user.role? == 'Administrator'
 #      redirect_to rails_admin_path
 #   elsif current_user.role? == (('C1' or 'D1') or ('M1' or 'M2'))
 #      redirect_to upload_path
 #   end
 # end  

#I saw this somewhere and It doesn't work either
 def require_login
   redirect_to new_user_session_path, alert: "You must be logged in to perform this action" if current_user.nil?
 end
    rescue_from CanCan::AccessDenied do |e|
   redirect_to new_user_session_path, alert: e.message
   end

end

routes.rb

Siteconfigurationlistgenerator::Application.routes.draw do

  mount RailsAdmin::Engine => '/admin', :as => 'rails_admin'

 devise_for :users
  # The priority is based upon order of creation:
  # first created -> highest priority.

  match 'upload' => 'upload_file#new'
.
.
.

ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
   #Define abilities for the passed in user here.
   user ||= User.new #guest user (not logged in)
   #a signed-in user can do everything
    if user.role == 'Administrator'
       #an admin can do everything
         can :manage, :all
         can :access, :rails_admin   # grant access to rails_admin
         can :dashboard              # grant access to the dashboard
    elsif user.role == (('C1' or 'M1') or ('D1' or 'M1'))
       # can :manage, [ProductList, Inventory]
       # can :read, SiteConfigurationList
   #  end
   end

  end

When I run rake routes, I get the routes for Devise and the Rails_admin routes, plus the "upload" route. I've really tried to fix this stupid error but honestly I ran out of ideas. I'd appreciate any help you're able to provide me. Thank you in advance.

Was it helpful?

Solution

The problem is that you have a before_filter that requires a user to sign in, in your ApplicationController. Basically you are asking your users to sign in before accessing the sign in page.

You can solve this by using devise's built-in method :authenticate_user :

before_filter :authenticate_user!

Or you can specify that your before_filter doesn't run on an action from the DeviseController.

before_filter :require_login, :unless => :devise_controller?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top