Following The Rails getting Started Guide and getting a ActionController::InvalidAuthenticityToken - ruby-on-rails

I'm following the rails getting started guide here:
http://guides.rubyonrails.org/getting_started.html
I'm on the step 'Creating posts', where I setup my new view to submit a post to my controller.
When I click the submit button in the view I get the error ActionController::InvalidAuthenticityToken
I was able to get past the error by commenting out this line in the ApplicationController
protect_from_forgery with: :exception
However I'm not sure if I should be doing that. Is that fine or should I dig deeper into the problem? What does that line do?
Content of:
/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Budget</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>

No, you shouldn't be commenting that line in your ApplicationController. It is meant for the security of your application at production level.
From the docs: Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
protect_from_forgery is a feature in Rails that protects against Cross-site Request Forgery (CSRF) attacks. This feature makes all generated forms have a hidden id field. This id field must match the stored id or the form submission is not accepted. This prevents malicious forms on other sites or forms inserted with XSS from submitting to the Rails application. Shamelessly copied from here.
And, in last but not the least. Here is the link explaining why Cross-Site Request Forgery (CSRF) should be taken seriously, and why it is important.

Related

Logging out returns Can't verify CSRF token authenticity

I am able to login and logout most of the time, but sometimes during logging out I am returned with this error as stated below and I am not logged out.
Can't verify CSRF token authenticity.
User excluded error: #<ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken>
It doesn't happen always that I am not able to logout but when I am not able to logout above is the error which I get. I read about it this is what I have done so far. I am using vuejs on my front end and rails on the backend. I am using rails version 5.1.
application_controller.rb
protect_from_forgery with: :exception
application.html.erb
<%= csrf_meta_tags %>
this is the axios request I am making to logout the user
index.vue
logout() {
this.$axios.delete('/users/sign_out').then(function(response) {
console.log("Logged out")
});
}
Please help me resolve this issue
You may need to add the csrf_meta_tags to the request
In your case, the csrf_meta_tags in application.html.erb is not re-rendered.

Getting Dojo to Work with Ruby on Rails 4

I'm porting my symfony app to Ruby on Rails 4.2.0. My setup works fine in symfony. There is this old post on how to use dojo with RoR, but it uses deprecated code.
In my application.html.erb I have
<script>dojoConfig = {async: true}</script>
<%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js'%>
I replaced the symfony wrappers with Rails ones. I also changed the dojo version. I was using 1.9.1. Rails generates this html:
<script>
dojoConfig = {async: true}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js">
The last line is followed by a bunch of compressed javascript and the close script tag in Firebug.
I didn't make any changes in my home/index.html.erb where I'm testing this code. In app/assets/javaascipts/home.js, I have:
//require(["dojo/dom", "dojo/ready", "dijit/Tooltip"], function(dom, ready, Tooltip)
define(["dojo/dom", "dojo/ready", "dijit/Tooltip"], function(dom, ready, Tooltip)
{
ready(function()
{
var head = "<div class='footnote-text'>";
var tail = "</div>";
var fnt1 = head + dom.byId("fnb1").innerHTML + tail;
var fnt2 = head + dom.byId("fnb2").innerHTML + tail;
var fnt4 = head + dom.byId("fnb4").innerHTML + tail;
new Tooltip({ connectId: ["footnote1"],position:["after","above","below"],label: fnt1 });
new Tooltip({ connectId: ["footnote2"],position:["after","above","below"],label: fnt2 });
new Tooltip({ connectId: ["footnote4"],position:["after","above","below"],label: fnt4 });
new Tooltip({ connectId: ["footnote5"],position:["after","above","below"],label: fnt4 });
});
});
//require(["dojo/dom", "dojo/ready", "dijit/Dialog"], function(dom, ready, Dialog){
define(["dojo/dom", "dojo/ready", "dijit/Dialog"], function(dom, ready, Dialog){
ready(function(){
var fnt3 = dom.byId("fnb3").innerHTML;
myDialog = new Dialog({
title: "Contact Me",
content: fnt3,
style: "width: 300px"
});
});
});
The commented out require lines are what I use in my symfony app. As you can see, I replaced them with define as described on the dojo site. When I run it, I get the following error on the Firebug console:
ReferenceError: define is not defined
...define(["dojo/dom", "dojo/ready", "dijit/Tooltip"], function(dom, ready, Tooltip
If I used require instead of define, I get require is not defined.
Update
I tried installing dojo into the app and made some progress. I copied the download from dojo to vendor/assets/javascript/dojo. The dojo directory contains the subdirectories dojo, dojox, and digit
I then added
//= require dojo/dojo/dojo.js
to app/assets/javascript/application.js. I also changed the define back to require in the home.js file. When I reloaded the page, I got an error complaining that it couldn't find Tooltip. I then added:
//= require dojo/dijit/Tooltip.js
On reload it complained about a bunch of other missing js files. This is the same problem I had using symfony, which is why I went to the google image. How can I get to rails to search for the files in the vendor directories? This is one of the errors:
"NetworkError: 404 Not Found - http://amcolan.loc/dijit/_base/manager.js"
Update 2
Since require_tree worked for app assets, I thought it might work to vendor as well. I added
//= require_tree ../../../vendor/assets/javascripts/dojo
to my application.js file. When I reloaded the page, it took about a minute. My guess is that it's loading everything in the dojo directory tree, which is not surprising. The page load completed without any errors. When I hovered over a tooltip item (the purpose of the code is to show tooltips), Firebug cranked out about two thousand errors and quit. All the errors appear to be "ReferenceError: define is not defined"
Update 3
I went back to using the googleapi. My application.html.erb header looks like this
<head>
<meta charset="UTF-8">
<title><%= content_for?(:title) ? yield(:title) : "American Colonial Ancestors" %></title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<script>dojoConfig = {async: true}</script>
<%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js'%>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
I reversed the order of the javascript includes. The page reloaded without errors. The tooltip doesn't work, but it doesn't generate any errors when I hover over an item. I put a bad statement in the home.js code and it came up on the console so I know the code is being parsed. I may just have a bug in my page setup.
There may be more than one way to get Dojo toolkit to work with Ruby on Rails. This is the easiest if not the most efficient way. This works in Rails 4.2.0. I would imagine it would work in other versions as well.
In views/layouts/application.html.erb add the following prior to the inclusion of the site scripts:
<script>dojoConfig = {async: true}</script>
<%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js'%>
Change the version to the latest or to which ever one you want to use. Here I'm using version 1.10.3. The dojo site says there are other CDN's (Content Delivery Network) for the source code. I'm using google as it was in their example. Here are the pertinent parts of my head section:
<head>
<meta charset="UTF-8">
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dijit/themes/claro/claro.css" %>
<script>dojoConfig = {async: true}</script>
<%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js'%>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= content_for :page_script %>
<%= csrf_meta_tags %>
</head>
If you are going to use any of the toolkit's dialog boxes, tooltips, etc, you will need to include a stytlesheet by adding something like this:
<%= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dijit/themes/claro/claro.css" %>
Change the version and the theme to your own requirements. Here I'm using the claro theme. You can see it in my head section above. I don't think placement is critical. You also need to declare your theme class in the body statement. Here's mine:
<body class="claro">
An older post on the subject had different javascript formatting. I don't think anything special is needed. Here's an example of a working script:
require(["dojo/dom", "dojo/ready", "dijit/Tooltip"], function(dom, ready, Tooltip)
{
ready(function()
{
var head = "<div class='footnote-text'>";
var tail = "</div>";
var fnt1 = head + dom.byId("fnb1").innerHTML + tail;
var fnt2 = head + dom.byId("fnb2").innerHTML + tail;
new Tooltip({connectId: ["footnote1"], position:["after","above","below"], label: fnt1 });
new Tooltip({connectId: ["footnote2"], position:["after","above","below"], label: fnt2 });
});
});
As mentioned in my question, I tried placing the Dojo Toolkit source in vendor/assets/javascript. Starting with with version 1.7, dojo started using Asynchronous Module Definition (AMD). It may be the case that the AMD loader is incompatible with the Rails pre-compile feature. I don't know enough about it to say for sure.

Cached app issue - deployed with capistrano

I have deployed my app for first time. Cap deploy was successful. However I was getting an error on a specific code segment. So I decided to delete this code segment and get the website up and running first before fixing this error.
I run cap deploy again but I am still getting the same error on the code segment that I removed from the source file (I see the error by tailing production.log). It was not suppose to be there. I searched around on the net and found that the problem is that there is a cached version of the app. I found out that a solution would be to delete the cache-copy folder in /shared folder.
I restarted my services (nginx, unicorn) and open the site again and I still get the same error on the code segment I removed.
I checked my new current folder, cached-copy folder and last release folder and all don't have the code segment that produces the error.
It's really odd to me. Any clue whats going on?
Thanks!
Code segment that produces the error:
ActionView::Template::Error (undefined method `stripe' for #<Rails::Application::Configuration:0x00000002a85578>):
20: <meta name="viewport" content="width=device-width">
21: <%= javascript_include_tag 'application' %>
22: <%= javascript_include_tag "https://js.stripe.com/v1/", type: 'text/javascript' %>
23: <%= javascript_tag "Stripe.publishableKey = '#{Rails.configuration.stripe[:publishable_key]}';", type: 'text/javascript' %>
24: <%= csrf_meta_tag %>
25: <%= stylesheet_link_tag "application", :media => "all" %>
26: <script type="text/javascript" src="//use.typekit.net/xoh2pss.js"></script>
app/views/layouts/application.html.erb:23:in `_app_views_layouts_application_html_erb__486989174473553269_34754060'
The line 23 was removed but its still shown as generating the error.
# config/initializers/stripe.rb
Stripe::API_KEY = 'asd8df9sadf766'
# application.html.erb
<%= javascript_tag do -%>
Stripe.publishableKey = <%= Stripe::API_KEY %>;
<% end -%>
Are your assets precompiled and the old all.js (or similar) being redeployed without this change present? If the routine invoked by the javascript portion isn't present that could produce an error -- that might be the stripe method you're trying to invoke. If they were manually precompiled and you made the change but didn't re-compile it, the redeploy would simply put the old one back out there.

Content for doesn't work in production mode

On one of application's page there is:
<% content_for :head do %>
<%= tag :meta, property: "fb:app_id", content: ENV["FACEBOOK_APP_ID"] %>
<% content_for :title, #check.title %>
<% end %>
And it worked in development, while I was running server at my localhost.
After that I deployed application on heroku. And that simply doesn't work.
What means doesn't work. I load page in development at localhost:
<title>Tenta</title>
<meta content="*****************" property="fb:app_id">
When I load this page deployed at heroku host, these tags are simply absent.
Why?
Also, If you don't know this particular issue solution, I would appreciate if you adivce me, how can I look what is going on - heroku logs and watching last 150 logs in inconvinient windows console doesn't give me a lot of helpful information.

Why is the wrong action processing my .ajax request.

This is an issue I have been working around for some time now thinking I would eventually stumble on an explaination. I have not and it's now becoming a little more problematic for me.
I used rails-generate-scaffold to create a simple (users and posts) application. This was done after installing jquery and jquery-ui. I added actions "login" and "auth" to the users controller. Login.html.erb contains some javascript that sends .ajax request to the users#auth action passing the login information (email and password) as parameters.
The the template auth.js.erb exists. The "auth" action responds to format.js. The request looks normal, but rails processes the request with the "show" action rather than the "auth" action.
In other words, a request to userscontrollers#auth (via .ajax) is being processed by userscontroller#show (as JS).
The problem goes away if I remove the "resources :users" route that scaffold added (the correct action is then called). But without this route other useful scaffold stuff becomes unuseable (like users#new).
From Gemfile: gem 'jquery-rails', '>=0.2.6'
Installed jQuery with: rails generate jquery:install --ui
From ../layouts/application.html.erb
<head>
<title>Tab1</title>
<%= stylesheet_link_tag :all %>
<%= stylesheet_link_tag 'jquery-ui-1.8.16.custom.css' %>
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag 'jquery.min.js' %>
<%= javascript_include_tag 'jquery.min.js', 'jquery-ui.min.js' %>
<%= csrf_meta_tag %>
</head>
Here is ./log/development.log to shows the request and the response.
Started GET "/users/auth/?email=steve&password=[FILTERED]&_=1326063255777" for 24.11.242.181 at 2012-01-08 17:53:45 -0500
Processing by UsersController#show as JS
Parameters: {"email"=>"steve", "password"=>"[FILTERED]", "_"=>"1326063255777", "id"=>"auth"}
^[[1m^[[36mUser Load (0.2ms)^[[0m ^[[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 0 LIMIT 1^[[0m
Completed 404 Not Found in 6ms
ActiveRecord::RecordNotFound (Couldn't find User with ID=auth):
app/controllers/users_controller.rb:43:in `show'
Suggests that the request --> GET "/users/auth/?email ... is being processed by UsersController#show as JS
Thanks

Resources