Skip to content

Instantly share code, notes, and snippets.

@kingcons
Last active August 29, 2015 14:16
Show Gist options
  • Save kingcons/5e6f84fe0a8e2b3eca77 to your computer and use it in GitHub Desktop.
Save kingcons/5e6f84fe0a8e2b3eca77 to your computer and use it in GitHub Desktop.
Spotify OAuth Notes

Spotify OAuth Integration

If you have questions, I will be happy to expand these notes. Note that you need to add the httparty gem to your Gemfile for this code to work! You may also want to get RSpotify to handle this for you! Instructions for trying that are in their README here. I haven't used it before but am more than happy to help debug issues!

Supporting OAuth requires storing Access Tokens, Refresh Tokens, and Expiration Times on the User model. I have not included migrations for that in this code. You can see I assume column names of access_token, refresh_token, and expires_at but feel free to change those names. As you can see, I have added changes to the Users and Songs controllers and User model to support OAuth.

Creating Playlists once you have Tokens

Forthcoming

def share
if !current_user.access_token
redirect_to build_auth_link
elsif current_user.token_expired?
current_user.refresh!
end
@playlist = Playlist.find(params[:id])
@playlist.share!(current_user)
end
private
def build_auth_link
auth_opts = {
:client_id => ENV["SPOTIFY_CLIENT_ID"],
:response_type => 'code',
:redirect_uri => my_new_token_path(current_user),
:scope => 'playlist-modify playlist-modify-public playlist-modify-private'
}.to_query
"https://accounts.spotify.com/authorize?" + auth_opts
end
def token?
access_token && !token_expired?
end
def token_expired?
Time.now > expires_at
end
def refresh!
token_opts = {
:client_id => ENV["SPOTIFY_CLIENT_ID"],
:client_secret => ENV["SPOTIFY_CLIENT_SECRET"],
:grant_type => 'refresh_token',
:refresh_token => self.refresh_token
}
response = HTTParty.post("https://accounts.spotify.com/api/token",
:body => token_opts)
self.update(:access_token => response[:access_token],
:expires_at => Time.now + response[:expires_in])
end
def get_token!(auth_code)
token_opts = {
:client_id => ENV["SPOTIFY_CLIENT_ID"],
:client_secret => ENV["SPOTIFY_CLIENT_SECRET"],
:grant_type => 'authorization_code',
:code => auth_code,
:redirect_uri => my_new_token_path(self)
}
response = HTTParty.post("https://accounts.spotify.com/api/token",
:body => token_opts)
self.update(:access_token => response[:access_token],
:refresh_token => response[:refresh_token],
:expires_at => Time.now + response[:expires_in])
end
def update_token
if params[:code]
current_user.get_token!(params[:code])
flash[:notice] = "Now that we're authenticated, you can share that playlist!"
redirect_to playlists_path # the playlist index page, perhaps.
else
flash[:alert] = "Cannot share playlist without spotify account access."
redirect_to :root
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment