为什么更新用户时current_user会话变为nil? [英] Why does current_user session become nil when updating a user?
问题描述
我正在使用Devise和CanCan进行用户身份验证和管理角色,以限制某些用户对我的Rails 4应用程序的访问。
I'm using Devise and CanCan for user authentication and administrating roles restricting access to parts of my Rails 4 app for certain users.
我遇到了一些问题更新用户的问题。该更新工作正常,并且数据库中的用户对象得到了应有的更新,但是在以下用户显示操作 redirect_to
中,我的用户会话丢失了。 current_user
变为 nil
,这意味着CanCan限制了对用户show动作的访问。
I've run into some problems with updating a user. The update works fine and the user object in the db get updated as it should, but my user session is lost on the following redirect_to
my user show action. current_user
becomes nil
which means that CanCan restricts the access to the user show action.
为什么 current_user
在更新后变成 nil
,而在其他操作上却没有发生(例如创建,销毁等)?
Why does current_user
become nil
after update, when this does not happen on other actions (e.g create, destroy etc.)?
这些是我的用户模型中的设计设置:
These are the devise settings in my user model:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
这是我的users_controller.rb的更新方法:
This is my users_controller.rb's update method:
class UsersController < ApplicationController
load_and_authorize_resource
before_filter :authenticate_user!
def update
@user = User.find(params[:id])
if params[:user][:password].blank?
params[:user].delete(:password)
end
respond_to do |format|
if @user.update_attributes(user_params)
format.html { redirect_to user_path, :notice => 'User was successfully updated.' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @user.errors, :status => :unprocessable_entity }
end
end
end
end
这是我的ability.rb文件:
And this is my ability.rb file:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if defined?(user.role_id)
if user.role? :admin, user.role_id
can :manage, :all
elsif user.role? :hauler, user.role_id
can :manage, [User,Trip,Invoice], user_id: user.id.to_s
else
can :create, :Trip
end
end
end
end
推荐答案
这取决于正在执行的更新。会话使用用户数据的某些位进行序列化。
It depends on the update being performed. Sessions are serialized with certain bits of user data.
例如,更新密码将导致会话无效,因为加密的密码是序列化哈希的一部分,如果更改,会话将不再引用原始的加密密码。
For instance updating the password will cause a session to be nullified because the encrypted password is part of the serialized hash, and if that is changed, the session can no longer reference the original encrypted password.
这篇关于为什么更新用户时current_user会话变为nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!