omniauth_callbacks_controller.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. module Users
  2. class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  3. before_action :set_service
  4. before_action :set_user
  5. attr_reader :service, :user
  6. def facebook
  7. handle_auth "Facebook"
  8. end
  9. def twitter
  10. handle_auth "Twitter"
  11. end
  12. def github
  13. handle_auth "Github"
  14. end
  15. private
  16. def handle_auth(kind)
  17. if service.present?
  18. service.update(service_attrs)
  19. else
  20. user.services.create(service_attrs)
  21. end
  22. if user_signed_in?
  23. flash[:notice] = "Your #{kind} account was connected."
  24. redirect_to edit_user_registration_path
  25. else
  26. sign_in_and_redirect user, event: :authentication
  27. set_flash_message :notice, :success, kind: kind
  28. end
  29. end
  30. def auth
  31. request.env['omniauth.auth']
  32. end
  33. def set_service
  34. @service = Service.where(provider: auth.provider, uid: auth.uid).first
  35. end
  36. def set_user
  37. if user_signed_in?
  38. @user = current_user
  39. elsif service.present?
  40. @user = service.user
  41. elsif User.where(email: auth.info.email).any?
  42. # 5. User is logged out and they login to a new account which doesn't match their old one
  43. flash[:alert] = "An account with this email already exists. Please sign in with that account before connecting your #{auth.provider.titleize} account."
  44. redirect_to new_user_session_path
  45. else
  46. @user = create_user
  47. end
  48. end
  49. def service_attrs
  50. expires_at = auth.credentials.expires_at.present? ? Time.at(auth.credentials.expires_at) : nil
  51. {
  52. provider: auth.provider,
  53. uid: auth.uid,
  54. expires_at: expires_at,
  55. access_token: auth.credentials.token,
  56. access_token_secret: auth.credentials.secret,
  57. }
  58. end
  59. def create_user
  60. User.create(
  61. email: auth.info.email,
  62. #name: auth.info.name,
  63. password: Devise.friendly_token[0,20]
  64. )
  65. end
  66. end
  67. end