gitlab_controller.rb 1.81 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
    token = client.get_token(params[:code], callback_import_gitlab_url)
Valery Sizov's avatar
Valery Sizov committed
9
10
    current_user.gitlab_access_token = token
    current_user.save
11
    redirect_to status_import_gitlab_url
Valery Sizov's avatar
Valery Sizov committed
12
13
14
15
  end

  def status
    @repos = client.projects
16

Valery Sizov's avatar
Valery Sizov committed
17
18
19
    @already_added_projects = current_user.created_projects.where(import_type: "gitlab")
    already_added_projects_names = @already_added_projects.pluck(:import_source)

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

  def jobs
24
    jobs = current_user.created_projects.where(import_type: "gitlab").to_json(only: [:id, :import_status])
Valery Sizov's avatar
Valery Sizov committed
25
26
27
28
29
30
    render json: jobs
  end

  def create
    @repo_id = params[:repo_id].to_i
    repo = client.project(@repo_id)
Valery Sizov's avatar
Valery Sizov committed
31
    @project_name = repo["name"]
32
33
34
35

    repo_owner = repo["namespace"]["path"]
    repo_owner = current_user.username if repo_owner == client.user["username"]
    @target_namespace = params[:new_namespace].presence || repo_owner
36

Valery Sizov's avatar
Valery Sizov committed
37
    namespace = get_or_create_namespace || (render and return)
Valery Sizov's avatar
Valery Sizov committed
38
39
40
41
42
43
44
45
46
47

    @project = Gitlab::GitlabImport::ProjectCreator.new(repo, namespace, current_user).execute
  end

  private

  def client
    @client ||= Gitlab::GitlabImport::Client.new(current_user.gitlab_access_token)
  end

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

Valery Sizov's avatar
Valery Sizov committed
52
53
54
55
56
57
58
  def gitlab_auth
    if current_user.gitlab_access_token.blank?
      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
65
  end

  def gitlab_unauthorized
    go_to_gitlab_for_permissions
  end
end