Created
December 7, 2014 19:18
-
-
Save rigelstpierre/07d461911182e3cb3480 to your computer and use it in GitHub Desktop.
Spotify Auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def spotify | |
self.validate_spotify_auth_token if self.spotify_auth_token.present? | |
config = { | |
:access_token => self.spotify_auth_token, # initialize the client with an access token to perform authenticated calls | |
:raise_errors => true, # choose between returning false or raising a proper exception when API calls fails | |
# Connection properties | |
:retries => 0, # automatically retry a certain number of times before returning | |
:read_timeout => 10, # set longer read_timeout, default is 10 seconds | |
:write_timeout => 10, # set longer write_timeout, default is 10 seconds | |
:persistent => false # when true, make multiple requests calls using a single persistent connection. Use +close_connection+ method on the client to manually clean up sockets | |
} | |
@client ||= ::Spotify::Client.new(config) | |
end | |
def validate_spotify_auth_token | |
if Time.now > self.token_expires_at | |
encoded_auth = Base64.strict_encode64("#{ENV['SPOTIFY_CLIENT_ID']}:#{ENV['SPOTIFY_CLIENT_SECRET']}") | |
request = { :body => { "grant_type" => "refresh_token", "refresh_token" => self.spotify_refresh_token } , | |
:headers => { "Authorization" => "Basic #{encoded_auth}" } | |
} | |
response = HTTParty.post("https://accounts.spotify.com/api/token?refresh_token", request) | |
self.update(:spotify_auth_token => response["access_token"], :token_expires_at => Time.now + response["expires_in"]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment