如何让 Koala 与 Omniauth 融洽相处?

发布于 2024-11-28 15:07:03 字数 1973 浏览 1 评论 0原文

我正在尝试让 Koala 与 Omniauth 合作。用户模型使用 Omniauth 登录 Facebook,我想使用 Koala 作为客户端来提取正在使用该应用程序的用户好友列表。我似乎没有正确保存令牌:

控制器

@friends = Array.new
 if current_user.token
   graph = Koala::Facebook::GraphAPI.new(current_user.token)
   @profile_image = graph.get_picture("me")
   @fbprofile = graph.get_object("me")
   @friends = graph.get_connections("me", "friends")
end

DB 架构

create_table "users", :force => true do |t|
  t.string   "provider"
  t.string   "uid"
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "token"
end

用户模型具有

def self.create_with_omniauth(auth)  
  create! do |user|  
    user.provider = auth["provider"]  
    user.uid = auth["uid"]  
    user.name = auth["user_info"]["name"]  
  end  
end

Koala.rb 初始值设定项具有:

module Facebook
  CONFIG = YAML.load_file(Rails.root.join("config/facebook.yml"))[Rails.env]
  APP_ID = CONFIG['app_id']
  SECRET = CONFIG['secret_key']
end

Koala::Facebook::OAuth.class_eval do
  def initialize_with_default_settings(*args)
    case args.size
      when 0, 1
        raise "application id and/or secret are not specified in the config" unless Facebook::APP_ID && Facebook::SECRET
        initialize_without_default_settings(Facebook::APP_ID.to_s, Facebook::SECRET.to_s, args.first)
      when 2, 3
        initialize_without_default_settings(*args) 
    end
  end 

  alias_method_chain :initialize, :default_settings 
end

会话控制器具有:

  def create  
    auth = request.env["omniauth.auth"]  
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
    session[:user_id] = user.id  

    session['fb_auth'] = request.env['omniauth.auth']
    session['fb_access_token'] = omniauth['credentials']['token']
    session['fb_error'] = nil

    redirect_to root_url 
  end  

I'm trying to get Koala to work with Omniauth. A User model logs in with Facebook using Omniauth and I want to use Koala as a client to pull the list of a user's friends that are using the app. I don't seem to be saving the tokens properly:

Controller

@friends = Array.new
 if current_user.token
   graph = Koala::Facebook::GraphAPI.new(current_user.token)
   @profile_image = graph.get_picture("me")
   @fbprofile = graph.get_object("me")
   @friends = graph.get_connections("me", "friends")
end

DB Schema

create_table "users", :force => true do |t|
  t.string   "provider"
  t.string   "uid"
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "token"
end

User model has

def self.create_with_omniauth(auth)  
  create! do |user|  
    user.provider = auth["provider"]  
    user.uid = auth["uid"]  
    user.name = auth["user_info"]["name"]  
  end  
end

Koala.rb initializer has:

module Facebook
  CONFIG = YAML.load_file(Rails.root.join("config/facebook.yml"))[Rails.env]
  APP_ID = CONFIG['app_id']
  SECRET = CONFIG['secret_key']
end

Koala::Facebook::OAuth.class_eval do
  def initialize_with_default_settings(*args)
    case args.size
      when 0, 1
        raise "application id and/or secret are not specified in the config" unless Facebook::APP_ID && Facebook::SECRET
        initialize_without_default_settings(Facebook::APP_ID.to_s, Facebook::SECRET.to_s, args.first)
      when 2, 3
        initialize_without_default_settings(*args) 
    end
  end 

  alias_method_chain :initialize, :default_settings 
end

Sessions controller has:

  def create  
    auth = request.env["omniauth.auth"]  
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
    session[:user_id] = user.id  

    session['fb_auth'] = request.env['omniauth.auth']
    session['fb_access_token'] = omniauth['credentials']['token']
    session['fb_error'] = nil

    redirect_to root_url 
  end  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黑白记忆 2024-12-05 15:07:04

您已经知道的问题是 fb_access_token 仅在当前会话中可用,并且对 Koala 不可用。

你的用户模型有存储“token”的列吗?如果没有,请确保用户模型中有该列。当用户模型中有该列时,您需要在创建用户时在其中存储一些内容(User 类中的 create_with_omniauth 方法)。从 facebook 成功授权后,您应该会发现令牌字段已填充 facebook oauth 令牌。如果它已填充,那么您的 Koala 代码应该可以工作。在这种情况下,无需在会话中存储 facebook 凭据。

然而,如果您没有从 Facebook 获得离线访问(这意味着访问仅在短时间内提供),那么将 facebook 凭据存储在会话中是有意义的。在这种情况下,您不应该使用“current_user.token”,而应使用 session[" fb_auth_token"] 而不是 Koala。

希望这会有所帮助!

因此,如果您想要离线访问(长期存储 Facebook 授权),请更改您的模型代码以存储 fb_auth_token,如下所示

# User model
def self.create_with_omniauth(auth)  
  create! do |user|  
    user.provider = auth["provider"]  
    user.uid = auth["uid"]  
    user.name = auth["user_info"]["name"]  
    user.token = auth['credentials']['token']
  end  
end

# SessionsController
def create  
  auth = request.env["omniauth.auth"]  
  user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
  # Note i've also passed the omniauth object      

  session[:user_id] = user.id  
  session['fb_auth'] = auth
  session['fb_access_token'] = auth['credentials']['token']
  session['fb_error'] = nil

  redirect_to root_url 
end 

如果您有短期访问权限,请更改您的“其他”控制器使用会话

# The other controller
def whateverthissactionis
  @friends = Array.new
  if session["fb_access_token"].present?
    graph = Koala::Facebook::GraphAPI.new(session["fb_access_token"]) # Note that i'm using session here
    @profile_image = graph.get_picture("me")
    @fbprofile = graph.get_object("me")
    @friends = graph.get_connections("me", "friends")
  end
end

The problem like you already know is that the fb_access_token is only available in the current session and not being available to Koala.

Does your user model have a column to store "token"? If not, then make sure you have that column in the user model. When you have that column in the user model, you will need to store something in it at the time you create the user (create_with_omniauth method in the User class). After successfull authorization from facebook you should find that the token field is populated with the facebook oauth token. If it is populated, then your Koala code should work. In this case there is no need to store the facebook credentials in the session.

If however you are not getting offline access from Facebook (which means the access is only provided for a short duration, then storing the facebook credentials in the session makes sense. In this case you should not use "current_user.token" but session["fb_auth_token"] instead with Koala.

Hope this helps!

So if you want offline access (long term storage of facebook authorization), change your model code to store fb_auth_token as below

# User model
def self.create_with_omniauth(auth)  
  create! do |user|  
    user.provider = auth["provider"]  
    user.uid = auth["uid"]  
    user.name = auth["user_info"]["name"]  
    user.token = auth['credentials']['token']
  end  
end

# SessionsController
def create  
  auth = request.env["omniauth.auth"]  
  user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
  # Note i've also passed the omniauth object      

  session[:user_id] = user.id  
  session['fb_auth'] = auth
  session['fb_access_token'] = auth['credentials']['token']
  session['fb_error'] = nil

  redirect_to root_url 
end 

If you have short term access then change your "other" controller to use sessions

# The other controller
def whateverthissactionis
  @friends = Array.new
  if session["fb_access_token"].present?
    graph = Koala::Facebook::GraphAPI.new(session["fb_access_token"]) # Note that i'm using session here
    @profile_image = graph.get_picture("me")
    @fbprofile = graph.get_object("me")
    @friends = graph.get_connections("me", "friends")
  end
end
黎夕旧梦 2024-12-05 15:07:04

当您可以测试一下时,请避免编写:

https ://github.com/holden/devise-omniauth-example/blob/master/config/initializers/devise.rb

我已经使用该应用程序作为成功的基础。

我已经修复了一些问题,但尚未在 github 上提交。但这些都是非常小的。我认为示例应用程序有效。

您的问题可能不是 Koala,而是令牌未保存,因此您无法查询任何内容,甚至无法连接到 Facebook。

Avoid writing when you can just test this out:

https://github.com/holden/devise-omniauth-example/blob/master/config/initializers/devise.rb

I've used that app as a basis with success.

I've fixed a few issues but haven't committed on github however. But those are very minor. I think the example app works.

Your problem may not be Koala but the fact that the token was not saved so you can't query anything or even connect to Facebook.

旧伤还要旧人安 2024-12-05 15:07:04

您的问题似乎是您将错误的内容传递给 Koala:

if @token = current_user.token
   @graph = Koala::Facebook::GraphAPI.new(oauth_callback_url)
   @friends = @graph.get_connections("me", "friends")
end

尝试将其更改为以下内容:

@friends = Array.new # I think it returns a straight array, might be wrong.
if current_user.token
   graph = Koala::Facebook::GraphAPI.new(current_user.token)
   @friends = graph.get_connections("me", "friends")
end

Your issue looks to be that you're passing the wrong thing into Koala:

if @token = current_user.token
   @graph = Koala::Facebook::GraphAPI.new(oauth_callback_url)
   @friends = @graph.get_connections("me", "friends")
end

Try changing it to the following:

@friends = Array.new # I think it returns a straight array, might be wrong.
if current_user.token
   graph = Koala::Facebook::GraphAPI.new(current_user.token)
   @friends = graph.get_connections("me", "friends")
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文