Read about our upcoming Code of Conduct on this issue

gitlab_controller.rb 1.96 KB
Newer Older
Valery Sizov's avatar
Valery Sizov committed
1
class Import::GitlabController < Import::BaseController
2
3
  before_action :verify_gitlab_import_enabled
  before_action :gitlab_auth, except: :callback
Valery Sizov's avatar
Valery Sizov committed
4
5
6
7

  rescue_from OAuth2::Error, with: :gitlab_unauthorized

  def callback
8
    session[:gitlab_access_token] = client.get_token(params[:code], callback_import_gitlab_url)
9
    redirect_to status_import_gitlab_url
Valery Sizov's avatar
Valery Sizov committed
10
11
12
13
  end

  def status
    @repos = client.projects
14

15
    @already_added_projects = find_already_added_projects('gitlab')
Valery Sizov's avatar
Valery Sizov committed
16
17
    already_added_projects_names = @already_added_projects.pluck(:import_source)

18
    @repos = @repos.to_a.reject { |repo| already_added_projects_names.include? repo["path_with_namespace"] }
Valery Sizov's avatar
Valery Sizov committed
19
20
21
  end

  def jobs
22
    render json: find_jobs('gitlab')
Valery Sizov's avatar
Valery Sizov committed
23
24
25
  end

  def create
26
27
    repo = client.project(params[:repo_id].to_i)
    target_namespace = find_or_create_namespace(repo['namespace']['path'], client.user['username'])
Valery Sizov's avatar
Valery Sizov committed
28

29
30
31
32
33
34
35
36
    if current_user.can?(:create_projects, target_namespace)
      project = Gitlab::GitlabImport::ProjectCreator.new(repo, target_namespace, current_user, access_params).execute

      if project.persisted?
        render json: ProjectSerializer.new.represent(project)
      else
        render json: { errors: project.errors.full_messages }, status: :unprocessable_entity
      end
37
    else
38
      render json: { errors: 'This namespace has already been taken! Please choose another one.' }, status: :unprocessable_entity
39
    end
Valery Sizov's avatar
Valery Sizov committed
40
41
42
43
44
  end

  private

  def client
45
    @client ||= Gitlab::GitlabImport::Client.new(session[:gitlab_access_token])
Valery Sizov's avatar
Valery Sizov committed
46
47
  end

Douwe Maan's avatar
Douwe Maan committed
48
  def verify_gitlab_import_enabled
49
    render_404 unless gitlab_import_enabled?
Douwe Maan's avatar
Douwe Maan committed
50
51
  end

Valery Sizov's avatar
Valery Sizov committed
52
  def gitlab_auth
53
    if session[:gitlab_access_token].blank?
Valery Sizov's avatar
Valery Sizov committed
54
55
56
57
58
      go_to_gitlab_for_permissions
    end
  end

  def go_to_gitlab_for_permissions
59
    redirect_to client.authorize_url(callback_import_gitlab_url)
Valery Sizov's avatar
Valery Sizov committed
60
61
62
63
64
  end

  def gitlab_unauthorized
    go_to_gitlab_for_permissions
  end
65
66
67
68

  def access_params
    { gitlab_access_token: session[:gitlab_access_token] }
  end
Valery Sizov's avatar
Valery Sizov committed
69
end