2013-08-28 63 views
4

我正在使用Devise和CanCan進行用戶身份驗證和管理角色,限制某些用戶訪問部分Rails 4應用程序。更新用戶時,爲什麼current_user會話變爲零?

我遇到了更新用戶的一些問題。更新工作正常,數據庫中的用戶對象得到更新,但我的用戶會話在以下redirect_to我的用戶顯示操作中丟失。 current_user變成nil這意味着CanCan可以限制對用戶顯示操作的訪問。

爲什麼current_user在更新之後變成nil當這種情況不會發生在其他動作上(例如創建,銷燬等)?

這些都是我的用戶模型中的色器件設置:

devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login] 

這是我users_controller.rb的更新方法:

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文件:

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 

回答

4

這取決於正在執行的更新。會話是用特定位數的用戶數據序列化的。

例如,更新密碼會導致會話無效,因爲加密密碼是序列化哈希的一部分,如果更改了該密碼,會話將不能再引用原始加密密碼。

+0

感謝TRH。重定向工作正常,如果我更新用戶而不更新密碼。那麼根據你所說的話,如果他/她更改了密碼,我需要將用戶登錄回來,對嗎? – asprotte

+0

yes - 特別是'sign_in @user,:bypass => true' - 你可以在這裏看到更多信息:https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-編輯他們的密碼 – trh

+0

偉大的作品!謝謝trh! – asprotte

0

爲我工作

def update 

    respond_to do |format| 

     if @user.update(user_params) 

     sign_in(@user, :bypass=>true) 

     format.html { redirect_to @user, notice: 'User was successfully updated.' } 
     format.json { render :show, status: :ok, location: @user } 

     else 
     format.html { render :edit } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 

    end 

end 

魔術發生在:旁路=>真

相關問題