Advertisement
Guest User

Untitled

a guest
Apr 5th, 2017
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. User.rb
  2.  
  3. class User < ApplicationRecord
  4. include Storext.model
  5. devise :database_authenticatable, :registerable, :omniauthable,
  6. :recoverable, :rememberable, :trackable, :validatable
  7. validates :first_name, :last_name, :email, :experience_level,
  8. :goal_level, :theoretical_learner_level, presence: true
  9. mount_uploader :avatar, AvatarUploader
  10.  
  11. # Override devise method for Oauth
  12. def self.new_with_session(params, session)
  13. if session['devise.user_attributes']
  14. new(session['devise.user_attributes'].merge(session[:user_attributes])) do |user|
  15. user.attributes = params
  16. user.valid?
  17. end
  18. else
  19. super
  20. end
  21. end
  22.  
  23. def self.from_omniauth(auth)
  24. where(auth.slice(:provider, :uid).to_hash).first_or_create do |user|
  25. OauthUserGenerator.new(user: user, auth: auth).generate
  26. end
  27. end
  28.  
  29. # If sign in through Oauth, don't require password
  30. def password_required?
  31. super && provider.blank?
  32. end
  33.  
  34. # Don't require update with password if Oauth
  35. def update_with_password(params, *options)
  36. if encrypted_password.blank?
  37. update_attributes(params, *options)
  38. else
  39. super
  40. end
  41. end
  42. end
  43.  
  44. oauth_user_generator.rb
  45.  
  46. class OauthUserGenerator
  47. def initialize(user:, auth:)
  48. @user = user
  49. @auth = auth
  50. end
  51.  
  52. def generate
  53. @user.provider = @auth.provider
  54. @user.uid = @auth.uid
  55. @user.email = @auth.info.email
  56. @user.password = Devise.friendly_token[0, 20]
  57. @user.first_name = @auth.info.name.split[0]
  58. @user.last_name = @auth.info.name.split[1]
  59. @user.remote_avatar_url = @auth.info.image
  60. end
  61. end
  62.  
  63. omniauth_callbacks_controller.rb
  64.  
  65. class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  66. def omniauth_providers
  67. process_oauth(request.env['omniauth.auth'].merge(session.fetch(:user_attributes, {})))
  68. end
  69.  
  70. alias facebook omniauth_providers
  71. alias github omniauth_providers
  72.  
  73. private
  74.  
  75. def process_oauth(omniauth_params)
  76. user = User.from_omniauth(omniauth_params)
  77. if user.persisted?
  78. flash.notice = 'Signed in!'
  79. sign_in_and_redirect user
  80. else
  81. session['devise.user_attributes'] = user.attributes
  82. redirect_to new_user_email_registration_path
  83. end
  84. end
  85. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement