Skip to content

Commit aba356b

Browse files
Authorize each lesson in batch create with CanCan's authorize!
1 parent 80eb0fc commit aba356b

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

app/controllers/api/lessons/batch_controller.rb

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ class BatchController < ApiController
99
before_action :authorize_user
1010
before_action :verify_school_class_belongs_to_school
1111
before_action :verify_can_create_scratch_projects
12-
load_and_authorize_resource :lesson
12+
before_action :authorize_lesson_projects!
1313

1414
def create_batch
1515
raise ParameterError, 'lesson_projects cannot be blank' unless lesson_projects?
1616

1717
@results = Lesson::CreateBatch.call(
18-
lessons_params: params[:lesson_projects].map { |entry| create_batch_params(entry) }
18+
lessons_params: batch_lessons_params
1919
)
2020
@user = current_user
2121
render :create_batch, formats: [:json], status: :created
@@ -38,6 +38,10 @@ def verify_can_create_scratch_projects
3838
verify_lesson_scratch!(scratch_project_params)
3939
end
4040

41+
def batch_lessons_params
42+
@batch_lessons_params ||= params[:lesson_projects].map { |lesson_params| create_batch_params(lesson_params) }
43+
end
44+
4145
def create_batch_params(lesson_project)
4246
lesson_project.permit(*LESSON_ATTRIBUTES, :origin_identifier, project_attributes: PROJECT_ATTRIBUTES).merge(user_id: current_user.id)
4347
end
@@ -48,6 +52,14 @@ def lesson_projects?
4852

4953
projects.any?(&:present?)
5054
end
55+
56+
def authorize_lesson_projects!
57+
return unless lesson_projects?
58+
59+
batch_lessons_params.each do |lesson_params|
60+
authorize! :create, Lesson.new(lesson_params.slice(:school_id, :school_class_id, :user_id))
61+
end
62+
end
5163
end
5264
end
5365
end

spec/features/lesson/creating_a_batch_of_lessons_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,32 @@
157157
end
158158
end
159159

160+
context 'when the user does not belong to the school' do
161+
let(:other_school) { create(:school, scratch_enabled: true) }
162+
let(:lesson_project_params) do
163+
[
164+
{
165+
name: 'Lesson 1',
166+
school_id: other_school.id,
167+
project_attributes: { name: 'Project 1', project_type: Project::Types::CODE_EDITOR_SCRATCH }
168+
},
169+
{
170+
name: 'Lesson 2',
171+
school_id: other_school.id,
172+
project_attributes: { name: 'Project 2', project_type: Project::Types::CODE_EDITOR_SCRATCH }
173+
}
174+
]
175+
end
176+
177+
it 'responds 403 Forbidden' do
178+
expect(response).to have_http_status(:forbidden)
179+
end
180+
181+
it 'does not create any lessons' do
182+
expect(Lesson.count).to eq(0)
183+
end
184+
end
185+
160186
context 'when the school does not have Scratch enabled' do
161187
let(:scratch_enabled) { false }
162188

0 commit comments

Comments
 (0)