Created
August 1, 2014 03:41
-
-
Save orafaelfragoso/39e01d96feb9ef2b1fed to your computer and use it in GitHub Desktop.
Omniauth Controller Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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