我正在使用omniauth来允许用户注册/登录。我正在尝试将这个添加到我已经拥有的简单身份验证登录/注销系统之上。我没有使用Devise。如何让使用omniauth登录的用户具有与当前定义相同的状态:signed_in_user?
我已经设置了大部分代码,除了我试图弄清楚如何让用户实际登录并在使用omniauth时显示他们的登录页面。
首先,这是omniauth authentications_controller,它似乎到目前为止工作
def create
omniauth = request.env['omniauth.auth']
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:success] = "Signed in successfully"
sign_in_and_redirect User.find(authentication.user_id)
elsif current_user
token = omniauth['credentials'].token
secret = omniauth['credentials'].secret
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => token, :secret => token_secret)
flash[:success] = "Authentication successful"
sign_in_and_redirect current_user
else
user = User.new
user.apply_omniauth(omniauth)
if user.save!
flash[:success] = "Account created"
sign_in_and_redirect User.find(user.id)
else
session[:omniauth] = omniauth.except('extra')
redirect_to '/signup'
end
end
end
这是第一个身份验证系统
使用的sessions_controllerclass SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to root_url
else
flash.now[:error] = "Invalid email/password combination"
render 'new'
end
end
def destroy
sign_out
redirect_to root_path
end
end
这是我的sessions_helper 模块SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
current_user = user
end
def sign_in_and_redirect(user)
#what should go here?#
end
Users_controller
Class UsersController < ApplicationController
before_filter :signed_in_user,
only: [:index, :edit, :update, :destroy]
before_filter :correct_user, only: [:edit, :update]
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "Welcome!"
redirect_to root_url
else
render 'new'
end
end
使用我当前的身份验证系统(不是omniauth),重定向到root_url会使登录用户转到'static_pages #home'
class StaticPagesController < ApplicationController
def home
if signed_in?
@post = current_user.posts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
答案 0 :(得分:1)
我会将sign_in
辅助函数移至ApplicationHelper
,以便您可以在SessionsController
以外的其他位置使用它们。
之后,它应该非常简单。
def sign_in_and_redirect user
sign_in user
redirect_to root_url # or wherever you want
end
甚至可以更容易地执行sign_in user and redirect_to root_url
而不是使用其他帮助程序。