2
votes

I am using rails with devise token auth. i want to implement omniauth but it keeps me asking uninitialized constant user

routes.rb

  namespace :api, defaults: { format: :json } do
    scope :v1 do
      mount_devise_token_auth_for 'User', at: 'auth', controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
    end
  end

in app/controllers/api/v1/users/omniauth_callbacks_controller.rb

class OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController

  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
    else
      session["devise.google_data"] = request.env["omniauth.auth"]
    end
    redirect_to '/'
  end
end

i dont know where i am doing wrong. i have try all answer in google but not work

1

1 Answers

0
votes

Is it Users or User constant that is unitialized in the error message?

Let's cover both.


Users

In your routes.rb you specified controller path as 'users/omniauth_callbacks'. By convention this means your controller is called Users::OmniauthCallbacksController. Notice the Users scope.

Now you can either drop the 'users' part of the route and move the controller up a folder or create the controller inside Users scope.

class Users
  class OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController
    ...
  end
end


User

User is simply the model that is usually used to store devise data. Make sure you have one in your /app/models.

class User < ApplicationRecord
  devise :omniauthable, omniauth_providers: %i[google]
end