Session problem using Facebooker with Ruby on Rails - ruby-on-rails

I am reading the book Facebook Platform Development in order to try to code a small game for Facebook, and I have come across a "little" problem: I am trying to insert a user every time this is logged, into a database in my computer. I am using a couple of methods written in the book, but there seems to be a couple of problems:
I can't seem to retrieve the session_key from Facebook using the Facebooker helpers for RoR, and thus this value is null into the table in my database.
Every time I reload the webpage, I can see that even though the facebook_id is the same, the same user is added in another row to my table in the database, even though it shouldn't; it's just supposed to update the attribute session_key if this changes -anyway, right now this is null.
These are the three methods I am using in order to perform all this:
def self.for(facebook_id,facebook_session=nil)
user = User.find_or_create_by_facebook_id(facebook_id)
unless facebook_session.nil?
user.store_session(facebook_session.session_key)
end
end
def store_session(session_key)
if self.session_key != session_key
update_attribute(:session_key, session_key)
end
end
# Re-create a Facebooker::Session object outside a request
def facebook_session
#facebook_session ||= returning Facebooker::Session.create do |session|
# Facebook sessions are good for only one hour storing
session.secure_with!(session_key,facebook_id,1.hour.from_now)
end
end
Thanks a lot in advance to everybody!1.

Hey sadly facebook changes its API all the time!
Make sure that the book is up to date and that none of the API has changed as of when the book was written. Also check that the gem is also up to date.
I personally use http://github.com/chrisdinn/hyper-graph when dealing with facebook. It makes calls to the facebook graph (graph.facebook.com)

Related

Rails 4 session.id occasionally nil

I'm running a simple website on Heroku and I'm noticing something strange occurring when I'm running the app. It appears that approximately 50-60% of my users are reporting a nil session_id when it gets logged in my database.
I'm using active_record_store for my session handler and Postgres as my db server. I've gotten similar results using the cookie_store, so i'm not sure what i'm doing wrong. The only guess I have is that the first request a user makes, the id might not be populated yet. The sessions table has the correct number of entries, but my tracking table does not.
Example Code
class CaptionController < ApplicationController
def index
#image = Image.order("RANDOM()").first
Tracking.log(session.id, Tracking::VIEW_CAPTION_ON_IMAGE, #image.id)
end
The code above results in 50% of the time, the session being nil in the table it logs to.
I found the answer, it looks like Rails is trying to be efficient by only creating a session if there is something to store. So accessing the session.id without storing something doesn't return consistent results.
You need to force the session to be created by storing something in it.
TLDR: Add this somewhere before you access the session ID.
session[:foo] = "bar"
Source: http://www.gani.com.au/2013/08/force-session-creation-in-rails/

Adding User-Agent & IP to a stored Session -RecordNotSaved -Rails

I'm currently building an in-house analytics system which tracks where a visitor clicks throughout each session, whether they are logged into a User account or are a visitor without an account.
I am currently saving my sessions to the database thanks to changes made through sessions_store.rb, however in addition to the session_id, I am trying to figure out how to add both UserAgent details and a visitor's IP to the sessions table.
I've tried a couple solutions but all have failed - my current solution appears to be the closest, however I keep encountering an ActiveRecord::RecordNotSaved error after updating the Session's attributes.
I am currently using a before filter in application controller:
before_filter :set_useragent_and_ip_in_session
def set_useragent_and_ip_in_session
if session
sess = request.session_options[:id]
#session = Session.where(session_id: sess).first
#session.update_attributes(:ip=>request.remote_ip, :user_agent=>request.user_agent)
#session.save!
else
end
end
I've inserted a debugging statement in my views and have played around the code in pry - the #session is valid and displays the #session.user_agent properly .... however when saving to the DB it justs rollsback.
When I use save!, I receive a Completed 422 Unprocessable Entity in the logs in addition to the following (pasted to gist to conserve space):
https://gist.github.com/anonymous/8019c2426334f395a5fd
Thanks! Any help would be very appreciated.
I would recommend rethinking your schema. A session can last many requests and you want a record per request. Also notice how your moving data off the request object and trying to store them into a session table. Instead make your very own request table and make a before filter that moves all the data you want from the request object to the request table. Now a session will have many requests.
I'm not sure why your record isn't saving however I would wager naming a model Session is conflicting with rails. By that same token when you make your request table you should give it a unique name like maybe SessionMeta and RequestMeta. Then SessionMeta could have many RequestMeta.

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.

How to store where a new user was referred? Using Rails + Devise

I have a rails app that uses devise. I'm curious to know, is it possible in the User table to somehow track where a new user came from, the HTTP referrer?
I'd like to know which came from Facebook, Twitter, LinkedIn, Google+ in order to track a viral loop.
Any ideas? Seen anyone do this? Possible? Where should this live in the rails app? Still very new. Thanks
It could be done like this. May require some tweaking and fixing but You'll get an idea
Make before filter for Application controller, you will call it for any action
def landing_filter
if from_other_site(request.referrer) and !session[:referer].blank?
session[:referer] = request.referrer #you don't want to delete first entrance
end
end
from_other_site should be the method which will check domain name in referrer url, if it match your then return false, otherwise true
in devise/registration/new.erb.html view add in form hidden field
<%= f.hidden_field :referrer, session[:referrer] %>
and don't forget to add migration with new database field for user
Save referer somewhere and after creating a user copy information to user table. Using session to save referer works but permanent cookies are better. Cookies can persist the information even when user closes browser and comes again in the next day.
# so basically in ApplicationContreller using before_filter
def referer_before_filter
if cookies[:referer].blank?
cookies.permanent[:referer] = request.env["HTTP_REFERER"] || 'none'
end
end
# and in signup action somewhere else saving that information
#user.referer = cookies[:referer] # or maybe to some other table
Instead of modifying every action you can also use rails sweepers/observers to handle automatic saving every time an object is created.
A good gem to automatically save referer and other needed information is
https://github.com/holli/referer_tracking . You can choose do you want to save information manually or use sweepers to do saving automatically.

Finding last active time for logged in user

I am using ruby on rails session to store a user cookie to keep them logged in, so I can't just update a last_seen column after they login. I'm trying to figure out the best way to find out if a user has been active in the last day. This is what I have so far but I'm wondering if there's a better way:
class ApplicationController
before_filter :update_last_seen
private
def update_last_seen
if (DateTime.now - 1.day) < current_user.last_seen
current_user.last_seen = DateTime.now
current_user.save
end
end
end
The problem with this is that it is going to get called with every request. Is there any way to avoid this? Does the session cookie get updated somehow when a user is active?
No, that is exactly how you should go about it. before_filters are a great way to keep track of things like that, and are how authlogic implements it's authentication system as well. There's no way to do processing on one request "per day". If you use Authlogic as your authentication method, it has last-login time built in. You can see an example of it here.

Resources