Can I "Unload" a Rails Metal Class after one time use? - ruby-on-rails

I've got a Rails metal class that basically does a one time check to make sure there is an admin user in the system, if not, it redirects user to create one. Right now I'm using the rack session to prevent double checking but that seems to have the following problems:
Still does one time check for each session
Slows things down by checking the session in the first place.
I wonder if its possible to direct Rails to "remove" or "unload" the class from the chain. Can this be done safely? Any other suggestions?

A simplest solution (although not quite as clean) would be to store the fact that an admin user exists in the class.
class EnsureAdminUser
def self.call(env)
if #admin_defined or Admin.any?
#admin_defined = true
[404, {"Content-Type" => "text/html"}, "Not Found"]
else
…
end
end
end
This saves you the DB hit on each request.
To actually delete the metal you will need to do something a bit more radical (and evil):
ObjectSpace.each_object(Rails::Rack::Metal){|metal_handler|
metal_handler.instance_eval{ #metals.delete(EnsureAdminUser) }
}

Related

Rails: Model.find() or Model.find_by_id() to avoid RecordNotFound

I just realized I had a very hard to find bug on my website. I frequently use Model.find to retrieve data from my database.
A year ago I merged three websites causing a lot of redirections that needed to be handled. To do I created a "catch all"-functionality in my application controller as this:
around_filter :catch_not_found
def catch_not_found
yield
rescue ActiveRecord::RecordNotFound
require 'functions/redirections'
handle_redirection(request.path)
end
in addition I have this at the bottom of my routes.rb:
match '*not_found_path', :to => 'redirections#not_found_catcher', via: :get, as: :redirect_catcher, :constraints => lambda{|req| req.path !~ /\.(png|gif|jpg|txt|js|css)$/ }
Redirection-controller has:
def not_found_catcher
handle_redirection(request.path)
end
I am not sure these things are relevant in this question but I guess it is better to tell.
My actual problem
I frequently use Model.find to retrieve data from my database. Let's say I have a Product-model with a controller like this:
def show
#product = Product.find(params[:id])
#product.country = Country.find(...some id that does not exist...)
end
# View
<%= #product.country.name %>
This is something I use in some 700+ places in my application. What I realized today was that even though the Product model will be found. Calling the Country.find() and NOT find something causes a RecordNotFound, which in turn causes a 404 error.
I have made my app around the expectation that #product.country = nil if it couldn't find that Country in the .find-search. I know now that is not the case - it will create a RecordNotFound. Basically, if I load the Product#show I will get a 404-page where I would expect to get a 500-error (since #product.country = nil and nil.name should not work).
My question
My big question now. Am I doing things wrong in my app, should I always use Model.find_by_id for queries like my Country.find(...some id...)? What is the best practise here?
Or, does the problem lie within my catch all in the Application Controller?
To answer your questions:
should I always use Model.find_by_id
If you want to find by an id, use Country.find(...some id...). If you want to find be something else, use eg. Country.find_by(name: 'Australia'). The find_by_name syntax is no longer favoured in Rails 4.
But that's an aside, and is not your problem.
Or, does the problem lie within my catch all in the Application Controller?
Yeah, that sounds like a recipe for pain to me. I'm not sure what specifically you're doing or what the nature of your redirections is, but based on the vague sense I get of what you're trying to do, here's how I'd approach it:
Your Rails app shouldn't be responsible for redirecting routes from your previous websites / applications. That should be the responsibility of your webserver (eg nginx or apache or whatever).
Essentially you want to make a big fat list of all the URLs you want to redirect FROM, and where you want to redirect them TO, and then format them in the way your webserver expects, and configure your webserver to do the redirects for you. Search for eg "301 redirect nginx" or "301 redirect apache" to find out info on how to set that up.
If you've got a lot of URLs to redirect, you'll likely want to generate the list with code (most of the logic should already be there in your handle_redirection(request.path) method).
Once you've run that code and generated the list, you can throw that code away, your webserver will be handling the redirects form the old sites, and your rails app can happily go on with no knowledge of the previous sites / URLs, and no dangerous catch-all logic in your application controller.
That is a very interesting way to handle exceptions...
In Rails you use rescue_from to handle exceptions on the controller layer:
class ApplicationController < ActionController::Base
rescue_from SomeError, with: :oh_noes
private def oh_noes
render text: 'Oh no.'
end
end
However Rails already handles some exceptions by serving static html pages (among them ActiveRecord::RecordNotFound). Which you can override with dynamic handlers.
However as #joshua.paling already pointed out you should be handling the redirects on the server level instead of in your application.

Override redirect_to in rails

I use an engine in my rails app that logins the user and redirects to a service param (it's a CAS engine). However, from the host app I want to redirect the user (after he/she has logged in) in a different location sometimes depending on the params. At the moment I can't get it work because rails permits only 1 call of redirect_to/render. The engine inherits from my rails app ApplicationController.
How can I override/redefine redirect_to to call it multiple times?
The problem might be solved in other ways but I really don't want them. I have tried some of them but none can compete with the simplicity of just letting the last defined redirect_to take action.
I'm only interested in solutions that involve redefining redirect_to so that I can invoke it multiple times.
Of course you can "override" it. You can redefine any method in any object at any point in Ruby. However, this is a terrible idea. You should fix your problem, which is that you're calling redirect_to twice, instead of hacking apart Rails in order to allow your problem to continue.
If you're still set on "fixing" this the wrong way, find the source code (this was trivially easy to do), copy it into an initializer/library file of your own, and make the modifications.
module ActionController::Redirecting
def redirect_to(options = {}, response_status = {})
raise ActionControllerError.new("Cannot redirect to nil!") unless options
raise AbstractController::DoubleRenderError if response_body
self.status = _extract_redirect_to_status(options, response_status)
self.location = _compute_redirect_to_location(options)
self.response_body = "<html><body>You are being redirected.</body></html>"
end
end
If you really want to do this, despite being forewarned that it is the wrong solution to your problem and that you're fundamentally altering behavior of Rails that other things may depend on, comment out the line that raises a DoubleRenderError.
It seems it was much easier than I thought. All you need to do is to explicitly modify the response object.
Thus you could declare the following function in ApplicationController:
def re_redirect_to(location, status = 303)
response.location = location
response.status = status
end
That's it basically. Elegant and simple.
As I said in the first post:
I use an engine in my rails app that logins the user and redirects to a service param (it's a CAS engine). However, from the host app I want to redirect the user (after he/she has logged in) in a different location sometimes depending on the params. At the moment I can't get it work because rails permits only 1 call of redirect_to/render. The engine inherits from my rails app ApplicationController.
So basically I had no other option than override the engine's redirect_to in an after_action in ApplicationController. I believe it's much better and more maintainable solution than modifying the engine's source code.
I would like to note here that it's absolutely good to follow the conventions. Definitely calling redirect_to more than once should be avoided in 99% cases. But it's good to know that there is a way to deal with that other 1%. Conventions are just conventions.
This worked for me, in the application controller, override redirect, do your thing, then call super:
class ApplicationControler < ... #depends on your rails version
def redirect_to(options = {}, response_status = {})
# do your custom thing here
super # and call the default rails redirect
Hope this helps,
Kevin

customizing Devise's authenticate and current_user methods to work with soft delete / acts as paranoid

I am using Devise as authentication for a rails 3.2 app. My user model is called User, and I've been trying to implement a soft delete. I am trying to do this by using acts_as_paranoid, which automatically does the work for you. Things work as expected (others can no longer see the "deleted" user), except that I want the deactivated user to still be able to log in and see a "deactivated" screen, and give them the chance to reactivate their account.
The problem is that Devise (Warden?) is no longer able to find the deleted user. Acts_as_paranoid lets you access the soft deleted records if you use the scope "with_deleted". So I am able to get part of the way there with:
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
where(conditions).with_deleted.first
end
I put this into my user model, and so now when I input the log in information, I'll get the flash message that I have successfully logged in, and it'll touch the "updated_at" column in the user model and increment the sign_in_count, etc. However, it doesn't really authenticate in the sense that the authenticated method returns false and the current_user helper method returns nil. So what is my best strategy to get these working? Can I override the current_user method somehow so that it queries the User model with the with_deleted scope? Do I have to do something with warden, such as added conditions like I did with the find_first_by_auth_conditions method? I cannot figure out how to do this. Any help is appreciated!
also, after I do get it working, I would like to automatically send all soft deleted users to a "deactivated" page where their only options are to permanently delete or reactivate. Is there some way to do this with routing via the "authenticated :user do {} end", or do i have to put a before_filter in the application_controller and check for the users at every request?
I can answer your last question, about routing to the "deactivated page". You can use a lambda to isolate different types of users, like this:
authenticated :user, lambda {|u| u.deactivated? } do
root :to => 'application#deactivated'
end
authenticated :user, lambda {|u| u.active? } do
root :to => 'application#active'
end
Thanks to a tip from the Devise group, it turns out I needed to override the serialize_from_session method, which is inside the authenticatable module and looks like this:
def serialize_from_session(key, salt)
record = to_adapter.get(key)
record if record && record.authenticatable_salt == salt
end
I'd been trying with no success to override modules using initializers (I was trying to override existing strategies, and also to try writing a new one for warden); but I kept getting weird name errors. I still haven't figured that out. However, with the tip, I went ahead and overrode the method inside my User model. Since I don't foresee using some other resource, I didn't mind just editing it like this. The code was just:
def self.serialize_from_session(key, salt)
record = with_deleted.find(key).first
record if record && record.authenticatable_salt == salt
end
This skips the to_adapter.get method altogether (which, to anyone interested, is in orm_adapter, not devise; this took me awhile to find as I was thinking I needed to override this). This probably isn't the cleanest way to do this, but it works well enough for me. And even if I do have a different resource, this should only override the User resource, so I think everything would work fine otherwise.
If problems crop up, I'll add them here. If not, hopefully this helps someone in some way. Certainly took me long enough to get to the bottom of!

My cookie token is strong enough in order to use that for user authentication purposes?

I am running Ruby on Rails 3 and I would know if the code that I am using in order to set the cookie value for user authentication purposes is strong enough.
In my model I have:
require 'digest'
class User < ActiveRecord::Base
...
def make_cookie_id_salt(string)
secure_hash("#{self.id}--#{string}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
In my controller I have:
cookies.signed[:current_user_id] = { :value => [#user.id, #user.make_cookie_id_salt(#user.id)], :expires => 15.days.from_now }
Is it strong enough? If no, how I can improve that (make an example!)?
Everything that gets put into cookies is stored as plain text.
If you set a cookie, and then check the cookies in your browser you will notice (in your case the cookie name would be current_user_id) that it is represented by a string of characters like: G8gcm9sbCB5b3VyIG93biBhdXRoIHRvIGt... (Not quite plain text, right? It is actually Base64 encoded, but you can easily read it - require('base64'); Base64.decode64(string)).
Rails stores a special _yourapp_session cookie that is used to check the cookies validity. If for example someone/something was trying to modify it, it would get rejected.
Now in your case it doesn't really matter if you try to hash something in the cookie or not.
It is just used for authentication (to look up a user in the database by his id) and you are not storing any unique secret data (Which you should not place in a cookie anyway, but it would be the only reason to hash something)
Of course someone could steal the cookie of a user (if he used a public computer and hasn't cleared his cache, etc.) and log in, but there's no way to prevent that (No matter what kind of hashing was used to obfsucate it)
In conclusion you should be fine with what you have.
Rather than try to create your own, I suggest using the Authlogic gem. In a few minutes of configuration you get a complete authentication solution, including cookies and much more. If you really want to roll your own, install the Authlogic gem and take a look at how they do it.
Devise is another option. It's extremely configurable, pretty DRY, with exhausting wiki.
For now-days I prefer it over Authlogic.

Read only mode for Ruby on Rails application

I have an interactive Ruby on Rails application which I would like to put into a "read only mode" during certain times. This will allow users to read the data they need but block them from actions that write to the database.
One way to do this would be to have a true/false variable located in the database that was checked before any write was made.
My question. Is there a more elegant solution for this problem out there?
If you really want to prevent any database write, the easiest way I can imagine would be to override the readonly? method of a model to always return true, either in selected models or maybe even for all ActiveRecord models. If a model is set to readonly (normally done by calling #readonly! on it), any try to save the record will raise an ActiveRecord::ReadOnlyRecord error.
module ActiveRecord
class Base
def readonly?
true
end
end
end
(actually untested code, but you get the idea…)
Zargony's solution seems to be the best one, but I would like to add to it a bit.
So, about his code:
This works nicely. A good solution is to add this in an initializer and run this code only if an env var is set, so that you can choose whether to run the app in read-only mode on launching the app.
if ENV['READ_ONLY'] == 'true'
module ActiveRecord
class Base
def readonly?
true
end
end
end
end
And then run the server from command prompt like READ_ONLY=true bin/rails s. Also, adding
rescue_from ActiveRecord::ReadOnlyRecord, with: ->() {
flash[:alert] = "The site is running in read-only mode. We are going to return to full operation soon. Thank you for your patience!"
redirect_to root_path
}
to the ApplicationController (that all of your controllers should inherit from) is a nice way to show the users what is going on.
Another good one which I liked a little better is Declarative Authorization
which is covered by Railscasts as well: Railscasts - Declarative Authorization
Permissions plugin? Something simple like cancan where you define what a user can do, when. It will allow you to display links, or not, and restrict access to controller actions. The railscast will explain better than I can.
http://github.com/ryanb/cancan
http://railscasts.com/episodes/192-authorization-with-cancan
The answer by Zargony will work well but raise an exception if your application is trying to write anything. If you want your application to fail silently on writes so that it doesn't show error pages on each operation (e.g. if you update a timestamp on login in your code, you will get an exception), you can use the approach below:
unless Rails.env.test?
class ActiveRecord::Base
before_save do
raise ActiveRecord::Rollback, "Read-only"
end
before_destroy do
raise ActiveRecord::Rollback, "Read-only"
end
end
end

Resources