Unable to log out and redirect to new page from yielded layout - ruby-on-rails

In a 3.2.16 Rails app using Devise, we allow users to stay logged in for a number of days. This means, of course, that if they click a link to our page (say in their bookmarks) they come right back into the app (assuming their session is still active).
For our main screen, we have a yielding layout
...
<body>
...
<%= yield %>
...
</body>
The layout surrounding the yield includes a display of the username among other things.
And now I have a new controller:
class AccountSelectionsController < ApplicationController
def new
if user_signed_in?
sign_out current_user
current_user = nil
end
...
render :layout => "external"
end
...
end
When the new action is invoked, I want the user signed out completely, the session cleared, and the user taken to a completely different layout. The use-case assumes the user is reaching this controller from a link in, say, an email or a page outside my app (IOW, not from a spot inside my app).
I first thought I merely had do a sign_out current_user(as above), but that didn't do anything obvious: the user seems to stay signed in.
The above was just my starting point. I've tried just sign_out (without a resource, implying all scopes), reset session, and redirect_to destroy_user_session_path (which is what our standard logout button does, a button positioned on the surrounding layout).
What I got though was my new external view (or the normal new session sign in screen, depending on the permutation of what I tried) trying to render inside the old layout (as if it was part of the yield).
I could try the Devise after_sign_out_path_for to help with redirect, but then I'd only want it if it was tied to this particular controller and action and I'm not quite sure how to safely accomplish that. And now I'm not convinced it wouldn't just keep me wrapped in the surrounding layout anyway.
So, (1) is there a reason the main layout stays intact even upon a full redirect_to (even using :status => 301) that I should be able to defeat (for instance, is the yield interfering?), or (2) am I on the right track with Devise after_sign_out_path_for and what do I need to do to limit that behavior to just respond to this one controller action?
Thank you!
Richard
UPDATE: the served page (via view source) shows the intended screen body is wrapped within the layout of the origin screen
UPDATE 2: I've also tried returning a head :reset_content from a before filter along with various other things in a before_filter. Still the old layout keeps rendering before it attempts to render the new page. This is although I'm using different Chrome tabs in the test (i.e., the session stays in memory); I've tried it in Firefox too. Same result. The output of rails s shows the redirects and gives no indication that it's attempting to go through another controller first, something is triggering the layout. Is there away to force a layout in a redirect?

Try this instead,
sign_out current_user, :bypass => true

So this is my penance for posting the question.
I just figured out that a before_filter was intercepting the call to the controller and redirecting it to the wrong layout before a sign-in was ever checked for. Normally this is desired for this particular application, but I didn't realize that the filter actually was catching the redirect ahead of my controller (the logs suggested it happened at a later point). Once I set that filter to be skipped in my controller, all was well.
Moral of the story, I need to better consider the side effects of before_filters in the ApplicationController.
Thank you to RSB and Jasdeep Singh and everyone else who spent time considering an answer for this.

Related

Rails redirect or render to show errors

When a user makes an invalid create request for a resource, I want to send them back to the form and show them an error. As far as I can tell, calling render "new" is the standard way to do it.
This seems like a bad idea to me, because the create request has taken the user to /resources, whereas my "new" form is otherwise at /resources/new. If I use render "new", the URL in the address bar will not reflect what the user sees. If they make a GET request there, they'll end up on a different page.
I thought I could solve this problem by using redirect_to new_[resource]_path, but if I do that I lose access to the form data and errors. Surely this is not an uncommon problem. Is there a better way to deal with it?
I have the same problem with edit/update and other form/submit action pairs.
TL;DR:
class ResourcesController < ApplicationController
def new
#resource = Resource.new(resource_params)
if resource_params.present?
#resource.validate
end
end
def create
#resource = Resource.new(resource_params)
if #resource.save
redirect_to #resource, notice: 'Resource has been created'
else
redirect_to new_resource_url(resource: resource_params)
end
end
private
def resource_params
params.fetch(:resource, {}).permit(...)
end
end
I asked this myself as well in my early beginner days, on why Rails scaffold generator generates the def create action to render :new if saving failed, instead of redirecting to the correct URL just something like above, which would confuse the users because their URL would have changed from /resources/new into /resources even though they would still see the exact same Resource form on the page, and therefore they would not be able to reload the page or copy this /resources URL (for example, if they want to share this URL to someone else), because should they share this /resources URL, the others would see a list of Resources on the page instead of what the original user would have expected to see from the copied URL: which is the form page.
After the user submits the form, the URL they see on the address bar should have changed into POST http://localhost:3000/resources instead of just simply http://localhost:3000/resources. The browser hides the HTTP Method being used, that's why this leads to their possible confusion that /resources seems to have been both sometimes: a form page, sometimes a list of resources page. However, speaking of UX, every time anyone enters something or pastes something in the URL address bar of the browser, it is always automatically implied to be doing a GET request. Therefore, it makes sense for the browser-developers to just simply hide the HTTP method (i.e. GET in particular) from the users as to not confuse them.
From my answer above, I only used something like this once before (because there was a certain action that demanded me not to change the URL from the referrer form page). However, I normally render :new instead of redirect_to new_resources_url, simply because:
a redirect_to new_resource_url(resource_params) would take twice as much time and data-transmitted than simply rendering :new. Why? Because you redirect (opening up a new request) with the exact same parameters anyway. Just imagine if your form page is soooo big, and has so many input fields.
and also that there's a limit to how long a URL can be, of which won't guarantee to work if you have a very big form with very long text fields. See this SO
Updated:
As you have said though, why not just POST /resources/new instead of POST /resources when the form is submitted, right? This will solve the redirect_to new_resource_url(resource_params) problem I've shown above, because the URL after form-submit would have been the same and you can just simply render :new, then. And I actually agree on that, and I've used something like this also before long time ago. The main reason I don't use this is that it is not inline with REST standards. That is: POST /resources/new means that you're creating a Resource object "inside" the resources/new location, which then means by REST, after submitting the form, I would and should be able to access this newly created resource by doing something like GET /resources/new/the_newly_created_record, except that... you can't.
But you can still use POST /resources/new, although I would not recommend it on a normal Rails application like yours, and however strictly discourage it on an API-based Rails application.
You may be overthinking this. How about get /resources the index page vs post /resources the create action? Same url in the address bar!
It's not a problem. Neither a technical problem or an aesthetic problem.
render "new" means: render this template, not: go to this route. And although templates often have the name of the corresponding action, it's not a requirement.

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

How to trigger modal when event occurs in Rails

I'm sure that there is an answer to this out there, but I'm not entirely certain how to properly phrase this question, so my apologies if this is repetitious.
I am working on implementing a badge/achievement system for a site. The backend stuff is there, but I'm working on the front-end now, and I'm basically trying to figure out how to redirect to a sort of "Congratulations!" page when someone gets a new badge.
The congratulations page is going to be a modal, but for simplicities sake, if anyone has an idea of how to trigger an action like this only once when a new Badge is created, that would be a huge help. Right now, when a user performs a given action, say... adding money to their account, a user_badge is created (adds a Badge ID to an array).
Thanks in advance!
You can use before_filter for actions, where you want to check that new badge appears (probably you don't want to check it in auth actions, so you can't use global before_filter). Then you can use redirect_to in this before filter, if user has a new badge.
But I don't recommend to do so, since you'll break the users flow. It's better to show alert/modal on the next requested page. To achieve this you can define a new instance variable in your before_filter (like #show_modal) and include the partial with modal to your footer.
example:
#before filter
def check_for_new_badges
if current_user.has_new_badges?
#show_modal = true
current_user.set_badges_as_seen!
end
end
#included in layout
- if #show_modal
= render 'shared/congrats_modal'

How does Twitter get two different home pages depending on login or not? - Rails 3.1

If you go to Twitter.com when you are not logged in, you will see the marketing page with the login & registration fields.
However, if you go there when you are logged in, you will see your activity stream for your Twitter handle.
I know one way to do this in Rails is to have a home/index for the logged in users, and just use public/index.html for the marketing site. But Twitter is not using public/index.html, so I am wondering how they do it?
Is it just a simple case of having one root route, but then an if statement that displays two different pages depending on whether or not the user is logged in?
Or is there some other more fancy routing trick that I can use to do that?
If it is just an if-statement, that seems a bit hacky...no?
Thanks.
This might give a head start. http://collectiveidea.com/blog/archives/2011/05/31/user-centric-routing-in-rails-3/
By default controller methods that handle specific routes render a view that has a corresponding name (home/index route links to home controller and index action which in turn renders the view index.html.erb inside the app/views/home folder).
However, inside the controller method that handles the root request you can simply render a different view based on the fact that a user is logged in or not.
You would probably have something like this:
class HomeController
def index
...
if user_logged_in?
render "logged_in_user"
# else it will render the index view by default
end
end
end
In this case "logged_in_user" would be a different view (template or html.erb file) from the app/views/home folder.
For more information take a look here: Rails rendering guide
it can some kind of redirect for not logged in users to different controller , checking of user session can be done in before_filter

getting the flash hash to persist through redirects

My basic use case is do some processing, set flash[:notice], and then redirect to a new page. From what I can tell, redirects reset the flash tag (please correct me if I'm wrong). Is there a way to gain persistence? Using sessions isn't an option, and I have hacked around the problem using cookies, but I think there's got to be a better way.
The flash hash persists for exactly one redirect or render. So you should be fine with the default settings.
If you need to keep the flash hash for another request/redirect, you can call flash.keep.
flash.keep # keep the entire flash hash around for an extra request.
flash.keep(:notice) # keep just flash[:notice] for an extra request.
Something to be aware of in at least Rails v3.2.1 is that the flash will persist through a redirect if its not referenced at all through at least 1 redirect and load the same view after. This is a pseudo code of my recent experience:
def some_action
(code that may set a flag to redirect 1 time)
redirect_to action_path if(redirect_flag)
....
end
Running this would result in the flash[:message] being present regardless of the redirect.
def some_action
logger.debug("Flash[:message] #{flash[:message]}")
(code that may set a flag to redirect 1 time)
redirect_to action_path if(redirect_flag)
....
end
During debugging with the logger referencing flash[] it would only show up when the redirect didn't happen. I could see this being problematic if you added a reference to flash before a redirect and lost it down the line for no apparent reason.
See ruby docs here (Instance protected method: Use at the bottom)

Resources