rails architecture/best practice question - ruby-on-rails

i have been brainstorming the best way to do this, and figured i should reach out to the community for some ideas/clarity.
basically from a single payment controller, i want to be able to handle various payment options that a user might select. for example, my controller gets hit with a post request with :payment_option => paypal. i want to pass off logic to handle the paypal specific operations, then hand back to the controller a url (to paypal) to redirect to.
i was doing a params[:payment_option].constantize to initialize a Paypal class, but the problem i ran into was not able to access various pieces of data that paypal requires (ie current user information, request IP address, cookie data, url helpers, etc.)
then i thought maybe i could have a paypal module, but how to include the correct payment module programmatically? and it seemed that i might be mis-using the module concept because i would be using the module for specific logic, rather than shared logic.
so if the user instead chooses google checkout, the controller regardless of payment method, should only need generic instructions
take params[:payment_option]
get the payment_option_url
receive payment_option_response
any thoughts on a good approach to doing something like this? i have run into similar scenarios in the past, but was never to sure it was the best route.

class Payment
def self.handle
raise 'must impliment in subclass'
end
end
class PaypalPayment < Payment
end
class GooglePayment < Payment
end
class PaymentController < ApplicationController
def show_me_the_money
case params[:payment_option]
when 'paypal': url = PaypalPayment.handle params
when 'google': url = GooglePayment.handle params
end
redirect_to url
end
end

Related

How can I access the session of a rails app from a PORO?

I'm working on a wizard - a PORO module - for user's information. The goal is to forward the users to said wizard for him to complete his user profile if he attempts to make a booking (or similar action) with an incomplete profile.
After the last step of the wizard I would like to redirect the user back to the action he intended initially. For that I'm saving a session variable named ":user_return_to_from_wizard".
I can't seem to access the session variable from the PORO module. What can I do?
I tried of course
session[:user_return_to_from_wizard]
but that doesn't work. I guess something like
App::Application.session....
You probably can't and should'nt - one of nice things of using PORO is to be able to use them outside of a specific context (HTTP and session in your case). What I would do is collect the information you need from the session and use it to initialize your wizard:
class SomeController < ApplicationController
def index
return_url = session[:user_return_to_from_wizard]
wizard = Wizard.new(return_url: return_url)
...
end
end
This way you can still test/use Wizard independently and don't have to rely on session inside.

How to handle Shopify API connection with Shopify gem?

Hi I'm using the Shopify gem in my Shopify app and I'm looking for suggestions on how to handle the API connection to Shopify.
I'm using webhooks and delayed_jobs so I need a way to open the connection outside of the controller.
At the moment I added this method to my Shop model:
def connect_to_store
session = ShopifyAPI::Session.new(self.url, self.access_token)
session.valid?
ShopifyAPI::Base.activate_session(session)
end
So I can open the connection very easily, for example:
Shop.find(1).connect_to_store
ShopifyAPI::Shop.current.name
The problem is that, inside my Product module, I need the connection open inside several methods but I end up calling the connect_to_store method several times and I'm worried about opening several connections to the same store, without a real need.
Is there a way to check if a connection is already opened and open a new one only if another one is not found?
Thanks,
Augusto
------------------- UPDATE -------------------
I explain better my issue.
Let's say that in my Product model I want to see if a given product has a compare_at_price greater than its price and, in this case, I want to add a "sale" tag to the Shopify product.
In my Product model I have:
class Product < ActiveRecord::Base
belongs_to :shop
def get_from_shopify
self.shop.connect_to_store
#shopify_p = ShopifyAPI::Product.find(self.shopify_id)
end
def add_tag(tag)
#shopify_p = self.get_from_shopify
shopify_p_tags = shopify_p.tags.split(",")
shopify_p_tags.collect{|x| x.strip!}
unless shopify_p_tags.include?(tag)
shopify_p_tags << tag
shopify_p_tags.join(",")
shopify_p.tags = shopify_p_tags
shopify_p.save
end
end
def on_sale?
#shopify_p = self.get_from_shopify
sale = false
shopify_p.variants.each do |v|
unless v.compare_at_price.nil?
if v.compare_at_price > v.price
sale = true
end
end
end
return sale
end
def update_sale_tag
if self.on_sale?
self.add_tag("sale")
end
end
end
My problem is that if I call:
p.update_sale_tag
the Shop.connect_to_store is called several times and I authenticate several times while I'm already authenticated.
How would you refactor this code?
I approach this by storing the OAuth token that is returned by Shopify with the store (you should be doing this anyway). All you need to access the API is the token, so in your shop model you would have a method like:
def shopify_api_path
"https://#{Rails.configuration.shopify_api_key}:#{self.shopify_token}##{self.shopify_domain}/admin"
end
Then if you want to access the API for a particular store in a Delayed Job worker, you would simply:
begin
ShopifyAPI::Base.site = shop.shopify_api_path
# Make whatever calls to the API that you want here.
products = ShopifyAPI::Product.all
ensure
ShopifyAPI::Base.site = nil
end
Hopefully that helps a little. I find working with Sessions outside of controllers to be a bit messy, particularly since this is nice and easy.
Once your application has authenticated once, you can hold on to that computed password – it’s good until the app is uninstalled for that particular store.
In other words, authenticate just the once when the merchant first installs the app, save the password to a db, and load it up whenever you need it. Your self.shop.connect_to_store call should then just set the ShopifyAPI::Session instance.
I think there is some misunderstanding here. You do know that you are really just using Active Resource for all your API work? And therefore when you authenticate, you are probably authenticating a session? And that once authenticated, no matter how many times you actually use the API, you're not actually opening "new" connections.
You are doing it wrong if you are constantly authenticating in a single session to do more than one API call.
If you happen to be in a block of code that has no authentication (for example your App may process a WebHook from N shops) or a Delayed Job, simply pass the myshopify_domain string to those code blocks, look up the Shop in your DB, find the auth token, authenticate (once)... and away you go... it really quite simple.

Preventing discoverability in a RESTfully routed model

I have a model in my database whose 'show' action is open to viewing at URLs like:
mysite.com/project/12
mysite.com/project/14
The way my system is set up, there are a couple of defined methods through which these should be accessible:
A custom route I've set up is accessible to any visitor (registered or unregistered) who has this route. As an example, this custom route might be mysite.com/companyname/projectid, which the company might pass out itself to certain people it wants to have access. Note that this custom route runs a separate controller action, which sets some internal analytics then redirects to the show action.
Direct access when linked to by a registered user's home page.
I want to restrict the ability to start with mysite.com/project/14 then simply change the IDs, thereby seeing any project. How can I do this?
Clarification
My goal with this question is not just to obfuscate record IDs to make discovering certain records harder. Instead, I would like there to be only two allowable means of accessing project/12:
A user clicks on a link we provide on their home page (how can I ensure this link alone reaches project 12?)
A user or simple visitor is redirected here by another (specific) controller action.
Typing in project/12 directly should not be possible. At the moment, I imagine the best way to do this would be for the two methods above to pass a code that gets picked up by the project#show action. I just don't know how to implement this and if there are potential drawbacks.
Whatever you come up with - it is going to end up being security through obscurity due to this simple requirement:
A user clicks on a link we provide on
their home page (how can I ensure this
link alone reaches project 12?)
What you can do, however, is make it difficult to just straight-up guess the correct URL for the project.
My thought would be to give every Project a unique 'token' - If you are not logged in as the owner of the project, then you must use the token to access it.
For instance, in your project model you could have this:
class Project
before_create :set_public_token
protected
def set_public_token
# Randomizes a 20-digit long hex code
self.token = ActiveSupport::SecureRandom.hex(20)
end
end
Then, in your project's show action you would need to have this:
class ProjectsController < ApplicationController
def show
#project = Project.find(params[:id])
# Obviously you would changed signed_in? to whatever method
# you have that verifies someone is logged in
if !signed_in? || #project.owner_id != current_user.id
raise "Unauthorized Access" if #project.token != params[:token]
end
end
end
Then the owner of the project can share the 'public' link of their project to people they want to have access to it, which would look something like this:
www.example.com/projects/14?token=3jks83kasdkt84h6cd86
Again, anyone with that url could access the project, and I don't think you will be able to sanely get away from that - but it makes it a lot more difficult to do so.
This is the same concept many password reset functions work. Anyone with access to the password reset token could reset your password after you've requested a password. But knowing what token to use will take you ages (Make the token longer to make it harder to bruteforce).
That personally is how I would handle it, and how I've seen this sort of thing handled in the past (photobucket, private gists on github, etc)
The easiest way is to associate a project with a user or account, then require authentication when browsing your non public routes. If you setup an association, you can then do:
#user = current_user
#project = #user.projects.find(params[:id])
This will ensure that a given user can only find projects they 'own'.
If you don't want authorization, and just want obfuscation, you won't be able to use the 'id' alone in the route (as it is sequential). You could either pair the 'id' with a random key stored in the model (/projects/1?key=1234) or use a GUID instead of an id.
OK so another attempt now that I sort of understand.
First in your public controller action you want to do something like this:
def public_redirect
session[:authorized_for] = params[:id]
redirect_to resource_show_path(params[:id])
end
Now in your private controller:
def show
#resource = current_user.resources.find params[:id]
if #resource # authorized
respond_with #resource # ok
elsif session[:authorized_for] == params[:id] #redirected from public route
#resource = Resource.find params[:id]
respond_with #resource # ok
else
raise NotAuthorizedException # not ok, do something
end
end
This relies on sessions. This is certainly hackable, but it would be much harder then figuring out the public route. See http://guides.rubyonrails.org/security.html#sessions.
You can reuse the session technique for other similar needs (like for links from home pages where you can't verify the user from the controller, etc.
I have a project that has a similar requirement. Now first I feel the need to say that this is security by obscurity - and thus not much security at all. But for some apps that can be OK.
I have a on create callback on my model that generates a random string (or number) that I use as my ID - thus it is impossible hard to guess another resource's path.

RoR : Polymorphic Controllers

I have an existing site that has a bunch of different models and controllers. I am currently integrating Twilio's services into this site. Twilio allows you to supply a url that will be called when a user interacts with your phone number using their phone. Unfortunately, there is only one url that you can provide to Twilio and then all the parsing is done on your end.
So, now I have a twilio controller which parses the user's data and decides what they are trying to do.
Everything the user may be trying to do via their phone can be done on the website already, but now they have the option to use their phone when on the go. If they text my number "create group foo" then the site will try to create the group accordingly. My issue is that I already have a groups controller that knows how to create groups and has the appropriate before_filters to make sure that the user has permission to do so, amongst other things.
Is there a way for the twilio controller to parse the request and then "forward" it over to the proper controller in some way? I'd rather not have the twilio controller duplicate all of the code and filters that are in every other controller and some of that stuff doesn't feel right to be shoved into the models.
I'm somewhat new to rails in general, so I'm open to any suggestion. I'm hoping there's some design pattern out there that fits my use case and I'm willing to refactor my whole project for the correct solution.
I think there are a couple of things you can do. If you don't have to respond in a certain format, then you can simply redirect the request with the appropriately formatted parameters. For example:
class TwilioController
def create
if params[:twilio_action] == 'create group'
redirect_to create_group_path(:id => params[:group_id], :number => params[:number])
end
end
end
There's a good chance that you'll have problems with authentication though, because the twilio api will not be sending and receiving cookies for you, so you will not have an authenticated user. If this is the case it will be best to put all your shared code in the model and handle cookie authentication with your GroupsController and phone number authentication with your TwilioController. For example:
class TwilioController
def create
if params[:twilio_action] == 'create group'
if can_create_group?(params[:phone_number])
Group.create(:id => params[:group_id])
end
end
end
end
It's always best to put your business logic in your model, but if you do actually have a function you want to share within two controllers you can always create a module to do that as well:
module GroupControllerActions
def create_group user
Group.create(params[:group].merge({:user => user}))
end
end
class TwilioController
include GroupControllerActions
def create
if params[:twilio_action] == 'create group'
create_group(User.find_by_number(params[:phone_number]))
end
end
end
class GroupsController
def create
create_group(current_user)
end
end

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