javaeye3/lib/multi_auth/google.rb

72 lines
2.4 KiB
Ruby
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

require 'rubygems'
require 'openid'
require 'openid/store/filesystem'
require 'openid/extensions/ax'
require 'timeout'
module MultiAuth
class Google < Strategy
AppConfig = {
:service_name => "Google",
:callback => "http://#{DEFAULT_SITE_DOMAIN}/auth/google/callback"
}
AX = {
:email => 'http://axschema.org/contact/email',
:firstname => 'http://axschema.org/namePerson/first',
:lastname => 'http://axschema.org/namePerson/last'
}
def initialize(params, auth_hash = nil)
@params = params
@auth_hash = auth_hash || {}
@consumer = OpenID::Consumer.new(@auth_hash, OpenID::Store::Filesystem.new("#{Rails.root}/tmp/openid/google"))
end
def request
response = Timeout::timeout(5) do
@consumer.begin 'https://www.google.com/accounts/o8/id'
end
ax = OpenID::AX::FetchRequest.new
AX.each{|key, value| ax.add OpenID::AX::AttrInfo.new(value, key, true) }
response.add_extension ax
@auth_hash = @auth_hash.merge({
:provider => 'google',
:redirect_to => response.redirect_url("http://#{DEFAULT_SITE_DOMAIN}", AppConfig[:callback])
})
rescue Timeout::Error, OpenID::DiscoveryFailure, OpenID::FetchingError
raise Error, "由于Goolge的网络连接不稳定访问超时请稍后重试"
rescue OpenID::OpenIDError
raise Error, "验证过程发生错误,请稍后重试"
end
def callback
@response = Timeout::timeout(5) do
@consumer.complete @params.reject{|key, value| !key.match(/^openid/) }, AppConfig[:callback]
end
raise Error, "验证失败" unless @response.status == OpenID::Consumer::SUCCESS
@auth_hash = {
:provider => 'google',
:uid => @response.display_identifier,
}
rescue Timeout::Error, OpenID::DiscoveryFailure, OpenID::FetchingError
raise Error, "由于Goolge的网络连接不稳定访问超时请稍后重试"
rescue OpenID::OpenIDError
raise Error, "验证过程发生错误,请稍后重试"
end
def user_info
ax_response = OpenID::AX::FetchResponse.from_success_response(@response)
email = ax_response.data[AX[:email]]
firstname = ax_response.data[AX[:firstname]]
lastname = ax_response.data[AX[:lastname]]
{ :name => "#{firstname}-#{lastname}", :email => email }
end
end
end