Class: GitFit::Auth::Strava

Inherits:
Object
  • Object
show all
Defined in:
lib/git_fit/auth/strava.rb

Overview

Strava OAuth2 interactive flow. Ported from workouts-cli (lib/workouts/auth/strava.rb).

Starts a loopback WEBrick server, prints an auth URL for the user to open, exchanges the returned code for a refresh_token, and writes it into sync.strava.refresh_token in the config file.

Constant Summary collapse

STATUS_COLORS =
{ done: 32, warn: 33, error: 31, auth: 36 }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(cli_options, config) ⇒ Strava

Returns a new instance of Strava.



21
22
23
24
# File 'lib/git_fit/auth/strava.rb', line 21

def initialize(cli_options, config)
  @options = cli_options
  @config = config
end

Instance Method Details

#callObject

Faithful port of workouts Auth::Strava#call — full loopback server lifecycle, inherently large surface area. rubocop:disable Metrics/AbcSize, Metrics/MethodLength



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/git_fit/auth/strava.rb', line 29

def call
  strava_cfg = @config.sync_config('strava')
  client_id = strava_cfg['client_id'].to_s
  client_secret = strava_cfg['client_secret'].to_s
  creds_missing = client_id.empty? || client_secret.empty?

  puts "\e[33m⚠  Strava API credentials not configured — see browser page\e[0m" if creds_missing

  port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] }
  redirect_uri = "http://localhost:#{port}/callback"

  code = nil
  exchange_error = nil
  tokens = nil

  log_file = File.open(File::NULL, 'w')
  server = WEBrick::HTTPServer.new(
    Port: port, Logger: WEBrick::Log.new(log_file),
    AccessLog: [[log_file, '']]
  )

  server.mount_proc '/' do |_req, res|
    fresh = load_fresh_config
    scfg = fresh.dig('sync', 'strava') || {}
    has_creds = scfg['client_id'].to_s != '' && scfg['client_secret'].to_s != ''

    if has_creds
      auth_url = "https://www.strava.com/oauth/authorize?#{URI.encode_www_form(
        client_id: scfg['client_id'], redirect_uri: redirect_uri,
        response_type: 'code', approval_prompt: 'force',
        scope: 'read_all,profile:read_all,activity:read_all'
      )}"
      res.body = success_html(auth_url)
    else
      res.body = config_page_html
    end
  end

  server.mount_proc '/callback' do |req, res|
    fresh = load_fresh_config
    scfg = fresh.dig('sync', 'strava') || {}
    cid = scfg['client_id'].to_s
    csec = scfg['client_secret'].to_s

    code = req.query['code']
    if code && !cid.empty? && !csec.empty? && !code.empty?
      begin
        resp = Faraday.post('https://www.strava.com/oauth/token') do |r|
          r.body = { client_id: cid, client_secret: csec, code: code, grant_type: 'authorization_code' }
        end
        if resp.success?
          tokens = JSON.parse(resp.body)
          rt = tokens['refresh_token']

          cfg = load_fresh_config
          cfg['sync'] ||= {}
          cfg['sync']['strava'] ||= {}
          cfg['sync']['strava']['client_id'] ||= cid
          cfg['sync']['strava']['client_secret'] ||= csec
          cfg['sync']['strava']['refresh_token'] = rt
          File.write(config_path, YAML.dump(cfg))

          puts "\e[32m✓ Strava authorization successful\e[0m"
        else
          exchange_error = "Token exchange failed: HTTP #{resp.status}"
        end
      rescue StandardError => e
        exchange_error = e.message
      end
    else
      exchange_error = 'No authorization code received'
    end

    if tokens
      repo = `git remote get-url origin 2>/dev/null`.strip.sub(%r{.*github\.com[/:]}, '').sub(/\.git$/, '')
      gh_url = repo.empty? ? 'https://github.com' : "https://github.com/#{repo}/settings/secrets/actions"
      rt = tokens['refresh_token']
      res.body = result_html(cid, csec, rt, gh_url, config_path)
    else
      err = exchange_error || 'Unknown error'
      res.body = "<html><body><h1>#{err}</h1><p>Please close and try again.</p></body></html>"
    end
  end

  server.mount_proc '/shutdown' do |_req, res|
    res.body = '<html><body><h1>Server closed</h1><p>You may close this window.</p></body></html>'
    server.shutdown
  end

  Thread.new { server.start }
  puts "\e[36m🔗  Open in your browser:\e[0m"
  puts "  http://localhost:#{port}"

  begin
    sleep 0.1 while server.status == :Running
  rescue Interrupt
    puts "\e[33m⚠  Server stopped by user\e[0m"
  end

  if exchange_error
    puts "\e[31m✗ #{exchange_error}\e[0m"
    return
  end

  return unless tokens

  rt = tokens['refresh_token']
  puts "\e[32m✓ Done\e[0m"
  puts ''
  puts 'GitHub Actions Secrets:'
  puts "  SYNC_STRAVA_CLIENT_ID = #{client_id}"
  puts "  SYNC_STRAVA_CLIENT_SECRET = #{client_secret}"
  puts "  SYNC_STRAVA_REFRESH_TOKEN = #{rt}"
  puts ''
  puts 'Local config:'
  puts '  strava:'
  puts "    refresh_token: #{rt}"
end