Rails Devise - current_user is nil

2020-02-28 04:02发布

问题:

For some reason, current_user returns nil in my model-less controller (Subscriptions). I have found nothing on the Internet to justify this behavior...

class SubscriptionsController < ApplicationController  
  def new
    ...
  end

  def create
    current_user    # returns nil
  end
end

I have a csrf meta tag :

<meta content="xxx" name="csrf-token">

I can provide more code, but I'm not sure what would be useful.

UPDATE

So thanks to the comments/answers, I have pinpointed the problem to one particular action : create.

if I add @user = current_user to the new, I can show the current user's email in my new view. However, in my create controller, current_user returns nil.

I accessed the create action through a form (submit).

Before the form is submitted, I validate the input and then send a request to Stripe to get a token out of the form. If there are no errors (validation and stripe), I then send the form.

Could that be the cause?

UPDATE 2

In my error message, my session dump is empty, while it should contains the current_user info...

回答1:

It turned out the AJAX request I was making didn't carry the CSRF token. For that reason, Rails was killing my session.

I added skip_before_filter :verify_authenticity_token in my SubscriptionsController and it is now working. It might not be the most secure solution, but it works for now, so I continue to develop and come back to this issue later.



回答2:

Note that when you create forms using the form_tag helper, they do not automatically generate the hidden field which holds the token for CSRF authentication. I ran into this same issue with a form I had constructed using the form_tag which I sometimes prefer using.

I fixed the issue by including the following helpers within the form:

<%= hidden_field_tag 'authenticity_token', form_authenticity_token %>

It's basically a manual way of generating the hidden field you need for the CSRF stuff.



回答3:

for current_user to work you need to add before_filter :authenticate_user! to your class, like:

class SubscriptionsController < ApplicationController  
  before_filter :authenticate_user!

  def new
    ...
  end

  def create
    curent_user    # returns nil
  end
end

and the authenticate_user! method will set the current user for you :)



回答4:

I had a similar issue but I was editing the model. So everytime I updated the model suddenly that would happen:

current_model to nil

After analyzing things, it turns out that if you leave the password in the form, when the user tries to edit some attribute, the person is then forced to write a password.
Once the form is delivered and updated, Devise does the rational thing when someone updates a password, which is to destroy the session and ask the user to sign in again.

So that was why current_model was suddenly turning to nil. Hope this helps, have a great day!