Skip to content

Instantly share code, notes, and snippets.

@chatman-media
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save chatman-media/9736300 to your computer and use it in GitHub Desktop.

Select an option

Save chatman-media/9736300 to your computer and use it in GitHub Desktop.
Simple OAuth authorisation with multiply providers
class AuthService
def self.authorize(auth_data)
provider = Provider.find_or_create_by(name: auth_data['name'], uid: auth_data['uid'])
if provider.user.present?
provider.user
else
user = User.find_or_create_with_oauth(auth_data['info'])
provider.update(user: user)
user
end
end
end
class Provider < ActiveRecord::Base
validates_presence_of :uid, :name
validates_uniqueness_of :uid, scope: :name
belongs_to :user, dependent: :destroy
end
class SessionController < ApplicationController
def create
self.current_user = AuthService.authorize(safe_params)
render json: current_user
end
def destroy
self.current_user = nil
render json: { success: true }
end
private
def safe_params
params.require(:data).permit!
end
end
class User < ActiveRecord::Base
validates :name, presence: true
validates :email, presence: true, uniqueness: true
has_many :providers
def self.find_or_create_with_oauth(info)
cond = { email: info['email'] }
if User.where(cond).exists?
where(cond).first
else
create(cond.merge(name: info['name']))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment