如何创建自定义omniauth提供程序(如何返回数据)

时间:2013-10-30 09:50:45

标签: ruby-on-rails ruby omniauth provider

我在网上搜索,如何为omniauth创建一个自定义提供程序..并且我部分地成功了..

我创建了一个gem,它工作得很好,除了部分之外,我无法理解如何将收集的数据返回到会话控制器,就像其他提供商一样。

这是auth gem中的代码:

require 'multi_json'
require 'digest/md5'
require 'rest-client'

module OmniAuth
  module Strategies
    class Providername < OmniAuth::Strategies::OAuth
      attr_accessor :app_id, :api_key, :auth

      def initialize(app, app_id = nil, api_key = nil, options = {})
        super(app, :providername)
        @app_id = app_id
        @api_key = api_key
      end

      protected

      def request_phase
        redirect "http://valid_url"
      end

      def callback_phase
        if request.params['code'] && request.params['status'] == 'ok'
          response = RestClient.get("http://valid_url2/?code=#{request.params['auth_code']}")
          auth = MultiJson.decode(response.to_s)
          unless auth['error']
            @auth_data = auth

            if @auth_data
              @return_data = OmniAuth::Utils.deep_merge(super, {
                  'uid' => @auth_data['uid'],
                  'nickname' => @auth_data['nick'],
                  'user_info' => {
                    'first_name' => @auth_data['name'],
                    'last_name' => @auth_data['surname'],
                    'location' => @auth_data['place'],
                  },
                  'credentials' => {
                    'apikey' => @auth_data['apikey']
                  },
                  'extra' => {'user_hash' => @auth_data}
                })
            end

          end
        else
          fail!(:invalid_request)
        end
      rescue Exception => e
        fail!(:invalid_response, e)
      end

    end
  end
end

这里我在初始化程序中调用它:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider "providername", Settings.providers.providername.app_id, Settings.providers.providername.app_secret
end

在此代码中,到目前为止一切正常,提供程序被调用,我从提供程序获取信息,我创建一个带有信息的哈希(@auth_data),但我如何返回它

1 个答案:

答案 0 :(得分:0)

看起来您必须定义一个名为auth_hash的新方法,以便您可以从omniauth实例中调用它。

https://gist.github.com/dira/722793

您是否查看了omniauth构建策略指南?

https://github.com/intridea/omniauth/wiki/Strategy-Contribution-Guide

其他指南指向auth_hash方法的想法:

http://anti-pattern.com/adding-a-new-strategy-to-omniauth