Advertisement
Guest User

Untitled

a guest
Aug 31st, 2016
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. module Omniauthable
  2. extend ActiveSupport::Concern
  3. included do
  4. def self.find_for_oauth(auth)
  5. authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first
  6. return authorization.user if authorization
  7.  
  8. if auth.info.try(:email)
  9. email = auth.info[:email]
  10. else
  11. return false
  12. end
  13.  
  14. user = User.where(email: email).first
  15. if user
  16. user.create_authorization(auth)
  17. else
  18. password = Devise.friendly_token[0, 20]
  19. user = User.new(email: email,
  20. password: password,
  21. password_confirmation: password)
  22. if user.valid?
  23. user.save!
  24. user.create_authorization(auth)
  25. else
  26. return false
  27. end
  28. end
  29. user
  30. end
  31.  
  32. def create_authorization(auth)
  33. authorizations.create(provider: auth.provider, uid: auth.uid)
  34. end
  35. end
  36. end
  37.  
  38. module Omniauthable
  39. extend ActiveSupport::Concern
  40. included do
  41. def self.find_for_oauth(auth)
  42. authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first
  43. if authorization
  44. authorization.user
  45. else
  46. @email = auth.info.try(:email)
  47. find_user # ищем пользователя
  48. create_user unless @user # если не находим, то создаем
  49. auth_user(auth) # пытаемся авторизовать и возвращаем либо nil либо пользователя
  50. end
  51. end
  52.  
  53. def create_authorization(auth)
  54. authorizations.create(provider: auth.provider, uid: auth.uid)
  55. end
  56. private # скрываем служебные методы
  57.  
  58. def self.find_user
  59. @user = User.where(email: @email).first if @email
  60. end
  61.  
  62. def self.create_user
  63. password = Devise.friendly_token[0, 20]
  64. udata = {
  65. email: @email,
  66. password: password,
  67. password_confirmation: password
  68. }
  69. user = User.create(udata) # здесь происходит валидация и сохранение
  70. @user = user if user.errors.count == 0 # если после создания нет ошибок, то объявляем переменную экземпляра
  71. end
  72.  
  73. def self.auth_user(auth)
  74. if @user # если в предыдущих методах был найден/создан пользователь, если @user = nil(не существует, то nil вернется из метода)
  75. @user.create_authorization(auth)
  76. @user
  77. end
  78. end
  79. end
  80. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement