autenticazione
This commit is contained in:
parent
2f32706bda
commit
e320a46191
2 changed files with 108 additions and 0 deletions
49
backend/endpoints/spotify_api.py
Normal file
49
backend/endpoints/spotify_api.py
Normal file
|
@ -0,0 +1,49 @@
|
|||
from fastapi import APIRouter, Request, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
import requests
|
||||
import os
|
||||
from auth.session import SessionData, current_session
|
||||
|
||||
api = APIRouter(prefix="/music")
|
||||
|
||||
SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
|
||||
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
|
||||
SPOTIFY_REDIRECT_URI = os.getenv("HOST") + "/music/callback"
|
||||
SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
|
||||
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
|
||||
SPOTIFY_PLAY_URL = "https://api.spotify.com/v1/me/player/play"
|
||||
|
||||
# Step 1: Redirect user to Spotify login
|
||||
@api.get("/login")
|
||||
def login():
|
||||
scope = "user-modify-playback-state user-read-playback-state"
|
||||
url = (
|
||||
f"{SPOTIFY_AUTH_URL}?response_type=code"
|
||||
f"&client_id={SPOTIFY_CLIENT_ID}"
|
||||
f"&scope={scope}"
|
||||
f"&redirect_uri={SPOTIFY_REDIRECT_URI}"
|
||||
)
|
||||
return RedirectResponse(url)
|
||||
|
||||
# Step 2: Callback to get access token
|
||||
@api.get("/callback")
|
||||
def callback(code: str):
|
||||
payload = {
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": SPOTIFY_REDIRECT_URI,
|
||||
"client_id": SPOTIFY_CLIENT_ID,
|
||||
"client_secret": SPOTIFY_CLIENT_SECRET,
|
||||
}
|
||||
response = requests.post(SPOTIFY_TOKEN_URL, data=payload)
|
||||
token_info = response.json()
|
||||
access_token = token_info.get("access_token")
|
||||
refresh_token = token_info.get("refresh_token")
|
||||
expires_in = token_info.get("expires_in")
|
||||
|
||||
# Salva access_token in sessione o database per usi futuri
|
||||
if current_session is None:
|
||||
current_session = SessionData(access_token, refresh_token, expires_in)
|
||||
|
||||
return {}
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue