omniauth_callbacks_controller.rb 1.9 KB

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