当新用户注册我的网站时,他们会被重定向到个人教程。这目前适用于在网站上注册的用户。但是,当新用户点击"使用Facebook"它们会被重定向到错误的URL(如果他们在登录之前已经登录,那么他们会获得的URL会绕过教程)。任何人都可以帮我设置它,以便新的Facebook用户被重定向到教程和现有的Facebook绕过吗? (我安装了omniauth-facebook gem)
这是我的代码。感谢您抽出宝贵时间来看看这个!
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(用户模型)
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