当我测试我的 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