Search code examples
ruby-on-railsrubypostrequestcsrf

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


Solution

  • 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 :)