Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Omniauthable
- extend ActiveSupport::Concern
- included do
- def self.find_for_oauth(auth)
- authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first
- return authorization.user if authorization
- if auth.info.try(:email)
- email = auth.info[:email]
- else
- return false
- end
- user = User.where(email: email).first
- if user
- user.create_authorization(auth)
- else
- password = Devise.friendly_token[0, 20]
- user = User.new(email: email,
- password: password,
- password_confirmation: password)
- if user.valid?
- user.save!
- user.create_authorization(auth)
- else
- return false
- end
- end
- user
- end
- def create_authorization(auth)
- authorizations.create(provider: auth.provider, uid: auth.uid)
- end
- end
- end
- module Omniauthable
- extend ActiveSupport::Concern
- included do
- def self.find_for_oauth(auth)
- authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first
- if authorization
- authorization.user
- else
- @email = auth.info.try(:email)
- find_user # ищем пользователя
- create_user unless @user # если не находим, то создаем
- auth_user(auth) # пытаемся авторизовать и возвращаем либо nil либо пользователя
- end
- end
- def create_authorization(auth)
- authorizations.create(provider: auth.provider, uid: auth.uid)
- end
- private # скрываем служебные методы
- def self.find_user
- @user = User.where(email: @email).first if @email
- end
- def self.create_user
- password = Devise.friendly_token[0, 20]
- udata = {
- email: @email,
- password: password,
- password_confirmation: password
- }
- user = User.create(udata) # здесь происходит валидация и сохранение
- @user = user if user.errors.count == 0 # если после создания нет ошибок, то объявляем переменную экземпляра
- end
- def self.auth_user(auth)
- if @user # если в предыдущих методах был найден/создан пользователь, если @user = nil(не существует, то nil вернется из метода)
- @user.create_authorization(auth)
- @user
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement