Created
September 5, 2011 19:37
-
-
Save nu7hatch/1195740 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AuthProvider | |
include Mongoid::Document | |
field :provider, :type => String | |
field :uid, :type => String | |
belongs_to :user, :class_name => "User", :inverse_of => :providers | |
validates :uid, :presence => true, :uniqueness => { :scope => :provider } | |
validates :provider, :presence => true | |
def self.find_by_oauth(hash) | |
where(:provider => hash["provider"], :uid => hash["uid"]).first | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
include Mongoid::Paranoia | |
field :name, :type => String | |
field :email, :type => String | |
field :admin, :type => Boolean, :default => false | |
# Auth stuff | |
embeds_one :credentials, :class_name => "AuthCredential", :invese_of => :user | |
has_many :providers, :class_name => "AuthProvider", :inverse_of => :user | |
validates :email, :uniqueness => true, :email => true | |
validates :name, :presence => true | |
def self.create_admin!(attrs) | |
create!(attrs.merge(:admin => true)) | |
end | |
def self.find_or_create_by_oauth(hash) | |
if auth = AuthProvider.find_by_oauth(hash) | |
return auth.user | |
else | |
user = new | |
if hash["user_info"] # Twitter, ... | |
user.name, user.email = hash["user_info"].values_at("name", "email") | |
elsif hash["extra"] # Facebook | |
user.name, user.email = hash["extra"]["user_hash"].values_at("name", "email") | |
end | |
if user.save(:validate => false) | |
auth = user.providers.build(:provider => hash["provider"], :uid => hash["uid"]) | |
auth.save | |
return user | |
end | |
end | |
end | |
end # User |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment