Search code examples
ruby-on-railsruby-on-rails-5.2ruby-on-rails-6

how to not let a user open any other users page?


In my app, when a user logins he/she is redirected to the users profile page. Say he/she is redirected to http://localhost:3000/users/1

If he/she replaces 1 with any other number I want them to redirect to there current profile no matter if users exits in the database or not

 class SessionsController < ApplicationController
  def new
  end

 def create
  user = User.find_by_email(params[:email])
  if user && user.authenticate(params[:password])
    log_in user
    redirect_to user
  else
    flash.now[:danger] = 'Invalid email/password combination'
    render 'new'
  end
end

 def destroy
  @current_user = nil
  reset_session
  redirect_to root_path
end

end

User Controller:

  class UsersController < ApplicationController
     before_action :logged_in_user, only: [:new, :show, :edit, :update]
     before_action :correct_user, only: [:new, :show, :edit, :update]


 def index
  @users = User.all
 end

 def new
   @user = User.new
 end

 def create
   @user = User.new(set_params)
  if @user.save
    redirect_to new_sessions_path
  else
    render 'new'
  end
end

 def show
   @user = User.find(params[:id])
   @posts = @user.posts
 end

 def edit
   @user = User.find(params[:id])
  end

def update
  @user = User.find(params[:id])
  if @user.update(update_params)
    redirect_to @user
  else
    render 'edit'
 end
end

private

def set_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
end

def update_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
end 

  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_url) unless current_user?(@user)
 end

 end

Currenty if user type in search bar localhost:3000/users/5 and user with id 5 does not exists in database it shows error

ActiveRecord::RecordNotFound in UsersController#show Couldn't find User with 'id'=3

but I want to simply redirect to currently logged in users profile page.

If users type in search bar localhost:3000/users/3 and user with this id exists in db , currenty it show an error that firefox is not able to process this request but i want it redirect to its default page i.e,,user's profile page.


Solution

  • Just change your UsersController#correct_user to catch ActiveRecord NotFound exception:

    class UsersController < ApplicationController
      ...
    
      def correct_user
        @user = User.find(params[:id])
        redirect_to(root_url) unless current_user?(@user)
      rescue ActiveRecord::RecordNotFound
        redirect_to(root_url)
      end
    
    end