如何在注册后立即登录用户?

时间:2011-03-25 22:03:21

标签: ruby-on-rails ruby ruby-on-rails-3 authentication registration

我知道我应该把代码放在用户控制器的create动作中,但是我不确定应该放什么代码。我还假设它应该在我的会话控制器中调用create动作,但我又不知道如何...

顺便说一句,我在用户控制器的创建操作中尝试了render :template => 'sessions/create',但在注册时出现此错误:

Template is missing

Missing template sessions/create with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:rjs, :rhtml, :erb, :rxml, :builder]} in view paths "/rubyprograms/dreamstill/app/views", "/rubyprograms/dreamstill/vendor/plugins/facebox_render/app/views"

这都在我的应用程序控制器中:

protected 
  # Returns the currently logged in user or nil if there isn't one
  def current_user
    return unless session[:user_id]
    @current_user ||= User.find_by_id(session[:user_id]) 
  end


  # Make current_user available in templates as a helper
  helper_method :current_user

  # Filter method to enforce a login requirement
  # Apply as a before_filter on any controller you want to protect
  def authenticate
    logged_in? ? true : access_denied
  end

  # Predicate method to test for a logged in user    
  def logged_in?
    current_user.is_a? User
  end

  # Make logged_in? available in templates as a helper
  helper_method :logged_in?

  def access_denied
    respond_to do |format|
      format.html do
        flash[:alert] = "You must log in to peform this action."
        redirect_to root_path
      end

      format.js do
        render_to_facebox(:partial => 'sessions/login_box')
      end
    end
     false
  end

3 个答案:

答案 0 :(得分:5)

在你的控制器的某个地方,你有一些看起来像这样的东西:

user = User.new
# set attributes
user.save
render :template => 'sessions/create' # Probably based on your question

您需要做的就是将session更新为:

user = User.new
# set attributes
if(user.save)
   session[:user_id] = user.id
   # Send them somewhere useful
else
   # Handle the error
end

一旦设置session[:user_id],他们就会登录。

答案 1 :(得分:1)

技术上?

在您的控制器中,创建用户后,此代码:

@current_user = user

应该让你去(看起来你正在使用restful_authentication)。

现在,在没有验证他们的电子邮件地址/其他任何有争议的问题的情况下,自动登录用户是否是一个好主意。

答案 2 :(得分:0)

你似乎只是从Rails开始吧?我强烈建议您使用像Devise这样的宝石来处理您的用户注册。

但是,如果您坚持手动执行此操作,则只需创建一个会话变量来验证用户是否已登录。然后,您可以添加一个帮助器,如current_user,以便在用户会话显示他/她已登录时获取用户。

我看到你有一个会话控制器。您是否尝试使用restful_authentication?如果是这样,我再次强烈建议切换到Devise:)

旧代码使用RESTFUL AUTHENCEATION - 会话控制器

# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem

  # render new.erb.html
  def new
  end

  def create
    logout_keeping_session!
    user = User.authenticate(params[:login], params[:password])
    if user
      # Protects against session fixation attacks, causes request forgery
      # protection if user resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset_session
      self.current_user = user
      new_cookie_flag = (params[:remember_me] == "1")
      handle_remember_cookie! new_cookie_flag
      flash[:notice] = "Logged in successfully"
      redirect_to :controller=>'Town'
    else
      note_failed_signin
      @login       = params[:login]
      @remember_me = params[:remember_me]
      render :action => 'new'
    end
  end

  def destroy
    logout_killing_session!
    flash[:notice] = "You have been logged out."
    redirect_back_or_default('/')
  end

protected
  # Track failed login attempts
  def note_failed_signin
    flash[:error] = "Couldn't log you in as '#{params[:login]}'"
    logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
  end
end