pmerino
pmerino

Reputation: 6120

Weird thing when checking sessions in Rails on POST request

I'm having a weird error in Rails, I'm making an app where users can log in and upload files. Everything works, but when I want to upload any file, the code in my application controller for checking an active session fails because it can't access the session array:

def current_user
    if session[:session].nil? # <- Fails here
        redirect_to "/login"  
    else
        if session[:hash] == Digest::SHA512.hexdigest(session[:password]+" - "+session[:username]+" - "+session[:uuid]) #< and here (removing the other if) with NoMethodError
            return 0
        else
            redirect_to "/login"

        end

    end
end

This works on other things, but apparently breaks on POST requests. This is my HAML view to upload files:

%b Upload

%form{:action=>"/u",:method=>"post",:enctype=>"multipart/form-data"}
    %br
    %input{:type=>"file",:name=>"file"}
    %input{:type=>"submit",:value=>"Upload"}

What I'm doing wrong? Also in POST requests I get in the app log: WARNING: Can't verify CSRF token authenticity

Upvotes: 4

Views: 1705

Answers (3)

okliv
okliv

Reputation: 3959

just in case someone decide to use html helper inside the form:

  <%= hidden_field_tag('authenticity_token', form_authenticity_token.to_s)%>

Upvotes: 0

cicloon
cicloon

Reputation: 1099

It seems like you are missing the Authenticity Token that is generated by Rails to avoid Cross-Site Forgery. Check the HTML code generate to be sure the token is generated, if it's not, thats the problem, because Rails 3 default behaviour when the token is missing or doesn't match is to reset the session.

EDIT: Hmm the problem there is that you haven't used the Rails helper. You are using just plain HAML there.

Upvotes: 0

pmerino
pmerino

Reputation: 6120

Apparently I had to add this:

%input{:type=>"hidden", :name=>"authenticity_token", :value=>form_authenticity_token.to_s}

to my HAML form, now everything works good and no more WARNING: Can't verify CSRF token authenticity :)

Upvotes: 7

Related Questions