BigW Consortium Gitlab

github_controller.rb 1.81 KB
Newer Older
1
class Import::GithubController < Import::BaseController
2 3
  before_action :verify_github_import_enabled
  before_action :github_auth, except: :callback
Valery Sizov committed
4 5

  rescue_from Octokit::Unauthorized, with: :github_unauthorized
6

Valery Sizov committed
7
  def callback
8
    session[:github_access_token] = client.get_token(params[:code])
9
    redirect_to status_import_github_url
Valery Sizov committed
10 11 12
  end

  def status
13
    @repos = client.repos
Valery Sizov committed
14 15 16
    @already_added_projects = current_user.created_projects.where(import_type: "github")
    already_added_projects_names = @already_added_projects.pluck(:import_source)

17
    @repos.reject!{ |repo| already_added_projects_names.include? repo.full_name }
Valery Sizov committed
18 19
  end

20
  def jobs
21
    jobs = current_user.created_projects.where(import_type: "github").to_json(only: [:id, :import_status])
22 23 24
    render json: jobs
  end

Valery Sizov committed
25 26
  def create
    @repo_id = params[:repo_id].to_i
27
    repo = client.repo(@repo_id)
28
    @project_name = repo.name
29 30 31 32

    repo_owner = repo.owner.login
    repo_owner = current_user.username if repo_owner == client.user.login
    @target_namespace = params[:new_namespace].presence || repo_owner
33

34
    namespace = get_or_create_namespace || (render and return)
Valery Sizov committed
35

36
    @project = Gitlab::GithubImport::ProjectCreator.new(repo, namespace, current_user, access_params).execute
Valery Sizov committed
37 38 39 40 41
  end

  private

  def client
42
    @client ||= Gitlab::GithubImport::Client.new(session[:github_access_token])
Valery Sizov committed
43 44
  end

45
  def verify_github_import_enabled
46
    render_404 unless github_import_enabled?
47 48
  end

Valery Sizov committed
49
  def github_auth
50
    if session[:github_access_token].blank?
Steven Burgart committed
51
      go_to_github_for_permissions
Valery Sizov committed
52 53 54
    end
  end

Steven Burgart committed
55
  def go_to_github_for_permissions
56
    redirect_to client.authorize_url(callback_import_github_url)
Valery Sizov committed
57 58 59
  end

  def github_unauthorized
Steven Burgart committed
60
    go_to_github_for_permissions
Valery Sizov committed
61
  end
62 63 64 65 66 67

  private

  def access_params
    { github_access_token: session[:github_access_token] }
  end
Valery Sizov committed
68
end