2 require 'openid/extensions/sreg'
3 require 'openid/extensions/ax'
4 require 'openid/store/filesystem'
6 require File.dirname(__FILE__) + '/open_id_authentication/association'
7 require File.dirname(__FILE__) + '/open_id_authentication/nonce'
8 require File.dirname(__FILE__) + '/open_id_authentication/db_store'
9 require File.dirname(__FILE__) + '/open_id_authentication/request'
10 require File.dirname(__FILE__) + '/open_id_authentication/timeout_fixes' if OpenID::VERSION == "2.0.4"
12 module OpenIdAuthentication
13 OPEN_ID_AUTHENTICATION_DIR = RAILS_ROOT + "/tmp/openids"
19 def self.store=(*store_option)
20 store, *parameters = *([ store_option ].flatten)
24 OpenIdAuthentication::DbStore.new
26 OpenID::Store::Filesystem.new(OPEN_ID_AUTHENTICATION_DIR)
34 class InvalidOpenId < StandardError
39 :missing => "Sorry, the OpenID server couldn't be found",
40 :invalid => "Sorry, but this does not appear to be a valid OpenID",
41 :canceled => "OpenID verification was canceled",
42 :failed => "OpenID verification failed",
43 :setup_needed => "OpenID verification needs setup"
58 ERROR_MESSAGES.keys.each { |state| define_method("#{state}?") { @code == state } }
65 ERROR_MESSAGES.keys.include?(@code)
73 # normalizes an OpenID according to http://openid.net/specs/openid-authentication-2_0.html#normalization
74 def self.normalize_identifier(identifier)
76 identifier = identifier.to_s.strip
78 # if an XRI has a prefix, strip it.
79 identifier.gsub!(/xri:\/\//i, '')
81 # dodge XRIs -- TODO: validate, don't just skip.
82 unless ['=', '@', '+', '$', '!', '('].include?(identifier.at(0))
83 # does it begin with http? if not, add it.
84 identifier = "http://#{identifier}" unless identifier =~ /^http/i
87 identifier.gsub!(/\#(.*)$/, '')
90 uri = URI.parse(identifier)
91 uri.scheme = uri.scheme.downcase # URI should do this
92 identifier = uri.normalize.to_s
93 rescue URI::InvalidURIError
94 raise InvalidOpenId.new("#{identifier} is not an OpenID identifier")
101 # deprecated for OpenID 2.0, where not all OpenIDs are URLs
102 def self.normalize_url(url)
103 ActiveSupport::Deprecation.warn "normalize_url has been deprecated, use normalize_identifier instead"
104 self.normalize_identifier(url)
108 def normalize_url(url)
109 OpenIdAuthentication.normalize_url(url)
112 def normalize_identifier(url)
113 OpenIdAuthentication.normalize_identifier(url)
116 # The parameter name of "openid_identifier" is used rather than the Rails convention "open_id_identifier"
117 # because that's what the specification dictates in order to get browser auto-complete working across sites
118 def using_open_id?(identity_url = nil) #:doc:
119 identity_url ||= params[:openid_identifier] || params[:openid_url]
120 !identity_url.blank? || params[:open_id_complete]
123 def authenticate_with_open_id(identity_url = nil, options = {}, &block) #:doc:
124 identity_url ||= params[:openid_identifier] || params[:openid_url]
126 if params[:open_id_complete].nil?
127 begin_open_id_authentication(identity_url, options, &block)
129 complete_open_id_authentication(&block)
134 def begin_open_id_authentication(identity_url, options = {})
135 identity_url = normalize_identifier(identity_url)
136 return_to = options.delete(:return_to)
137 method = options.delete(:method)
139 options[:required] ||= [] # reduces validation later
140 options[:optional] ||= []
142 open_id_request = open_id_consumer.begin(identity_url)
143 add_simple_registration_fields(open_id_request, options)
144 add_ax_fields(open_id_request, options)
145 redirect_to(open_id_redirect_url(open_id_request, return_to, method))
146 rescue OpenIdAuthentication::InvalidOpenId => e
147 yield Result[:invalid], identity_url, nil
148 rescue OpenID::OpenIDError, Timeout::Error => e
149 logger.error("[OPENID] #{e}")
150 yield Result[:missing], identity_url, nil
153 def complete_open_id_authentication
154 params_with_path = params.reject { |key, value| request.path_parameters[key] }
155 params_with_path.delete(:format)
156 open_id_response = timeout_protection_from_identity_server { open_id_consumer.complete(params_with_path, requested_url) }
157 identity_url = normalize_identifier(open_id_response.display_identifier) if open_id_response.display_identifier
159 case open_id_response.status
160 when OpenID::Consumer::SUCCESS
163 # merge the SReg data and the AX data into a single hash of profile data
164 [ OpenID::SReg::Response, OpenID::AX::FetchResponse ].each do |data_response|
165 if data_response.from_success_response( open_id_response )
166 profile_data.merge! data_response.from_success_response( open_id_response ).data
170 yield Result[:successful], identity_url, profile_data
171 when OpenID::Consumer::CANCEL
172 yield Result[:canceled], identity_url, nil
173 when OpenID::Consumer::FAILURE
174 yield Result[:failed], identity_url, nil
175 when OpenID::Consumer::SETUP_NEEDED
176 yield Result[:setup_needed], open_id_response.setup_url, nil
181 OpenID::Consumer.new(session, OpenIdAuthentication.store)
184 def add_simple_registration_fields(open_id_request, fields)
185 sreg_request = OpenID::SReg::Request.new
187 # filter out AX identifiers (URIs)
188 required_fields = fields[:required].collect { |f| f.to_s unless f =~ /^https?:\/\// }.compact
189 optional_fields = fields[:optional].collect { |f| f.to_s unless f =~ /^https?:\/\// }.compact
191 sreg_request.request_fields(required_fields, true) unless required_fields.blank?
192 sreg_request.request_fields(optional_fields, false) unless optional_fields.blank?
193 sreg_request.policy_url = fields[:policy_url] if fields[:policy_url]
194 open_id_request.add_extension(sreg_request)
197 def add_ax_fields( open_id_request, fields )
198 ax_request = OpenID::AX::FetchRequest.new
200 # look through the :required and :optional fields for URIs (AX identifiers)
201 fields[:required].each do |f|
202 next unless f =~ /^https?:\/\//
203 ax_request.add( OpenID::AX::AttrInfo.new( f, nil, true ) )
206 fields[:optional].each do |f|
207 next unless f =~ /^https?:\/\//
208 ax_request.add( OpenID::AX::AttrInfo.new( f, nil, false ) )
211 open_id_request.add_extension( ax_request )
214 def open_id_redirect_url(open_id_request, return_to = nil, method = nil)
215 open_id_request.return_to_args['_method'] = (method || request.method).to_s
216 open_id_request.return_to_args['open_id_complete'] = '1'
217 open_id_request.redirect_url(root_url, return_to || requested_url)
221 relative_url_root = self.class.respond_to?(:relative_url_root) ?
222 self.class.relative_url_root.to_s :
223 request.relative_url_root
224 "#{request.protocol}#{request.host_with_port}#{ActionController::Base.relative_url_root}#{request.path}"
227 def timeout_protection_from_identity_server
229 rescue Timeout::Error
236 "Identity server timed out"