2013-06-19 52 views
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 
+0

你可以列出用户身份验证代码,其中auth_token用于身份验证吗? –

+0

^在编辑 –

+0

中增加了它,不是这个,而是在用户登录后用过User.find_by_auth_token的地方。 –

回答

2

您不需要从cookie中删除。您正在使用find_by_auth_token!如果找不到用户,将会引发异常。如果您使用find_by_auth_token而没有感叹号,则如果没有用户可以找到验证令牌,则该呼叫将返回零,并且@current_user将为零。

+0

哦,男人,作品谢谢! –

相关问题