Module: Exportify::Auth

Defined in:
lib/exportify/auth.rb

Constant Summary collapse

TOKEN_FILE =
File.expand_path('~/.exportify_token.json')
REDIRECT_URI =
'http://127.0.0.1:8888/callback'
SCOPES =
'playlist-read-private playlist-read-collaborative'

Class Method Summary collapse

Class Method Details

.access_tokenObject



107
108
109
110
111
112
113
114
115
# File 'lib/exportify/auth.rb', line 107

def access_token
  token = load_token
  if token.nil?
    token = authorize!
  elsif Time.now.to_i >= token['expires_at'].to_i - 60
    token = refresh_token(token)
  end
  token['access_token']
end

.authorize!Object



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
# File 'lib/exportify/auth.rb', line 75

def authorize!
  params = URI.encode_www_form(
    client_id: client_id,
    response_type: 'code',
    redirect_uri: REDIRECT_URI,
    scope: SCOPES
  )
  url = "https://accounts.spotify.com/authorize?#{params}"

  puts "\nAbrindo navegador para login no Spotify..."
  puts "Se não abrir automaticamente, acesse:\n#{url}\n"
  system("open '#{url}'")

  code   = nil
  server = WEBrick::HTTPServer.new(
    Port: 8888,
    BindAddress: '127.0.0.1',
    Logger: WEBrick::Log.new(File::NULL),
    AccessLog: []
  )
  server.mount_proc('/callback') do |req, res|
    code          = req.query['code']
    res.body      = '<html><body><h2>Login realizado! Pode fechar esta aba.</h2></body></html>'
    res['Content-Type'] = 'text/html'
    server.shutdown
  end
  server.start

  abort 'Login cancelado' unless code
  exchange_code(code)
end

.client_idObject



117
118
119
# File 'lib/exportify/auth.rb', line 117

def client_id
  ENV.fetch('SPOTIFY_CLIENT_ID', nil) || Config.load['spotify_client_id']
end

.client_secretObject



121
122
123
# File 'lib/exportify/auth.rb', line 121

def client_secret
  ENV.fetch('SPOTIFY_CLIENT_SECRET', nil) || Config.load['spotify_client_secret']
end

.exchange_code(code) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/exportify/auth.rb', line 46

def exchange_code(code)
  uri = URI('https://accounts.spotify.com/api/token')
  req = Net::HTTP::Post.new(uri)
  req['Authorization'] = "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"
  req.set_form_data(
    'grant_type' => 'authorization_code',
    'code' => code,
    'redirect_uri' => REDIRECT_URI
  )
  res  = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) }
  data = JSON.parse(res.body)
  handle_token_error!(data)
  save_token(data)
end

.handle_token_error!(data) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/exportify/auth.rb', line 61

def handle_token_error!(data)
  return unless data['error']

  case data['error']
  when 'invalid_client'
    abort 'Erro de autenticação: SPOTIFY_CLIENT_ID ou SPOTIFY_CLIENT_SECRET inválidos.'
  when 'invalid_grant'
    FileUtils.rm_f(TOKEN_FILE)
    abort "Sessão expirada ou revogada. Arquivo de token removido.\nExecute o comando novamente para fazer login."
  else
    abort "Erro ao obter token Spotify: #{data['error']}#{data['error_description']}"
  end
end

.load_tokenObject



25
26
27
28
29
# File 'lib/exportify/auth.rb', line 25

def load_token
  return nil unless File.exist?(TOKEN_FILE)

  JSON.parse(File.read(TOKEN_FILE))
end

.refresh_token(token_data) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/exportify/auth.rb', line 31

def refresh_token(token_data)
  uri = URI('https://accounts.spotify.com/api/token')
  req = Net::HTTP::Post.new(uri)
  req['Authorization'] = "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"
  req.set_form_data(
    'grant_type' => 'refresh_token',
    'refresh_token' => token_data['refresh_token']
  )
  res  = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) }
  data = JSON.parse(res.body)
  handle_token_error!(data)
  data['refresh_token'] ||= token_data['refresh_token']
  save_token(data)
end

.save_token(data) ⇒ Object



19
20
21
22
23
# File 'lib/exportify/auth.rb', line 19

def save_token(data)
  data['expires_at'] = Time.now.to_i + data['expires_in'].to_i
  File.write(TOKEN_FILE, JSON.generate(data))
  data
end