Why does the current_user session become null when updating the user?

I use Devise and CanCan to authenticate users and administer roles that restrict access to parts of my Rails 4 application to specific users.

I am having problems updating my user. The update works fine and the user object in db is updated as it should, but my user session is lost in the next redirect_to action of my user action. current_user becomes nil , which means that CanCan restricts access to user action.

Why does current_user become nil after updating, when it does not happen with other actions (for example, create, destroy, etc.)?

These are the device settings in my user model:

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

This is my users_controller.rb 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 

And this is my able.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 
+4
source share
2 answers

It depends on the update in progress. Sessions are serialized with specific bits of user data.

For example, updating a password will reset the session because the encrypted password is part of the serialized hash, and if it is changed, the session can no longer refer to the original encrypted password.

+4
source

Worked for me

 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 

Magic happens in: bypass => true

0
source

Source: https://habr.com/ru/post/1499396/


All Articles