Skip to content

Instantly share code, notes, and snippets.

@leeadkins
Forked from RSpace/user.rb
Created October 19, 2010 18:48
Show Gist options
  • Save leeadkins/634800 to your computer and use it in GitHub Desktop.
Save leeadkins/634800 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
devise :database_authenticatable, :openid_authenticatable, :recoverable, :rememberable, :trackable, :validatable
# Handle creation of user authenticated via OpenID
def self.create_from_identity_url(identity_url)
User.new(:identity_url => identity_url)
end
# Set email as a required field from the Open ID provider
def self.openid_required_fields
["email", "http://axschema.org/contact/email"]
end
# Accept fields from Open ID provider
def openid_fields=(fields)
fields.each do |key, value|
#Sometimes these values are arrays. That will cause you a headache later on
if value.is_a? Array
value = value.first
end
case key.to_s
when "email", "http://axschema.org/contact/email"
self.email = value
end
end
# If user already exists with that email, we just update that user instead
user = User.find_by_email(self.email)
if user.present?
user.update_attribute(:identity_url, self.identity_url)
# Overtake attributes from existing user, as we can't change self
self.id = user.id
else
# If we are a new user ...
if self.new_record?
# Make sure this is a myappsdomain.dk user - domain stored in the ApplicationSettings::GoogleApps::DOMAIN constant
if self.email.present? && self.email[ApplicationSettings::GoogleApps::DOMAIN.length*-1..-1] == ApplicationSettings::GoogleApps::DOMAIN
# Create this user
self.save!
else
# Don't allow this user to be created
self.email = nil
end
end
end
end
end
@leeadkins
Copy link
Author

The only modification I had to make was to the email parsing. The Google OpenID service was returning the email as an array, which threw off the domain checking logic at the end when creating a new entry. There are a few ways this could be handled, but for my purposes a simple check like this in the fields block:

if value.is_a? Array

value = value.first

end

is all I need. This also ensures that only a real email address is saved rather than a serialized array of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment