When a new user signs up to my website they are redirected to a personal tutorial. This is currently working for users who sign up on the site. However, when a new user clicks "sign in with facebook" they are redirected to the wrong URL (The url they would get if they have signed in before that bypasses the tutorial). Can anyone help me set it up so new Facebook users are redirected to the tutorial and existing Facebook bypass it? (I have the omniauth-facebook gem installed)
Here is my code. Thanks for taking the time to look this over!
User.controller.rb
class UsersController < ApplicationController
before_action :require_signin, except: [:new, :create]
before_action :require_correct_user, only: [:show, :edit, :update, :image, :tutorial]
before_action :require_admin, only: [:index, :destroy]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to users_tutorial_url (@user)
else
render :new
end
end
def tutorial
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:id, :first_name, :last_name, :email, :born_in, :gender, :password, :password_confirmation)
end
def require_correct_user
@user = User.find(params[:id])
redirect_to products_url unless current_user? (@user)
end
end
Session.controller.rb
class SessionsController < ApplicationController
def new
end
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to(session[:intended_url] || filtered_products_path(:trending))
session[:intended_url] = nil
elsif
auth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
session[:user_id] = user.id
redirect_to(session[:intended_url] || filtered_products_path(:trending))
session[:intended_url] = nil
else
flash.now[:alert] = "Invalid email/password combination!"
render :new
end
end
def destroy
session[:user_id] = nil
redirect_to root_url
end
end
User.rb (User Model)
class User < ActiveRecord::Base
before_create { generate_token(:auth_token) }
def self.authenticate(email, password)
user = User.find_by(email: email)
user && user.authenticate(password)
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
def self.create_with_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.email = auth.info.email
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save(:validate => false)
end
end
end
omniauth.rb OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'Facebook Key ###', 'Facebook Secret ###'
end