How to set variables across models for a single request in rails? - ruby-on-rails

The scenario: I need to give models access to API tokens stored in the session.
Background: I have an API-driven rails 3 application utilizing DataMapper(DM) and a DM adapter to interface with the API. Each DM model has a corresponding REST-ish API endpoint much like you get with rails scaffolding. The API requires various headers for requests, including API tokens, keys, ids etc. The headers have nothing to do with the requested data, they exist for authorization and tracking purposes only. A number of these tokens are stored in the session. I want a clean way to make these API headers available to any model during a request.
Possible solutions:
1. Passing session variables from the controller to the models
The obvious answer is passing the tokens in a hash or other object from the controller to the models. A controller action might have the following: #user = User.find(params[:id], api_headers).
The problem is needing to override any model method to accept the additional api_headers object. Not counting methods defined by Rails and DataMapper, there are hundreds of methods already defined in the application models that would need to be rewritten. So I'm ruling out a rewrite, and this also doesn't seem like a good solution since it would require overriding a ridiculous number of DM methods like the User#find example above.
2. Some metaprogramming hack
I could catch any ArgumentError's on DM's base class and check if the last argument is the api_headers object, then set the values as instance variables and invoke the requested method. This thought exercise already has me cringing at dealing with optional arguments etc. If given long enough I could probably create a functional Frankenstein that should get me fired but probably wouldn't.
3. Use a singleton (current preferred solution)
In the application controller set a before_filter to dump the session-stored API headers into a singleton ApiHeaders object. Then any model making an API request can get that singleton with the required API headers.
An additional after_filter* on the application controller would set all attributes to nil on the ApiHeaders singleton at the end of the request to prevent leaking headers between requests.
This is currently my preferred solution but I don't like that the API header values could potentially carry over into other requests if the after_filter doesn't get invoked. I don't know in which scenarios this might happen (in an application error perhaps?) which raises concerns. All I know is the values don't necessarily die with the request.
4. Custom code
Drop support of DataMapper and the custom API adapter and manually make all API calls, passing through all required API headers. Besides the fact I don't have time for this level of rewrite, why use a framework at all if you have to throw a huge chunk out to support a custom auth scheme?
Summary
What's the cleanest way to get these pesky API tokens from the session into the bowels of the application where they can be sent with each API request? I'm hoping for a better solution than those listed above.
* An alias for after_action

I set the current user and the request information on my User model using the request_store gem which is just a tiny shim over thread local storage with a bit of clean-up.
This makes the information available from any of my models via the User class. I have User.current, User.request and User.location available wherever I need it.
Your controller just has to set User.current and User.request once it has authenticated the user.
Example User model:
# models/user.rb
require 'request_store'
class User
def self.current
RequestStore.store[:current_user]
end
def self.current=(user)
RequestStore.store[:current_user] = user
end
def self.request
RequestStore.store[:current_request]
end
def self.request=(request)
# stash the request so things like IP address and GEO-IP based location is available to other models
RequestStore.store[:current_request] = request
end
def self.location
# resolve the location just once per request
RequestStore.store[:current_location] ||= self.request.try(:location)
end
end

Use Thread.current, which is passed in from request to model (note, this breaks if, inside your request, you use sub-threads). You can store the attribute you want to share in a cattr_accessor or in rails cache:
in a cattr_accessor
class YourClass
cattr_accessor :my_var_hash
...
# and in your controller
# set the var
YourClass.my_var_hash = {} if YourClass.my_var_hash.nil?
YourClass.my_var_hash[Thread.current.object_id] = {}
YourClass.my_var_hash[Thread.current.object_id][your_var] = 100
... and in your model
lvalue = YourClass.my_var_hash[Thread.current.object_id][your_var]
Note, if you use this method, you will also want to make one of the hash values a timestamp, and do some housekeeping on getting, by deleting old keys, b/c you'll eventually use up all your system memory if you don't do the housekeeping
with cache:
# in your controller
#var = Rails.cache.fetch("#{Thread.current.object_id}_var_name") do
return 100 # do your work here to create the var value and return it
end
# in your model
lvalue = Rails.cache.fetch(("#{Thread.current.object_id}_var_name")
You can then set the cache expiration to 5 minutes, or you can wildcard clear your cache at the end of your request.

Related

How to make a rails server wide object?

I am using the RedditKit gem and in order to access certain elements, I need to send a request to reddit api to create a "client" object. Below is my current logic:
## application_controller
before_action :redditkit_login
private
def redditkit_login
#client = RedditKit::Client.new ENV["reddit_username"], ENV["reddit_password"]
end
As you can see in my logic here, before EVERY REQUEST, I am subsequently making a new client object and then using that everywhere.
My question is, how do I only make one client object which can be used to serve ALL requests from anywhere?
My motive behind this is speed. For every request to server, I am making a new request to reddit and then responding to the original request. I want to have the client object readily available at all times.
You have a lot of options. A simple one would be to create a config/initializers/reddit_client.rb file and put in there:
RedditClient = RedditKit::Client.new ENV.fetch("reddit_username"), ENV("reddit_password")
(note I switched to ENV.fetch because it will error if the key is not found, which can be helpful).
You could also rename the file as app/models/reddit_client.rb. Although it's not really a model, that folder is also autoloaded so it should work as well.

Creating smart model in Ruby

I want to create an ActiveRecord-like interface for Salesforce, such that I can call
class Account < Salesforce::Model
end
and be able to call methods like Account.find_by_FirstName() using my own method_missing function.
However, connecting to Salesforce can be done in two ways: username and password, and oauth. If a username/password is used, I can have it defined in a salesforce.yml file and load automatically. But with oauth, I can't do that since each user will have this defined. I don't want to initialize a class with Account.new('oauth', oauth_parmas) or Account.new('username','password','sec_token'), but have the model determine which to use based off of rules and by seeing if one or the other is present.
Is there a way to implement this? In other words, is there a way for the model to know if the current user has a current oauth token or if a username/password defined?
Additionally, if I were to use this in a Rails app, the user would be logging in after the app was started, so the oauth token would be defined after the application started, and would be different for each of the multiple users. For example, let's say I call Account.find_by_FirstName('John') in AccountController#Show. I want the Account model to use the oauth token or usename/password without having to be asked. I also don't want to establish connection directly in my show method in the controller. I have two questions:
How would I implement this? Should I use a before_filter in the controller, or is there a way to implement this application-wide?
If I have multiple users connecting to Salesforce, would this cause issues in my application? In other words, would I have to worry about a connection being used by another user since the connection is dynamic?
Your needing is not different from ActiveRecord::Base connection establishment: you establish the connection using ActiveRecord::Base.establish_connection and every model you use after the connection establishment know which connection to use, because you memorized the connection at superclass level.
For Salesforce you can use the same concept:
class Salesforce::Model
def self.oauth_params
#oauth_params
end
def self.establish_connection(oauth_params)
#oauth_params = oauth_params
end
def self.find(id)
# use oauth_params here
end
end
class Account < Salesforce::Model
end
Now you can do something like
Salesforce::Model.establish_connection ['username', 'password']
Account.find 2 # without specifying authentication params
Since you know authentication params after knowing the logged user, you can establish the connection after the user is logged:
def sign_user
# user = ...
oauth_params = get_oauth_params(user)
Salesforce::Model.establish_connection(oauth_params)
end
Concurrency (threads)
If I have multiple users connecting to Salesforce, would this cause issues in my application? In other words, would I have to worry about a connection being used by another user since the connection is dynamic?
Legitimate question. If you run the Rails application in a threaded environment (threaded application server - f.e. Puma, multi-threaded architecture - JRuby, Rubinius...) AND Rails is configured as threadsafe (config.threadsafe!), you could have concurrency problems (the explanation is not trivial - check out this).
If this is your case you can scope the #oauth_params variable accessor to Thread.current:
class Salesforce::Model
#oauth_params = { Thread.current => nil }
def self.oauth_params
#oauth_params[Thread.current]
end
def self.establish_connection(oauth_params)
#oauth_params[Thread.current] = oauth_params
end
Would it be possible that the thread for the current user changes?
It is possible, if some code you execute runs inside a new thread. F.e.:
Salesforce::Model.establish_connection(oauth_params)
Thread.new{ p Salesforce::Model.oauth_params }.join #=> puts nil
In this case you have to reestablish the connection in the new thread (I can do it just if you need it).
I could request something on thread 1 and complete that request, but afterwards, someone else uses thread 1 and I have to use thread 2. Is this possible?
Thinking about it, you need to reset the variable at the beginning of the call in order to avoid that the next request uses the params set in any previous request:
before_action :reset_connection, :sign_user
def reset_connection
Salesforce::Model.establish_connection(nil)
end
def sign_user
# ...

How can I make session data available to my ruby gem in a thread safe way?

I have a API gem which is a public helper library that uses faraday to make resourceful requests to my API. I would like to make a middleware that checks if session data is present (in the form of a hash) and if so would merge these values into the arguments of any request that faraday makes.
My initial attempt involved setting a metaclass attr_accessor (global_params) in the gem's top level class (i.e. MyGem.global_params). The middleware could check this variable for necessary data. This meant that any ApplicationController that had access to my library could implement a before_filter that would set the global_params based on session data and an after_filter could clear it.. so that all faraday requests made by that instance of ApplicationController would share the same global_params set form the session data.
I now wonder if this is thread safe.. and if not what another way I could handle this is?
As for your other question, globals are almost always a sign of doing it wrong and should be avoided whenever possible.
What you need here is a factory method that can customize your context as required.
For example, you're probably doing something like this:
MyGem.global_arg = :foo
MyGem.new(...)
What you could do instead is this:
factory = MyGem.factory(:global_arg => :foo)
factory.new(...)
Or, to preserve a similar sort of feel:
factory = MyGem.factory do |factory|
factory.global_arg = :foo
end
Instead of creating a mattr_accessor in MyGem, you'd create one as an independent object of which MyGem could have a default instance of.

Encrypting Parameters across controllers

I need to pass a parameter from one method in a controller to another.
From my understanding I have to pass the parameters as a GET exposing it in the url string.
What is the best way to encrypt the data so no one can see what is actually getting passed in the string? Also, is there a way to pass it via POST or is my original understanding correct?
I haven't used RoR, but in the web world, this problem is solved with sessions. Using sessions you can store the parameters on the server and avoid sending sensitive data with GET or POST (both are insecure).
The Ruby on Rails Security Guide looks like a great read related to this.
I suggest you abstract your code into lib/ so that you don't have to call additional methods. Instead of making a new HTTP request, just put the code in a central place and call it from there.
class MyController < ApplicationController
def index
MyLibrary::Thing.do_stuff
end
def show
MyLibrary::Thing.do_stuff
end
end
# lib/my_library/thing.rb
module MyLibrary
module Thing
def self.do_stuff
# do stuff!
end
end
end
That way you can access the same code in multiple actions, without doing extra HTTP requests.

Getting the current request in rails from a file in lib/

I've put all of my user-authentication code in one place, namely lib/auth.rb. It looks like this:
lib/auth.rb
module Admin
def do_i_have_permission_to?(permission)
# Code to check all of this goes here
end
end
I include this module as part of the application helper, so these functions are available in all the views:
application_helper.rb
require 'auth'
module ApplicationHelper
include Admin
# other stuff here
end
And I also include it as part of the application controller, so the controllers likewise can call the functions:
application.rb
require 'auth'
class ApplicationController < ActionController::Base
include Admin
end
So far, so good.
The problem is that my application is not like a normal web app. Specifically, more than one user can be logged into the system from the same computer at the same time (using the same browser). I do authentication for actions by looking at all the people who are logged in from that IP and if they can all do it, it passes.
What this means is that, if an admin wants to do something, that admin has to log everyone else out first, which is annoying. But we want the admin seal of approval on everything the admin does. So the suggestion given to me was to have it so the admin can supply a username/password combo on any page they would not normally have access to (e.g. an 'edit user' page would have these extra input fields) and the authentication routines would check for that. This means
Admin::do_i_have_permission_to?(permission)
needs to get at the current request parameters. I can't just use params[:foo] like I would in a controller, because params isn't defined; similarly request.parameters[:foo] will also not work. My searching has revealed:
The current search parameters are in the current request,
The current request is in the current controller,
The current controller is in the current dispatcher, and
I'm not sure the current dispatcher is kept anywhere.
That said, experience tells me that when I'm jumping through this many hoops, I'm very probably Doing It Wrong. So what is the right way to do it? Options I've considered are:
Just move all the functions currently in auth.rb into the ApplicationHelper where (I think) they'll have access to the request and such. Works, but clutters the hell out of the helper.
Move all the functions somewhere else they'll see those methods (I don't know where)
I'm just plain missing something.
In a typical Rails application, authentication information is stored in the active session, not the parameters. As such, it's pretty straightforward to write a helper that does what you want.
It seems rather unorthodox to create a module that is then included in ApplicationHelper. The traditional approach is to create a separate helper which in this case would probably be called AuthenticationHelper. This can then be included in any required controllers, or if you prefer, loaded into ApplicationController to make it available universally.
In general terms, Helpers should not include other Helpers. It is better to simply load multiple helpers into a given Controller.
Helper methods have full access to any instance variables declared within the controller context they are operating from. To be specific, these are instance variables only (#name) and not local variables (name). Helper methods are executed for a particular view as well.
Further, I'm not sure why a user would be providing credentials and performing an operation in the same step, at least for traditional web-based apps. Usually the process is to log in and then perform an action separately.
However, in the case of an API where each transaction is an independent operation, the most straightforward approach is to do is pull out the relevant request parameters that deal with authentication, establish some controller instance variables, and then proceed to perform the particular request given the constraints that the credentials impose.
The approach I usually follow for this sort of thing is to layer in an authentication structure in the ApplicationController itself which can perform the required checks. These are protected methods.
While it's tempting to roll in a whole heap of them such as can_edit_user? and can_create_group? these very quickly get out of hand. It is a simpler design to put in a hook for a general-purpose can_perform? or has_authority_to? method that is passed an operation and any required parameters.
For example, a very rough implementation:
class ApplicationController < ActionController::Base
protected
def has_authority_to?(operation, conditions = { })
AuthenticationCheck.send(operation, conditions)
rescue
false
end
end
module AuthenticationCheck
def self.edit_user?(conditions)
session_user == conditions[:user]
end
end
class UserController
# ...
def edit
#user = User.find(params[:id])
unless (has_authority_to?(:edit_user, :user => #user))
render(:partial => 'common/access_denied', :status => :forbidden)
end
rescue ActiveRecord::RecordNotFound
render(:partial => 'users/not_found')
end
end
Obviously you'd want to roll a lot of the authority checks into before_filter blocks to avoid repetition and to promote consistency.
A full framework example might be of more help, such as the Wristband user authentication system:
http://github.com/theworkinggroup/wristband/tree/master

Resources