Hi,
Meanwhile I got it working. Don't know if it's the best way to deal with it but it's functional right now.
Here what I did:
My ApplicationController:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
helper_method :current_user_session, :current_user, :current_fb_user
filter_parameter_logging :password, :password_confirmation
protect_from_forgery
layout 'default'
before_filter :ensure_is_authenticated_in_fb
private
def ensure_is_authenticated_in_fb
#check if any session exists
if !current_user_session || !current_user.is_fb_authorized || !current_fb_user
html = ""
html +="<script>"
html +="window.top.location.href=\"#{new_oauth_url}\""
html +="</script>"
render :text=>html
end
end
def current_fb_user
return @current_fb_user if defined?(@current_fb_user)
@current_fb_user = fb_user = Mogli::User.find("me",Mogli::Client.new(current_user.fb_at))
rescue Exception
@current_fb_user = nil
end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
The OAuthController looks like this:
class OauthController < ApplicationController
skip_filter :ensure_is_authenticated_in_fb
def new
redirect_to authenticator.authorize_url(:scope => 'publish_stream', :display => 'page')
end
def create
mogli_client = Mogli::Client.create_from_code_and_authenticator(params[:code],authenticator)
fb_user = Mogli::User.find("me",Mogli::Client.new(mogli_client.access_token))
#if new user, create new one
if !user
user = User.new
user.fb_at = mogli_client.access_token
...
user.save!
else #if returning user, then update access token
user.fb_at = mogli_client.access_token
user.save!
end
#try to authenticate user
#remove old session if exists
if current_user_session
current_user_session.destroy
end
#create session
@user_session = UserSession.create(user, true)
@user_session.save
#redirect to canvas page
html = ""
html +="<script>"
html +="</script>"
render :text=>html
end
def authenticator
@authenticator ||= Mogli::Authenticator.new(WEBAPP_CONFIG['facebook_client_id'],WEBAPP_CONFIG['facebook_secret'],oauth_callback_url)
end
end
In the User model, what's relevant is:
class User < ActiveRecord::Base
acts_as_authentic
...
...
def is_fb_authorized
return false if self.fb_uid == 0 || !self.fb_at || self.fb_at.empty?
return true
end
end
Hope it helps. It's working but if you have any better way to deal with it will be great.