omniauth_callbacks_controller.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # frozen_string_literal: true
  2. class OmniauthCallbacksController < ApplicationController
  3. include CookieBasedCsrf
  4. include UserAuthentication
  5. def create
  6. case params[:provider]
  7. when 'google_oauth2'
  8. google_oauth2
  9. when 'reddit'
  10. reddit
  11. when 'discord'
  12. discord
  13. else
  14. head :not_found
  15. end
  16. end
  17. private
  18. def google_oauth2
  19. @user = User.from_omniauth(request.env['omniauth.auth'])
  20. if @user.persisted?
  21. sign_in_and_redirect @user, event: :authentication
  22. else
  23. redirect_to new_user_registration_url
  24. end
  25. end
  26. def reddit
  27. @user = User.from_omniauth(request.env['omniauth.auth'])
  28. if @user.persisted?
  29. sign_in_and_redirect @user, event: :authentication
  30. else
  31. redirect_to new_user_registration_url
  32. end
  33. end
  34. def discord
  35. @user = User.from_omniauth(request.env['omniauth.auth'])
  36. if @user.persisted?
  37. sign_in_and_redirect @user, event: :authentication
  38. else
  39. redirect_to new_user_registration_url
  40. end
  41. end
  42. def sign_in_and_redirect(user, *_args)
  43. # TODO: Log event
  44. # TODO: Throw on unregistered/unknown user
  45. # Ensure we have a new CSRF token now that user is signed in
  46. cookies.delete(:_csrf_token)
  47. login(user)
  48. cookies['x-csrf-token'] = {
  49. value: form_authenticity_token,
  50. httponly: false,
  51. secure: !(Rails.env.development? || Rails.env.test?),
  52. }
  53. redirect_to root_path
  54. end
  55. # More info at:
  56. # https://github.com/plataformatec/devise#omniauth
  57. # GET|POST /resource/auth/twitter
  58. # def passthru
  59. # super
  60. # end
  61. # GET|POST /users/auth/twitter/callback
  62. # def failure
  63. # super
  64. # end
  65. # protected
  66. # The path used when OmniAuth fails
  67. # def after_omniauth_failure_path_for(scope)
  68. # super(scope)
  69. # end
  70. end