Reputation: 125
i have a rails app with sorcery
everything work .
the problem is when edit a user like :
http://localhost:3000/users/1/edit
its work fine , but when i change the user id to 2 or 3 ..
i can update all users data
how can i restrict the edit page only if the current user is the one that logged in
here is my controller :
skip_before_action :require_login, only: [:new, :create, :show]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
auto_login(@user)
flash[:info] = "Welcome."
redirect_to root_url
else
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
Upvotes: 1
Views: 184
Reputation: 9495
There are (at least) two ways to do that. First and straightforward is detailed in another answer, fine-tune your controller.
A less obvious way is to create a singular resource and its own controller. In routes that could look like:
resource :profile, only: [:show, :edit, :update]
# generates:
# /profile (GET, PATCH, PUT)
# /profile/edit (GET)
Then create a controller that is responible solely for user's own profile and operates only on current_user
.
Yes, it's okay for one model to have multiple controllers, if your model should behave really differently in different parts of your app.
current_user
, all you need is ensure the user is logged in in the entire controller.Upvotes: 0
Reputation: 1534
you can also do something like this
before_action :edit_rights?, only: [:update, :edit]
private
def edit_rights?
@user = User.find(params[:id])
redirect_to(root_path) unless current_user == @user
end
you won't need @user = User.find(params[:id])
in both update
and edit
actions then
Upvotes: 1