1

我正在使用omniauth 来允许用户注册/登录。我正在尝试将其添加到我已经拥有的简单身份验证登录/注销系统之上。我没有使用设计。如何让使用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

这是第一个身份验证系统使用的 session_controller

class 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

这是我的 session_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

用户控制器

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
4

1 回答 1

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比使用另一个助手更容易。

于 2013-04-11T06:45:18.723 回答