Skip to content

Instantly share code, notes, and snippets.

@cfcosta
Forked from anonymous/gist:4462969
Last active December 10, 2015 16:48
Show Gist options
  • Save cfcosta/4462975 to your computer and use it in GitHub Desktop.
Save cfcosta/4462975 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
def self.create_from_omniauth_data(data)
user = new
user.external_provider = true
user.name = data['info']['email']
user.email = data['info']['email']
user.authorizations.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
user.save!
end
def self.find_or_create_by_omniauth(omniauth)
provider = omniauth.fetch('provider')
uid = omniauth.fetch('uid')
if authorization = Authorization.find_by_provider_and_uid(provider, uid)
self.find(authorization.user_id)
else
self.create_from_omniauth_data(omniauth)
end
end
end
def authenticate_and_redirect(user)
session[:user_id] = user.id
redirect_to root_url, alert: "Successfully logged in."
end
def create_by_provider
# It's the Omniauth callback, Twitter and Facebook sends you here after authorization.
omniauth = request.env["omniauth.auth"]
if not omniauth
redirect_to oops_url, alert: "We've found strange errors dealing with your external authentication, sorry."
return
end
@user = User.find_or_create_by_omniauth(omniauth)
authenticate_and_redirect(@user)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment