Omniauth redirects back to signin page - ruby-on-rails

So I'm trying to integrate Google OAuth2 with devise in my app but after signing in and allowing access to the app I get redirected back to the sign in page for some reason. I'm using the following tutorial:
https://www.digitalocean.com/community/tutorials/how-to-configure-devise-and-omniauth-for-your-rails-application
Here are my files:
callbacks_controller.rb
class CallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
route.rb:
devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }
users.rb:
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
devise.rb:
config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], callback_url: ENV['GOOGLE_CALLBACK_URL']
What am I doing wrong? Thanks

Try this:
class ApplicationController < ActionController::Base
def after_sign_in_path_for(resource)
# return path you want to go to...
end
end

Related

Devise Wrong number of arguments (13 for 2) upon Omniauthable

Trying to follow this tutorial to implement Google Sign In With Devise into my rails app: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
Getting this error:
My routes:
devise_for :users, controllers: { sessions: 'users/sessions', registrations: 'users/registrations', omniauth_callbacks: 'users/omniauth_callbacks' }
Omniauthable controller: app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
#user = User.from_omniauth(request.env["omniauth.auth"])
puts #user
if #user.persisted?
sign_in_and_redirect #user
set_flash_message(:notice, :success, kind: "Google") if is_navigational_format?
else
puts "WENT INTO HERE---------"
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to root_path
end
end
def failure
redirect_to root_path
end
end
User.rb
class User < ApplicationRecord
devise :rememberable, :trackable,
:omniauthable, omniauth_providers: %i[google_oauth2]
# rubocop:disable Metrics/AbcSize
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
# user.password = Devise.friendly_token[0,20]
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.image_url = auth.info.image # assuming the user model has an image
end
end
end
I have identified the 13 arguments that the app is referring to, from the session dump:
warden.user.user.key: {"id"=>204, "uid"=>"*******", "first_name"=>"First name", "last_name"=>"last name", "provider"=>"google_oauth2", "image_url"=>"*****", "email"=>"***", "has_logged_in"=>false, "created_at"=>"2018-03-17T21:26:24.782Z", "updated_at"=>"2018-03-17T23:31:38.220Z", "admin"=>false}
But I don't know where this came from or how to solve it
Not sure what the issue was but after closing my browser, the problem was fixed. So it probably had something to do with my cache.

Login with Facebook when user is registered, Rails 5, Omniouth with Device

I have this User model:
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.fname = auth.info.name
user.skip_confirmation!
end
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] &&
session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"] if user.email.blank?
end
end
end
and this omniouth_callbacks_controller:
def facebook
#user = User.from_omniauth(request.env["omniauth.auth"])
#user.confirmed_at = Time.now
if #user.persisted?
sign_in_and_redirect #user, :event => :authentication
set_flash_message(:notice, :success, :kind => "Facebook") if
is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
Everything works, but if user is registered without Facebook and then try to login with Facebook, it is not logged, because there are user row in the table in the database.
I want if user is registered in the site without socials and login with Facebook, to do that and site profile to be connected with Facebook profile.
Is there Omniouth method builtin for this case ?
If not, how to do it ?

Using Devise and Omniauth, for facebook : Routing Error uninitialized constant OmniauthCallbacksController

I'm a newbie on rails, trying to get my login to work using devise gem and Omniauth, facebook from this tutorial Here I think the problem is in my routes.rb file but I can't spot it, can you spot it for me?
Here is my routes.rb file
Rails.application.routes.draw do
resources :requests
mount RailsAdmin::Engine => '/rabbit', as: 'rails_admin'
devise_for :users, class_name: 'FormUser', :controllers => { omniauth_callbacks: 'omniauth_callbacks',
registrations: 'registrations'}
#devise_for :users
devise_scope :user do
get '/users/auth/:provider/upgrade' => 'omniauth_callbacks#upgrade', as: :user_omniauth_upgrade
get '/users/auth/:provider/setup', :to => 'omniauth_callbacks#setup'
end
resources :listings do
resources :reviews, except: [:show, :index] do
put "upvote", to: "reviews#upvote"
put "downvote", to: "reviews#downvote"
resources :user
end
end
get 'pages/about'
get 'pages/how'
get 'pages/faqs'
get 'pages/contact'
get 'pages/privacy'
get 'pages/tos'
get 'pages/guidelines'
root 'listings#index'
resources :notifications do
collection do
post :mark_as_read
end
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
Here is my omniauth_callback_controller.rb
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def instagram
generic_callback( 'instagram' )
end
def facebook
generic_callback( 'facebook' )
end
def twitter
generic_callback( 'twitter' )
end
def google_oauth2
generic_callback( 'google_oauth2' )
end
def generic_callback( provider )
#identity = Identity.find_for_oauth env["omniauth.auth"]
#user = #identity.user || current_user
if #user.nil?
#user = User.create( email: #identity.email || "" )
#identity.update_attribute( :user_id, #user.id )
end
if #user.email.blank? && #identity.email
#user.update_attribute( :email, #identity.email)
end
if #user.persisted?
#identity.update_attribute( :user_id, #user.id )
# This is because we've created the user manually, and Device expects a
# FormUser class (with the validations)
#user = FormUser.find #user.id
sign_in_and_redirect #user, event: :authentication
set_flash_message(:notice, :success, kind: provider.capitalize) if is_navigational_format?
else
session["devise.#{provider}_data"] = env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
Rake routes
Here is my error
The file must be called omniauth_callbacks_controller.rb. Right now, it's called omniauth_callback_controller.rb.
i recently added facebook authentication in my app.This is how the code set up is..
my url was - my-localhost/users/auth/facebook
######in routes
devise_for :users,:controllers => {
:sessions => "users/sessions",
:registrations => "users/registrations",
:passwords => "users/passwords",
:confirmations => "users/confirmations",
omniauth_callbacks: 'users/omniauth_callbacks'
}
####in controllers/users/omniauth_callbacks_controller.rb
def facebook
logger.tagged("FACEBOOK LOGIN"){ logger.info "=====Login with facebook================"}
auth = request.env["omniauth.auth"]
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user ###, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
flash[:error] = "Unable to login from Facebook because of these errors:"
flash[:error] << "#{#user.errors.full_messages.to_sentence}"
flash[:error] << ".Kindly signup"
redirect_to new_user_registration_url
end
end
####in my user.rb
class << self
##============for facebook
def find_for_facebook_oauth(auth)
#facebook_user = where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.username = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
##using Koala gem to fetch address too
#graph = Koala::Facebook::API.new(auth.credentials.token,configatron.fb_app_secret)
##Check more permissions at https://developers.facebook.com/docs/facebook-login/permissions/v2.2
user_location = #graph.get_object("me?fields=first_name,last_name,email,location")
end
return #facebook_user
end
end
Hope it helps :)

Google+ Sign Up with Devise and Rails (google_oauth2)

I'm getting the following error when trying to sign in through google+ using the google_oauth2 gem.
undefined method `find_for_google_oauth2' for #<Class:0x007ff70a337148>
Here's the three files I've altered for sign up.
user.rb
def google_oauth2
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash.notice = "Signed in Through Google!"
sign_in_and_redirect user
else
session["devise.user_attributes"] = user.attributes
flash.notice = "You are almost Done! Please provide a password to finish setting up your account"
redirect_to new_user_registration_url
end
end
omniauth_callbacks_controller.rb
def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
and I've added config.omniauth :google_oauth2 in my devise.rb file.
routes.rb
devise_for :users, :controllers => { :registrations => "registrations", :sessions => "sessions", :omniauth_callbacks => "users/omniauth_callbacks" }
You are calling find_for_google_oauth2 from the omniauth_callbacks_controller, but you are using the wrong method name google_oauth2. You should replace google_oauth2 with find_for_google_oauth2.
And it seems like the code in user.rb is incorrect because it contains the controller code. Do you see it looks exactly the same like your controller code? :)
Correct code for user.rb
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:email => data["email"]).first
# Uncomment the section below if you want users to be created if they don't exist
# unless user
# user = User.create(name: data["name"],
# email: data["email"],
# password: Devise.friendly_token[0,20]
# )
# end
user
end
Read more here: https://github.com/zquestz/omniauth-google-oauth2#devise

Cookie Overflow with Twitter sign in

I've got he kind of error when I tried to sign in with twitter on my website.
ActionDispatch::Cookies::CookieOverflow in Users::OmniauthCallbacksController#twitter
ActionDispatch::Cookies::CookieOverflow
I can't find a solution, this is the code I use.
omniauth_callbacks_controller.rb
def twitter
#user = User.find_for_provider_oauth(request.env["omniauth.auth"], current_user)
if #user.persisted?
sign_in_and_redirect #user, :event => :authentication
set_flash_message(:notice, :success, :kind => "twitter") if is_navigational_format?
else
session["devise.twitter_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
devise.rb
require "omniauth-twitter"
config.omniauth :twitter, 'xxxxxxx', 'xxxxxxxxxxxk', :strategy_class => OmniAuth::Strategies::Twitter
user.rb
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
def self.find_for_provider_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(name:auth.extra.raw_info.name,
provider:auth.provider,
uid:auth.uid,
email:auth.info.email,
password:Devise.friendly_token[0,20],
invite_code:"42TXP"
)
end
user
Use: .except("extra")
session["devise.twitter_data"] = request.env["omniauth.auth"].except("extra")
It removes a big part from the cookie that is simply not needed.
It is what you put in the session in the else part of save
session["devise.twitter_data"] = request.env["omniauth.auth"]
It's probably too big for a cookie.
You should save that information somewhere else. Or don't keep it.
I recently had a similar problem after following the method in https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview, I hope this can help you.
In the OmniauthCallbacksController, instead of:
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
I use:
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"].provider, request.env["omniauth.auth"].uid, request.env["omniauth.auth"].extra.raw_info.name, request.env["omniauth.auth"].info.email, current_user)
In the user model :
def self.find_for_facebook_oauth(provider, uid, name, email, signed_in_resource=nil)
user = User.where(:provider => provider, :uid => uid).first
unless user
user = User.create(:name => name,
:provider => provider,
:uid => uid,
:email => email,
:password => Devise.friendly_token[0,20]
)
end
return user
end
Also in OmniauthCallbacksController make sure you avoid using request.env["omniauth.auth"], use request.env["omniauth.auth"].uid instead.

Resources