Skip to content

Instantly share code, notes, and snippets.

@orafaelfragoso
Created August 1, 2014 03:41
Show Gist options
  • Save orafaelfragoso/39e01d96feb9ef2b1fed to your computer and use it in GitHub Desktop.
Save orafaelfragoso/39e01d96feb9ef2b1fed to your computer and use it in GitHub Desktop.
Omniauth Controller Example
class SessionsController < ApplicationController
skip_before_filter :verify_authenticity_token, only: :create
def create
# Find an identity here
identity_info = Identity.filter_auth_hash(auth_hash)
@identity = Identity.find_with_omniauth(identity_info)
if @identity.nil?
# If no identity was found, create a brand new one here
@identity = Identity.create_with_omniauth(identity_info)
else
@identity.update_oauth_token(identity_info)
end
if signed_in?
if @identity.member == current_user
# User is signed in so they are trying to link an identity with their
# account. But we found the identity and the user associated with it
# is the current user. So the identity is already associated with
# this user. So let's display an error message.
self.current_user = @identity.member
redirect_to members_path
else
# The identity is not associated with the current_user so lets
# associate the identity
@identity.member = current_user
@identity.save()
self.current_user = @identity.member
redirect_to members_path
end
else
if @identity.member.present?
# The identity we found had a user associated with it so let's
# just log them in here
self.current_user = @identity.member
redirect_to members_path
else
# No user associated with the identity so we need to create a new one
info = Member.filter_auth_hash(auth_hash)
@member = Member.create_with_omniauth(info)
if @member
# Associate the user with the identity
@identity.member_id = @member.id
@identity.save
self.current_user = @member
redirect_to members_path
else
redirect_to root_url
end
end
end
end
def destroy
self.current_user = nil
redirect_to root_url
end
protected
def auth_hash
request.env['omniauth.auth']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment