Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
- def facebook
- oauthorize "Facebook"
- end
- def twitter
- oauthorize "Twitter"
- end
- def passthru
- render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
- end
- private
- def oauthorize(kind)
- omniauth = request.env['omniauth.auth']
- @user = User.includes(:authentications).merge(Authentication.where(:provider => omniauth['provider'], :uid => omniauth['uid'])).first
- if @user # if user exists and has used this authentication before, update details and sign in
- @user.set_token_from_hash(provider_auth_hash(kind, omniauth), provider_user_hash(kind, omniauth))
- sign_in_and_redirect @user, :event => :authentication
- elsif current_user # if user exists then new authentication is being added - so update details and redirect to
- current_user.set_token_from_hash(provider_auth_hash(kind, omniauth), provider_user_hash(kind, omniauth))
- redirect_to edit_user_registration_url
- else # create new user and new authentication
- user = User.new
- user.password = Devise.friendly_token[0,20]
- user.authentications.build(provider_auth_hash(kind, omniauth))
- if user.save :validate => false # validate false handles cases where email not provided - such as Twitter
- sign_in_and_redirect(:user, user)
- else # validate false above makes it almost impossible to get here
- session["devise.#{kind.downcase}_data"] = provider_auth_hash(kind,omniauth).merge(provider_user_hash(kind,omniauth))
- redirect_to new_user_registration_url
- end
- end
- end
- def provider_auth_hash(provider, hash)
- # Create provider specific hash's to populate authentication record
- case provider
- when "Facebook"
- {
- :provider => hash['provider'],
- :uid => hash['uid'],
- :name => hash['extra']['user_hash']['name'],
- :link => hash['extra']['user_hash']['link'],
- :token => hash['credentials']['token'],
- :secret => nil
- }
- when "Twitter"
- {
- :provider => hash['provider'],
- :uid => hash['uid'],
- :name => hash['user_info']['nickname'],
- :link => hash['user_info']['urls']['Twitter'],
- :token => hash['credentials']['token'],
- :secret => hash['credentials']['secret']
- }
- end
- end
- def provider_user_hash(provider, hash)
- # Create provider specific hash's to populate user record if appropriate
- case provider
- when "Facebook"
- {
- :name => hash['extra']['user_hash']['name'],
- :email => hash['extra']['user_hash']['email']
- }
- when "Twitter"
- {
- :name => hash['user_info']['name']
- }
- end
- end
- end
Add Comment
Please, Sign In to add comment