rails auto_complete plugin. how do i pass authenticity token? - ruby-on-rails

I tried the auto_complete text field in rails 2.3.3 and the server says it denied request because of no authenticity token. I can see that the helper doesn't automatically create a parameter for it.
How I can manually do this? And I do not want to disable forgery prevention for this autocomplete.

Honestly, disabling the forgery protection isn't a bad idea if you scope this to just JS.
def index
respond_to |format| do
format.html
format.js do
# your autocomplete code
end
end
end
Make your autocomplete call /things.js instead of /things.
As far as I understand it, forgery protection is not needed for JS responses, and ensuring your autocomplete uses a GET method should also solve your problem. You're displaying a list, you're not modifying state, so use a GET and use the js response.

The forgery prevention is part of the form helper, not the field helper. If you use the full RoR form helper it should work. If it doesn't, please edit your question to include the form code and I'll try to help.

having had a similar problem I found just adding ":method => :get" to the "text_field_with_auto_complete" tag fixed it (as per Brian) - I didn't need to disable forgery protection

Related

Using responders gem with Rails 5

I'm using responders gem to dry up my controllers. Here's my current code:
class OfficehoursController < ApplicationController
def new
#officehour = Officehour.new
end
def create
#officehour = Officehour.create(officehour_params)
respond_with(#officehour, location: officehours_path)
end
def officehour_params
params.require(:officehour).permit(:end, :start, :status)
end
end
The problem that I'm facing right now is:
When I send valid parameters to create, it redirects to officehours/ as expected, however when I get 422 (validation error), it changes the URL from officehours/new to officehours/ (however it stays at the form page... idk why). The same happens for edit/update actions.
So, I want to stay at the .../new or .../edit when I get 422 error, how can I do this?
I don't think the issue comes from the gem. It just follows RESTFUL API, so does Rails.
That means the path for creating office hours is /officehours. Let's talk about your case:
There is nothing to say when we creating successfully. In your case, you redirect users to officehours_path.
When we creating unsuccessfully, we need to re-render the error form to users. But we were rendering the form in create action. As I said above, the URL for creating is /officehours, so you will see the /officehours instead of officehours/new
In order to keep the url /officehours/new:
We can set /officehours/new instead of /officehours for :create action. But you should not do that, are we going to break RESTFUL API?
Creating via AJAX to keep the URL persisted and you have to handle everything, eg: set flash messages on client, using Javascript to redirect in case of success, render the form error in case failure, ... And I don't think the gem help you dry up your application anymore.
Hope it helps!
I don't think so that it's a problem in responders gem, as I've noticed the same in rails applications. It seems like the default behaviour of rails applications.
take a look at this link for the explanation.

Rails Rpec InvalidCrossOriginRequest

I have a test in rspec for a destroy that returns the following:
ActionController::InvalidCrossOriginRequest:
Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.
I can run the destroy just fine thru the UI but when it gets tested I get the above warning. Why is that?
Is your destroy request supposed to be an AJAX request? If so, you can assign the xhr option to true.
get some_path, xhr: true

In rails 4.2, how to display a form for preview but ensure it cannot be submitted

I'd like to have a a form view that can, depending on circumstances, have submit functionality disabled in a bullet-proof way so that even a clever user could not edit the HTML source (via a browser extension) to re-add the submit button.
It seems one way to do that might be to somehow inject an invalid authenticity token that replaces the (valid) rails-generated one, so that even if a user somehow re-adds the submit button (by editing the HTML via a browser extension) it would still be an invalid submission.
My thought is to have some logic in the view:
- if #form_disabled # set by controller
- somehow_invalidate_the_authenticity_token?
How might one 'break' Rails form submission?
The purpose of doing this, instead of rendering the preview in a :show action, is to have the exact same view displaying both the live-form and the dead-form.
If I were you, I would use pundit.
It's pretty simple, and has few lines of code if you need to know how it works.
I'd start to write the code here, but I realize that the example at the readme fit your needs.
At the application controller add this
At the folder app/policies put the class PostPolicy, of course, you must replace "Post" with the name of your controller in singular (even if you have not a model with that name). The update? (and create?) actions should return true/false to indicate if user is allowed or not.
A few lines down on the readme, you will find the PostsController#update action, which call to authorize with the record before the update. I think you want do the same with create (then you need a create? method at the policy class).
Pundit needs current_user controller method, if you don't have it. Just follow the user customization instructions.
Of course, new and edit actions don't call authorize because they are allowed to everybody. Only the POST & the PUT/PATCH actions are forbidden.
Yes, it's more than a surgery of one line of code. But it's simple and the right way of give access to users.
After reading my other answer, I start thinking that you can do the same that Pundit does at the controller:
def update
if <unauthorized user>
flash[:alert] = "You are not authorized to perform this action."
redirect_to(request.referrer || root_path)
else
# all the update stuff
# ...
end
end

Why is sessions reset in my rails application?

I has some features which settings I save in session. But after 1 times reload they reset and session values doesn't exist there.
First load I get session
{"session_id"=>"xxx"}
After save value I get
{"session_id"=>"xxx", "value"=>"100"}
And when I reload my page again I get reset session
{"session_id"=>"xxx"}
Why it can be?
Igor is exactly right. If that happens to be the case in your application, do something like this:
$(document).ajaxSend((event, jqxhr, settings) ->
jqxhr.setRequestHeader("X-CSRF-Token", $('meta[name="csrf-token"]').attr('content'))
jqxhr.setRequestHeader("X-CSRF-Param", $('meta[name="csrf-param"]').attr('content'))
return
)
Now that's CoffeScript, and that assumes you are using JQuery. Regardless, the point is you need to send the CSRF metadata along for the ride with your Ajax requests.
Most likely you're not passing the CSRF token in one of your (probably AJAX) requests. If rails receives invalid CSRF token - it resets the session.
Check out: http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf
Update: Vidya is right. You may also want to add the following code to your ApplicationController - to set the XSRF token for AJAX calls
after_filter :set_csrf_cookie
def set_csrf_cookie
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
Thanks for every one, I find problem but I can't explain it.
Later I remove row from js file app/assets/javascripts/application.js
//= require jquery_ujs
When I put it back, it's stop reset session values.

Rails: json response from secure action

Originally I had quite usual ajax form with json response:
def create
# created logic omitted as most likely irrelevant
render :json => {:success => true} #over simplified JSON for debug purposes
end
So far so good, works as expected. I've added security on the create action via ssl_requirement gem:
class RegistrationsController < Devise::RegistrationsController
ssl_required :create
# rest of the code omitted, 'create' action as above
end
All of a sudden I get the following in my form response (observing in HttpFox):
Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)
The create action runs as expected (enforces HTTPS, creates an object but... fails in the browser. To be specific, fails in Firefox (works on chrome). Any clues and ideas will be greatly appreciated.
Regards,
I'm not certain, but I believe your problem has to do with cross-site AJAX requests.
The fact that you are using a different protocol is making firefox believe you are making a cross-site request. Chrome, I believe, is less strict with this restriction when on local. Try visiting the site itself over https and see if the AJAX request goes through.

Resources