Sorcery Gem - Custom user_info_mapping for external providers

I am using NoamB Sorcery Authentication Gem version 0.7.7 on my Rails 3.2 App

I am looking for an opportunity, how can I connect a method that compares user information for a specific external login provider (eg facebook, twitter) .

For example, I want to change the provided locale to the format that I use in my database, or I want to upload a user avatar from twitter as part of the mapping process.

By default, this is only possible in the sorcery.rb file:

 config.facebook.user_info_mapping = {:email => "email", :first_name => "first_name", :last_name => "last_name" ... 

I know that I can achieve this behavior using setter methods in my user model, but I want these things to be separate from the model, and I want them to be able to define them specifically for each provider.

Is it possible? / What is the best way to implement such advanced matching options?

Thank you for your help!

+8
authentication ruby ruby-on-rails devise sorcery
source share
1 answer

It looks like you could do this by expanding the various classes of Sorcery providers to add application-specific fields for a hash of user information.

For example, to use Twitter, you might have something like this:

 config.external_providers = [:twitter] 

You can change this to:

 config.external_providers = [:TwitterWithAvatar] 

Now you need to define the TwitterWithAvatar provider in the Sorcery::Providers section and override the #get_user_hash method:

 module Sorcery module Providers class TwitterWithAvatar < Twitter def get_user_hash(access_token) user_hash = super user_hash.merge( avatar: get_avatar(user_hash[:uid]), ) end private def get_avatar(uid) # Some Twitter API call end end end end 

Now you can configure your mapping:

 config.TwitterWithAvatar.user_info_mapping = {avatar: "avatar"} 

Alternatively, since you are already using a custom provider class, you can transfer your mapping to this class:

 module Sorcery module Providers class TwitterWithAvatar < Twitter def user_info_mapping { avatar: "avatar", # ... } end end end end 

(I have not tried using this code, so the details may be a bit off, but reading the Sorcery source code, it looks like the right direction.)

0
source share

All Articles