vendredi 13 novembre 2015

Devise's current_user nil in ApplicationController but not in a different controller (using Simple Token Authentication)

I have a Rails 3.2.22 app running in production for +1 year which uses Devise to authenticate users.

I'm trying to implement token authentication, so I can send transactional e-mails with URL params that can log in the user automatically, using a Gem named Simple Token Authentication http://ift.tt/1dX8JWW

After following all the instructions, I replaced before_filter :authenticate_user! in my controllers with acts_as_token_authentication_handler_for User.

The gem has integration with and a default fallback to Devise, so devise doesn't need to be called in the controllers anymore; if the token is missing from the params (or wrong), Devise will take over.

In my tests, if I add this line to ApplicationController, everything works fine and I can log in users using the authentication_token= secret the gem generates.

But I don't need auth for ApplicationController, I need it for other controllers (like DashboardController), url being /dashboard

If I put acts_as_token_authentication_handler_for User in that controller (replacing Devise's call), I get the most bizarre of situations.

Using binding.pry, I can confirm that current_user is correctly set during the loading of the template.

But there comes a point in the template where it uses @last_emails, which is defined inside a method in ApplicationController.

Using binding.pry, I can confirm current_user is nil there.

This is the code:

class DashboardController < ApplicationController
  layout 'material'

  acts_as_token_authentication_handler_for User

And in ApplicationController:

class ApplicationController < ActionController::Base
 layout 'omega'

 before_filter :populate_last_contacts_for_menu 

private
  def populate_last_contacts_for_menu
    if current_user
      @last_contacts = Contact.where("user_id" => current_user.id).where('blocked != ? or blocked is null', true).last(10).reverse
    end
  end

Funny thing is: using binding.pry, like I said, I can check that current_user is defined in the template (which means sign_in was a success). It even is defined in the better errors console. But, if I go to homepage, I see that user is not logged in ...

I've looked all over the web for this: read all the issues inside the Gem's github and all posts in SO about current_user being nil, but no light at all.

My devise_for :users is not inside any scope in routes.rb and, as I said, I have many calls to current_user all over the app and this is the first time I have issues with Devise.

Aucun commentaire:

Enregistrer un commentaire