Read about our upcoming Code of Conduct on this issue

projects_controller.rb 14 KB
Newer Older
1
2
# frozen_string_literal: true

Douwe Maan's avatar
Douwe Maan committed
3
class ProjectsController < Projects::ApplicationController
4
  include API::Helpers::RelatedResourcesHelpers
5
  include IssuableCollections
6
  include ExtractsPath
7
  include PreviewMarkdown
8
  include SendFileUpload
9
  include RecordUserLastActivity
10
  include ImportUrlParams
11

12
13
  prepend_before_action(only: [:show]) { authenticate_sessionless_user!(:rss) }

14
15
  around_action :allow_gitaly_ref_name_caching, only: [:index, :show]

16
  before_action :whitelist_query_limiting, only: [:create]
17
  before_action :authenticate_user!, except: [:index, :show, :activity, :refs, :resolve]
18
  before_action :redirect_git_extension, only: [:show]
19
20
  before_action :project, except: [:index, :new, :create, :resolve]
  before_action :repository, except: [:index, :new, :create, :resolve]
21
22
23
  before_action :assign_ref_vars, if: -> { action_name == 'show' && repo_exists? }
  before_action :tree,
    if: -> { action_name == 'show' && repo_exists? && project_view_files? }
24
  before_action :lfs_blob_ids, if: :show_blob_ids?, only: :show
25
  before_action :project_export_enabled, only: [:export, :download_export, :remove_export, :generate_new_export]
26
  before_action :present_project, only: [:edit]
27
  before_action :authorize_download_code!, only: [:refs]
gitlabhq's avatar
gitlabhq committed
28
29

  # Authorize
30
  before_action :authorize_admin_project!, only: [:edit, :update, :housekeeping, :download_export, :export, :remove_export, :generate_new_export]
31
  before_action :authorize_archive_project!, only: [:archive, :unarchive]
32
  before_action :event_filter, only: [:show, :activity]
gitlabhq's avatar
gitlabhq committed
33

34
35
36
  # Project Export Rate Limit
  before_action :export_rate_limit, only: [:export, :download_export, :generate_new_export]

Douwe Maan's avatar
Douwe Maan committed
37
  layout :determine_layout
38

39
  def index
40
    redirect_to(current_user ? root_path : explore_root_path)
41
42
  end

43
  # rubocop: disable CodeReuse/ActiveRecord
gitlabhq's avatar
gitlabhq committed
44
  def new
45
46
    @namespace = Namespace.find_by(id: params[:namespace_id]) if params[:namespace_id]
    return access_denied! if @namespace && !can?(current_user, :create_projects, @namespace)
47

48
    @project = Project.new(namespace_id: @namespace&.id)
gitlabhq's avatar
gitlabhq committed
49
  end
50
  # rubocop: enable CodeReuse/ActiveRecord
gitlabhq's avatar
gitlabhq committed
51
52

  def edit
53
    @badge_api_endpoint = expose_url(api_v4_projects_badges_path(id: @project.id))
54
    render_edit
gitlabhq's avatar
gitlabhq committed
55
56
57
  end

  def create
58
    @project = ::Projects::CreateService.new(current_user, project_params(attributes: project_params_create_attributes)).execute
gitlabhq's avatar
gitlabhq committed
59

60
    if @project.saved?
61
62
      cookies[:issue_board_welcome_hidden] = { path: project_path(@project), value: nil, expires: Time.at(0) }

Vinnie Okada's avatar
Vinnie Okada committed
63
      redirect_to(
64
        project_path(@project, custom_import_params),
65
        notice: _("Project '%{project_name}' was successfully created.") % { project_name: @project.name }
Vinnie Okada's avatar
Vinnie Okada committed
66
      )
67
    else
Eric Eastwood's avatar
Eric Eastwood committed
68
      render 'new', locals: { active_tab: active_new_project_tab }
gitlabhq's avatar
gitlabhq committed
69
70
    end
  end
gitlabhq's avatar
gitlabhq committed
71

gitlabhq's avatar
gitlabhq committed
72
  def update
73
    result = ::Projects::UpdateService.new(@project, current_user, project_params).execute
74

75
    # Refresh the repo in case anything changed
76
    @repository = @project.repository
77

gitlabhq's avatar
gitlabhq committed
78
    respond_to do |format|
79
      if result[:status] == :success
80
        flash[:notice] = _("Project '%{project_name}' was successfully updated.") % { project_name: @project.name }
81

Vinnie Okada's avatar
Vinnie Okada committed
82
        format.html do
83
          redirect_to(edit_project_path(@project, anchor: 'js-general-project-settings'))
Vinnie Okada's avatar
Vinnie Okada committed
84
        end
gitlabhq's avatar
gitlabhq committed
85
      else
86
        flash.now[:alert] = result[:message]
87

88
        format.html { render_edit }
gitlabhq's avatar
gitlabhq committed
89
      end
90
91

      format.js
gitlabhq's avatar
gitlabhq committed
92
    end
93
  end
94

95
  # rubocop: disable CodeReuse/ActiveRecord
96
  def transfer
97
98
    return access_denied! unless can?(current_user, :change_namespace, @project)

99
100
101
102
103
    namespace = Namespace.find_by(id: params[:new_namespace_id])
    ::Projects::TransferService.new(project, current_user).execute(namespace)

    if @project.errors[:new_namespace].present?
      flash[:alert] = @project.errors[:new_namespace].first
skv-headless's avatar
skv-headless committed
104
    end
gitlabhq's avatar
gitlabhq committed
105
  end
106
  # rubocop: enable CodeReuse/ActiveRecord
gitlabhq's avatar
gitlabhq committed
107

108
  def remove_fork
109
110
    return access_denied! unless can?(current_user, :remove_fork_project, @project)

Baldinof's avatar
Baldinof committed
111
    if ::Projects::UnlinkForkService.new(@project, current_user).execute
112
      flash[:notice] = _('The fork relationship has been removed.')
113
114
115
    end
  end

116
117
118
119
120
121
122
123
124
125
  def activity
    respond_to do |format|
      format.html
      format.json do
        load_events
        pager_json('events/_events', @events.count)
      end
    end
  end

gitlabhq's avatar
gitlabhq committed
126
  def show
127
    if @project.import_in_progress?
128
      redirect_to project_import_path(@project, custom_import_params)
129
130
131
      return
    end

132
    if @project.pending_delete?
133
      flash.now[:alert] = _("Project '%{project_name}' queued for deletion.") % { project_name: @project.name }
134
135
    end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
136
    respond_to do |format|
Nihad Abbasov's avatar
Nihad Abbasov committed
137
      format.html do
138
        @notification_setting = current_user.notification_settings_for(@project) if current_user
139
140
        @project = @project.present(current_user: current_user)

141
        render_landing_page
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
142
      end
143

144
145
      format.atom do
        load_events
146
        render layout: 'xml.atom'
147
      end
148
149
150
    end
  end

gitlabhq's avatar
gitlabhq committed
151
  def destroy
152
    return access_denied! unless can?(current_user, :remove_project, @project)
153

Stan Hu's avatar
Stan Hu committed
154
    ::Projects::DestroyService.new(@project, current_user, {}).async_execute
155
    flash[:notice] = _("Project '%{project_name}' is in the process of being deleted.") % { project_name: @project.full_name }
gitlabhq's avatar
gitlabhq committed
156

Lin Jen-Shin's avatar
Lin Jen-Shin committed
157
    redirect_to dashboard_projects_path, status: :found
158
  rescue Projects::DestroyService::DestroyError => ex
159
    redirect_to edit_project_path(@project), status: :found, alert: ex.message
gitlabhq's avatar
gitlabhq committed
160
  end
161

162
  def new_issuable_address
163
164
165
    return render_404 unless Gitlab::IncomingEmail.supports_issue_creation?

    current_user.reset_incoming_email_token!
166
    render json: { new_address: @project.new_issuable_address(current_user, params[:issuable_type]) }
167
168
  end

169
  def archive
170
    ::Projects::UpdateService.new(@project, current_user, archived: true).execute
171
172

    respond_to do |format|
173
      format.html { redirect_to project_path(@project) }
174
175
176
177
    end
  end

  def unarchive
178
    ::Projects::UpdateService.new(@project, current_user, archived: false).execute
179
180

    respond_to do |format|
181
      format.html { redirect_to project_path(@project) }
182
183
    end
  end
184
185

  def housekeeping
186
    ::Projects::HousekeepingService.new(@project, :gc).execute
187
188
189

    redirect_to(
      project_path(@project),
190
      notice: _("Housekeeping successfully started")
191
192
193
    )
  rescue ::Projects::HousekeepingService::LeaseTaken => ex
    redirect_to(
194
      edit_project_path(@project, anchor: 'js-project-advanced-settings'),
195
196
      alert: ex.to_s
    )
197
  end
198

199
  def export
200
    @project.add_export_job(current_user: current_user)
201
202

    redirect_to(
203
      edit_project_path(@project, anchor: 'js-export-project'),
204
      notice: _("Project export started. A download link will be sent by email.")
205
206
207
    )
  end

James Lopez's avatar
James Lopez committed
208
  def download_export
James Lopez's avatar
James Lopez committed
209
    if @project.export_file_exists?
210
      send_upload(@project.export_file, attachment: @project.export_file.filename)
James Lopez's avatar
James Lopez committed
211
    else
212
      redirect_to(
213
        edit_project_path(@project, anchor: 'js-export-project'),
214
        alert: _("Project export link has expired. Please generate a new export from your project settings.")
215
216
217
218
219
220
      )
    end
  end

  def remove_export
    if @project.remove_exports
221
      flash[:notice] = _("Project export has been deleted.")
222
    else
223
      flash[:alert] = _("Project export could not be deleted.")
224
    end
225

226
    redirect_to(edit_project_path(@project, anchor: 'js-export-project'))
227
228
229
230
231
  end

  def generate_new_export
    if @project.remove_exports
      export
232
233
    else
      redirect_to(
234
        edit_project_path(@project, anchor: 'js-export-project'),
235
        alert: _("Project export could not be deleted.")
236
      )
James Lopez's avatar
James Lopez committed
237
    end
James Lopez's avatar
James Lopez committed
238
239
  end

Ciro Santilli's avatar
Ciro Santilli committed
240
241
  def toggle_star
    current_user.toggle_star(@project)
242
    @project.reset
243
244

    render json: {
245
      star_count: @project.star_count
246
    }
Ciro Santilli's avatar
Ciro Santilli committed
247
248
  end

249
  # rubocop: disable CodeReuse/ActiveRecord
250
  def refs
251
252
253
254
255
    find_refs = params['find']

    find_branches = true
    find_tags = true
    find_commits = true
Luke "Jared" Bennett's avatar
Luke "Jared" Bennett committed
256
257

    unless find_refs.nil?
Douwe Maan's avatar
Douwe Maan committed
258
259
260
      find_branches = find_refs.include?('branches')
      find_tags = find_refs.include?('tags')
      find_commits = find_refs.include?('commits')
261
    end
262

263
264
265
    options = {}

    if find_branches
Douwe Maan's avatar
Douwe Maan committed
266
      branches = BranchesFinder.new(@repository, params).execute.take(100).map(&:name)
267
      options['Branches'] = branches
268
    end
269

Douwe Maan's avatar
Douwe Maan committed
270
271
    if find_tags && @repository.tag_count.nonzero?
      tags = TagsFinder.new(@repository, params).execute.take(100).map(&:name)
272

273
      options['Tags'] = tags
Phil Hughes's avatar
Phil Hughes committed
274
275
    end

276
    # If reference is commit id - we should add it to branch/tag selectbox
277
    ref = Addressable::URI.unescape(params[:ref])
Douwe Maan's avatar
Douwe Maan committed
278
    if find_commits && ref && options.flatten(2).exclude?(ref) && ref =~ /\A[0-9a-zA-Z]{6,52}\z/
279
      options['Commits'] = [ref]
280
281
282
283
    end

    render json: options.to_json
  end
284
  # rubocop: enable CodeReuse/ActiveRecord
285

286
287
288
289
290
291
292
293
294
295
296
297
  def resolve
    @project = Project.find(params[:id])

    if can?(current_user, :read_project, @project)
      redirect_to @project
    else
      render_404
    end
  end

  private

298
299
300
301
  def show_blob_ids?
    repo_exists? && project_view_files? && Feature.disabled?(:vue_file_list, @project)
  end

302
  # Render project landing depending of which features are available
303
  # So if page is not available in the list it renders the next page
304
305
306
  #
  # pages list order: repository readme, wiki home, issues list, customize workflow
  def render_landing_page
307
    if can?(current_user, :download_code, @project)
308
      return render 'projects/no_repo' unless @project.repository_exists?
309

310
311
      render 'projects/empty' if @project.empty_repo?
    else
312
      if can?(current_user, :read_wiki, @project)
313
314
        @project_wiki = @project.wiki
        @wiki_home = @project_wiki.find_page('home', params[:version_id])
315
      elsif @project.feature_available?(:issues, current_user)
316
        @issues = issuables_collection.page(params[:page])
317
        @collection_type = 'Issue'
318
        @issuable_meta_data = issuable_meta_data(@issues, @collection_type, current_user)
319
320
321
322
323
324
      end

      render :show
    end
  end

325
326
327
328
  def finder_type
    IssuesFinder
  end

Douwe Maan's avatar
Douwe Maan committed
329
330
331
332
333
334
335
336
  def determine_layout
    if [:new, :create].include?(action_name.to_sym)
      'application'
    elsif [:edit, :update].include?(action_name.to_sym)
      'project_settings'
    else
      'project'
    end
337
  end
338

339
  # rubocop: disable CodeReuse/ActiveRecord
340
  def load_events
341
342
343
344
345
    projects = Project.where(id: @project.id)

    @events = EventCollection
      .new(projects, offset: params[:offset].to_i, filter: event_filter)
      .to_a
346
347

    Events::RenderService.new(current_user).execute(@events, atom_request: request.format.atom?)
348
  end
349
  # rubocop: enable CodeReuse/ActiveRecord
350

Małgorzata Ksionek's avatar
Małgorzata Ksionek committed
351
  def project_params(attributes: [])
352
    params.require(:project)
Małgorzata Ksionek's avatar
Małgorzata Ksionek committed
353
      .permit(project_params_attributes + attributes)
354
      .merge(import_url_params)
355
  end
Felipe Artur's avatar
Felipe Artur committed
356

357
  def project_params_attributes
358
359
360
361
    [
      :avatar,
      :build_allow_git_fetch,
      :build_coverage_regex,
362
      :build_timeout_human_readable,
363
      :resolve_outdated_diff_discussions,
Felipe Artur's avatar
Felipe Artur committed
364
      :container_registry_enabled,
365
366
      :default_branch,
      :description,
367
      :emails_disabled,
368
      :external_authorization_classification_label,
369
370
371
372
373
374
      :import_url,
      :issues_tracker,
      :issues_tracker_id,
      :last_activity_at,
      :lfs_enabled,
      :name,
375
      :only_allow_merge_if_all_discussions_are_resolved,
376
      :only_allow_merge_if_pipeline_succeeds,
377
      :path,
378
      :printing_merge_request_link_enabled,
379
      :public_builds,
380
      :remove_source_branch_after_merge,
381
382
383
384
      :request_access_enabled,
      :runners_token,
      :tag_list,
      :visibility_level,
385
      :template_name,
386
      :template_project_id,
387
      :merge_method,
388
      :initialize_with_readme,
389
      :autoclose_referenced_issues,
390
391
392
393

      project_feature_attributes: %i[
        builds_access_level
        issues_access_level
394
        forking_access_level
395
396
397
398
        merge_requests_access_level
        repository_access_level
        snippets_access_level
        wiki_access_level
399
        pages_access_level
400
401
      ]
    ]
402
  end
403

404
  def project_params_create_attributes
Małgorzata Ksionek's avatar
Małgorzata Ksionek committed
405
    [:namespace_id]
406
407
  end

408
409
410
411
  def custom_import_params
    {}
  end

Eric Eastwood's avatar
Eric Eastwood committed
412
413
414
415
  def active_new_project_tab
    project_params[:import_url].present? ? 'import' : 'blank'
  end

416
  def repo_exists?
Jacob Vosmaer's avatar
Jacob Vosmaer committed
417
    project.repository_exists? && !project.empty_repo?
418
419
420
421
422

  rescue Gitlab::Git::Repository::NoRepository
    project.repository.expire_exists_cache

    false
423
424
  end

425
  def project_view_files?
426
427
428
429
430
    if current_user
      current_user.project_view == 'files'
    else
      project_view_files_allowed?
    end
431
432
  end

433
  # Override extract_ref from ExtractsPath, which returns the branch and file path
Douwe Maan's avatar
Douwe Maan committed
434
  # for the blob/tree, which in this case is just the root of the default branch.
435
436
437
438
439
440
  # This way we avoid to access the repository.ref_names.
  def extract_ref(_id)
    [get_id, '']
  end

  # Override get_id from ExtractsPath in this case is just the root of the default branch.
441
442
443
  def get_id
    project.repository.root_ref
  end
444
445
446
447

  def project_view_files_allowed?
    !project.empty_repo? && can?(current_user, :download_code, project)
  end
448
449
450
451
452

  def build_canonical_path(project)
    params[:namespace_id] = project.namespace.to_param
    params[:id] = project.to_param

blackst0ne's avatar
blackst0ne committed
453
    url_for(safe_params)
454
  end
455
456

  def project_export_enabled
457
    render_404 unless Gitlab::CurrentSettings.project_export_enabled?
458
  end
459
460
461
462
463
464
465

  def redirect_git_extension
    # Redirect from
    #   localhost/group/project.git
    # to
    #   localhost/group/project
    #
466
    redirect_to request.original_url.sub(%r{\.git/?\Z}, '') if params[:format] == 'git'
467
  end
468
469

  def whitelist_query_limiting
470
    Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-foss/issues/42440')
471
  end
472
473
474
475

  def present_project
    @project = @project.present(current_user: current_user)
  end
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490

  def export_rate_limit
    prefixed_action = "project_#{params[:action]}".to_sym

    if rate_limiter.throttled?(prefixed_action, scope: [current_user, prefixed_action, @project])
      rate_limiter.log_request(request, "#{prefixed_action}_request_limit".to_sym, current_user)

      flash[:alert] = _('This endpoint has been requested too many times. Try again later.')
      redirect_to edit_project_path(@project)
    end
  end

  def rate_limiter
    ::Gitlab::ApplicationRateLimiter
  end
491
492
493
494

  def render_edit
    render 'edit'
  end
gitlabhq's avatar
gitlabhq committed
495
end
496
497

ProjectsController.prepend_if_ee('EE::ProjectsController')