Last active
August 29, 2015 13:57
-
-
Save chatman-media/9736300 to your computer and use it in GitHub Desktop.
Simple OAuth authorisation with multiply providers
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 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 |
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 Provider < ActiveRecord::Base | |
| validates_presence_of :uid, :name | |
| validates_uniqueness_of :uid, scope: :name | |
| belongs_to :user, dependent: :destroy | |
| end |
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 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 |
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 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