module Raddar class OmniauthCompletion def self.complete(auth_data, current_user = nil) user = User.new(password: Devise.friendly_token[0,20]) provider = auth_data[:provider] account = ExternalAccount.find_by(provider: provider, uid: auth_data[:uid]) if current_user.present? if account.present? if account.user != current_user raise 'Another user already owns this account.' end else create_account_for(current_user, auth_data) end user = current_user elsif account.present? user = account.user elsif auth_data[:info][:email].present? user_with_the_given_email = User.find_by(email: auth_data[:info][:email]) if user_with_the_given_email.present? create_account_for(user_with_the_given_email, auth_data) user = user_with_the_given_email end end populate(user, auth_data) if user.valid? if user.new_record? user.confirm! user.save create_account_for(user, auth_data) else user.save end end user end private def self.create_account_for(user, auth_data) account = user.external_accounts.new account.provider = auth_data[:provider] account.token = auth_data[:credentials][:token] account.secret = auth_data[:credentials][:secret] account.verified = auth_data[:info][:verified] account.name = auth_data[:info][:nickname] account.uid = auth_data[:uid] account.email = auth_data[:info][:email] account.url = auth_data[:info][:urls][account.provider.titleize.to_sym] account.save! end def self.populate(user, auth_data) user.email = user.email.presence || auth_data[:info][:email] user.name ||= auth_data[:info][:nickname] user.bio ||= auth_data[:info][:description] user.location ||= auth_data[:info][:location] user.remote_avatar_url = auth_data[:info][:image] if user.avatar.blank? if auth_data[:provider] == 'facebook' fb_birthday = auth_data[:extra][:raw_info][:birthday] user.birthday ||= Date.strptime(fb_birthday, '%m/%d/%Y') if fb_birthday user.gender ||= auth_data[:extra][:raw_info][:gender] end end end end