spot2txt

Export Spotify Playlist Listings as Plaintext
git clone git://git.alexkarle.com.com/spot2txt
Log | Files | Refs | README

commit e3e64330f1fa44f51ef3f87cb4a99c4a75410432 (patch)
parent 3226d36fed370323ae8ca12f71a9db552e79bf60
Author: Alex Karle <alex@alexkarle.com>
Date:   Tue,  4 Feb 2025 20:20:08 -0500

Add auth flow up until access token

Diffstat:
Mspotilist.pl | 34++++++++++++++++++++++++++++++++--
1 file changed, 32 insertions(+), 2 deletions(-)

diff --git a/spotilist.pl b/spotilist.pl @@ -3,6 +3,9 @@ use strict; use warnings; use Mojolicious::Lite; +use LWP::UserAgent; +use MIME::Base64; +use JSON::PP; my $CLIENT_ID = $ENV{SPOTIFY_CLIENT_ID}; my $CLIENT_SECRET = $ENV{SPOTIFY_CLIENT_SECRET}; @@ -14,7 +17,7 @@ my $AUTH_URL = "https://accounts.spotify.com/authorize" . "?client_id=$CLIENT_ID" . "&response_type=code" . "&redirect_uri=http://localhost:3000/auth" - . "&scope=playlist-read-private&playlist-read-collaborative" + . "&scope=playlist-read-private%20playlist-read-collaborative" . "&state=" . int(rand() * 100); get '/' => sub { @@ -27,9 +30,36 @@ get '/' => sub { get 'auth' => sub { my $c = shift; - $c->render(text => "Your code is:\n" . $c->param("code")); + + # TODO: check state too if ever productionize / allow multiple + # users instead of local-only + my $code = $c->param("code"); + if (!$code) { + $c->render(text => "Failed to Authorize; Go back and try again"); + return; + } + my $ua = LWP::UserAgent->new(); + my $hash = encode_base64("$CLIENT_ID:$CLIENT_SECRET", ""); + $ua->default_header('Authorization' => "Basic $hash"); + my %form = ( + grant_type => "authorization_code", + code => $code, + redirect_uri => "http://localhost:3000/auth", + ); + my $res = $ua->post( + "https://accounts.spotify.com/api/token", + \%form, + ); + if (!$res->is_success) { + my $err = $res->decoded_content; + return $c->render(text => "Error Authenticating: $err"); + } + my $json = decode_json($res->decoded_content); + my $tok = $json->{access_token} . ""; + return $c->render(text => $tok); }; + app->start; __DATA__