Skip to content

Instantly share code, notes, and snippets.

@miio
Created October 16, 2012 15:38
Show Gist options
  • Save miio/3900033 to your computer and use it in GitHub Desktop.
Save miio/3900033 to your computer and use it in GitHub Desktop.
Devise and Omniauth test
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.timestamps
end
end
end
class CreateAuthentications < ActiveRecord::Migration
def change
create_table :authentications do |t|
t.integer :user_id
t.string :provider
t.string :uid
t.string :screen_name
t.string :access_token
t.string :access_secret
t.string :bio
t.string :image_url
t.string :web_url
t.string :last_tid
t.timestamps
end
add_index :authentications, :user_id
add_index :authentications, [:provider, :uid], unique: true
end
end
class Authentication < ActiveRecord::Base
belongs_to :user
attr_accessible :provider, :uid, :access_token, :access_secret, :screen_name, :bio, :image_url, :web_url, :last_tid
end
class AuthenticationsController < ApplicationController
def callback
omniauth = request.env['omniauth.auth']
@authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if @authentication
@user = @authentication.user
else
# New User
@user = User.new
end
@user.set_for_twitter omniauth
sign_in(:user, @user)
redirect_to root_url
end
end
devise_for :users, controllers: { sessions: "users/sessions", authentications: "authentications" } do
get '/users/sign_out', to: 'devise/sessions#destroy', as: :destroy_user_session
get '/sessions/new', to: 'index#index', as: :new_user_session
get '/users/auth/:provider/callback', to: 'authentications#callback'
end
class User < ActiveRecord::Base
has_many :authentications
devise :trackable, :omniauthable
def set_for_twitter omniauth
User.transaction do
twitter_lock = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'], lock: true)
if twitter_lock.nil?
self.authentications.build self.get_twitter_args(omniauth)
else
twitter_lock.update_attributes self.get_twitter_args(omniauth)
end
self.save!
end
end
def get_twitter_args omniauth
data = omniauth['extra']['raw_info']
{
provider: omniauth['provider'], uid: omniauth['uid'],
access_token: omniauth['credentials']['token'],
access_secret: omniauth['credentials']['secret'],
screen_name: data['screen_name'],
bio: data['description'],
image_url: data['profile_image_url'],
web_url: data['url'],
last_tid: nil
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment