根据文档,我实现了身份验证。这是我的application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
before_action :auth_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
private
def auth_user
current_user
if @current_user.nil?
flash[:notice] = "You need to be logged in to access this part of the site"
redirect_to root_path(url: request.url)
end
end
end
我正在使用这个“登录”链接
<%= link_to "Sign in with Google", "/auth/google_oauth2?url=#{@url}", id: "sign_in" %>
路线:get 'auth/:provider/callback', to: 'user_sessions#create'
控制器:
class UserSessionsController < ApplicationController
skip_before_filter :auth_user
def create
url = params[:url]
auth = env["omniauth.auth"]
if auth
user = User.from_omniauth(auth)
session[:user_id] = user.id
flash[:notice] = "Login Sucessful!"
redirect_to url
else
flash[:notice] = "error"
redirect_to root_path
end
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
end
现在,当我没有有效的会话尝试去时,localhost:3000/privileged
我被重定向到根 URL,登录链接是这样的:
http://localhost:3000/auth/google_oauth2?url=http://localhost:3000/privileged
但是,当我单击它时,我会成功登录,但随后会出现无法重定向到 nil 的错误。为什么要删除参数?或者有没有更好的方法在成功登录后将用户重定向到最初请求的 URL?