Last active
December 16, 2015 11:58
-
-
Save Najaf/5431024 to your computer and use it in GitHub Desktop.
Quick tip for implementing access control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# So your PicsController probably looks something like this: | |
class PicsController < ApplicationController | |
def update | |
@pic = Pic.find(params[:id]) | |
@pic.update_attributes(params[:pic]) | |
end | |
end | |
# You want to change that to this: | |
class PicsController < ApplicationController | |
def update | |
# This bit makes sure you can only update your own images | |
@pic = current_user.pics.find(params[:id]) | |
@pic.update_attributes(pic_params) | |
end | |
def show | |
@pic = current_user.pics.find(params[:id]) | |
# do rendering stuff | |
end | |
def edit | |
@pic = current_user.pics.find(params[:id]) | |
end | |
def destroy | |
current_user.pics.find(params[:id]).destroy | |
# redirect somewher useful | |
end | |
private | |
def pic_params | |
# This bit makes sure you whitelist parameters you send to the model | |
# The list of attributes here should contain as little as possible and | |
# almost *never* contain a user_id, for real yo. | |
params[:pic].slice(:title, :caption, :tags, :other, :stuff, :you, :are, :sure, :you, :want, :users, :to, :be, :able, :to, :edit) | |
end | |
end | |
# I'm making the following assumptions though: | |
# 1. That a User has_many Pics and a Pic belongs_to a User: | |
class User < ActiveRecord::Base | |
has_many :pics | |
end | |
class Pic < ActiveRecord::Base | |
belongs_to :user | |
end | |
# 2. That you have access to a `current_user` method from somewhere | |
# You get it for free if you're using devise, or you may have rolled | |
# your own in ApplicationController or somewhere | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment