已删除用户尝试登录

时间:2013-06-19 11:17:10

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

当我测试我的rails应用程序并删除用户并尝试登录时,我得到了。无法找到auth_token = " ... "的用户。好的,我想我为用户创建了一个不再存在auth_token的cookie。

如果用户不再存在,我如何让我的应用程序删除cookie,以及我将该代码放在哪里?

会话控制器

 class SessionsController < ApplicationController
   def new
   end

   def create
    user = User.authenticate(params[:email].downcase, params[:password])
       if user
         if user.email_activation_token == true
           if params[:remember_me]
             cookies.permanent[:auth_token] = user.auth_token
           else
            cookies[:auth_token] = user.auth_token
           end
          redirect_to root_url, :notice => "Logged in!"
         else
           flash.now.alert = "You email has not yet been verified. Please click the link in your email." 
           render "new"
         end
      else
        flash.now.alert = "Invalid email or password"
        render "new"
      end
   end

   def destroy
     cookies.delete(:auth_token)
     redirect_to root_url, :notice => "Logged out!"
   end
 end

用户控制器

  def self.authenticate(email, password)
   user = find_by_email(email)
   if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
    user
   else  
    nil
  end
end

应用程序控制器

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user

  def handle_unverified_request
    sign_out
    super
  end


private
  def current_user
    @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
  end

  def admin_user
  redirect_to(root_path) unless current_user.admin?
  end
end

1 个答案:

答案 0 :(得分:2)

您无需从Cookie中删除。您正在使用find_by_auth_token!,如果找不到该用户,则会引发异常。如果您使用没有感叹号的find_by_auth_token,那么如果找不到用户身份验证令牌,则调用将返回nil,@current_user将为nil。