Skip to content

Commit

Permalink
ui, fix: use wss if loaded with https
Browse files Browse the repository at this point in the history
  • Loading branch information
dxstiny committed Apr 26, 2024
1 parent 1777612 commit b090a5f
Show file tree
Hide file tree
Showing 118 changed files with 125 additions and 123 deletions.
64 changes: 31 additions & 33 deletions src/server/handler/spotifyAuth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""reAudioPlayer ONE"""
from __future__ import annotations

__copyright__ = "Copyright (c) 2022 https://github.com/reAudioPlayer"

import os
Expand All @@ -13,19 +14,20 @@
import aiohttp
from aiohttp import web
from pyaddict import JDict
from spotipy.oauth2 import SpotifyOAuth # type: ignore
from spotipy.oauth2 import SpotifyOAuth # type: ignore

from config.runtime import Runtime
from helper.cacheDecorator import clearCache
from helper.logged import Logged


SCOPE = "user-library-read user-follow-read user-follow-modify"
REDIRECT = "http://localhost:1234/api/spotify/callback"
REDIRECT = "{origin}/api/spotify/callback"


class SpotifyAuth(Logged):
"""Handles Spotify Authentication"""

def __init__(self) -> None:
super().__init__(self.__class__.__name__)
self._attemptedClientAuth = False
Expand All @@ -34,21 +36,22 @@ async def _refresh(self, token: str) -> bool:
"""attempts to use the refresh token to get a new access token"""
# spotify api docs: https://developer.spotify.com/documentation/general/guides/authorization-guide/#refreshing-access-tokens # pylint: disable=line-too-long
async with aiohttp.ClientSession() as session:
async with session.post("https://accounts.spotify.com/api/token", data = {
"grant_type": "refresh_token",
"refresh_token": token
}, headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": SpotifyAuth._getSpotifyAuthHeader()
}) as response:
async with session.post(
"https://accounts.spotify.com/api/token",
data={"grant_type": "refresh_token", "refresh_token": token},
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": SpotifyAuth._getSpotifyAuthHeader(),
},
) as response:
self._logger.debug("refresh response: %s", response.status)
if response.status != 200:
return False

data = await response.json()
data["refresh_token"] = token
data["expires_at"] = time() + data["expires_in"]
with open(".cache", "w", encoding = "utf8") as file:
with open(".cache", "w+", encoding="utf8") as file:
file.write(json.dumps(data))
return True

Expand All @@ -62,7 +65,7 @@ async def shouldAuth(self, forceRefresh: bool = False) -> bool:
self._logger.info("Spotify is not authenticated (no cache file)")
return True

with open(".cache", "r", encoding = "utf8") as file:
with open(".cache", "r", encoding="utf8") as file:
data = json.loads(file.read())

if not forceRefresh and not JDict(data).ensure("expires_at", int) < time():
Expand All @@ -84,7 +87,7 @@ def isAuth(self) -> bool:
def authorizeUrl(self) -> str:
"""Returns the Spotify Authorize Url"""
clientId, _ = SpotifyAuth._getSpotifyAuthData()
return f"https://accounts.spotify.com/authorize?client_id={clientId}&response_type=code&redirect_uri={REDIRECT}&scope={SCOPE}" # pylint: disable=line-too-long
return f"https://accounts.spotify.com/authorize?client_id={clientId}&response_type=code&redirect_uri={REDIRECT}&scope={SCOPE}" # pylint: disable=line-too-long

@staticmethod
def isDisabled() -> bool:
Expand Down Expand Up @@ -113,17 +116,15 @@ def _getSpotifyAuthHeader() -> Optional[str]:
return None

clientId, secret = SpotifyAuth._getSpotifyAuthData()
return "Basic " + \
base64.b64encode(f"{clientId}:{secret}"\
.encode("utf-8")).decode("utf-8")
return "Basic " + base64.b64encode(f"{clientId}:{secret}".encode("utf-8")).decode("utf-8")

@staticmethod
def getSpotifyAuth() -> Optional[SpotifyOAuth]: # pylint: disable=invalid-name
def getSpotifyAuth() -> Optional[SpotifyOAuth]: # pylint: disable=invalid-name
"""Returns the SpotifyOAuth object"""
if SpotifyAuth.isDisabled():
return None
id_, secret = SpotifyAuth._getSpotifyAuthData()
return SpotifyOAuth(id_, secret, "localhost", scope = SCOPE)
return SpotifyOAuth(id_, secret, "localhost", scope=SCOPE)

async def getSpotifyConfig(self, _: web.Request) -> web.Response:
"""get(/api/config/spotify)"""
Expand All @@ -134,10 +135,7 @@ async def getSpotifyConfig(self, _: web.Request) -> web.Response:
return web.HTTPUnauthorized()

id_, secret = SpotifyAuth._getSpotifyAuthData()
return web.json_response({
"id": id_,
"secret": secret
})
return web.json_response({"id": id_, "secret": secret})

async def clientSideAuthHandler(self, _: web.Request) -> web.Response:
"""Returns the client side auth data"""
Expand All @@ -157,7 +155,7 @@ async def _reset() -> None:
self._attemptedClientAuth = True

# redirect to spotify auth
return web.Response(text = self.authorizeUrl)
return web.Response(text=self.authorizeUrl)

async def callbackHandler(self, request: web.Request) -> web.Response:
"""Handles the callback from Spotify"""
Expand All @@ -177,20 +175,20 @@ async def getSpotifyToken(self, code: str) -> Optional[str]:
return None

async with aiohttp.ClientSession() as session:
async with session.post("https://accounts.spotify.com/api/token", data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT
}, headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": SpotifyAuth._getSpotifyAuthHeader()
}) as resp:
async with session.post(
"https://accounts.spotify.com/api/token",
data={"grant_type": "authorization_code", "code": code, "redirect_uri": REDIRECT},
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": SpotifyAuth._getSpotifyAuthHeader(),
},
) as resp:
if resp.status == 200:
data = await resp.json()

data["expires_at"] = data["expires_in"] + int(time())

with open(".cache", "w", encoding = "utf8") as file:
with open(".cache", "w", encoding="utf8") as file:
file.write(json.dumps(data))

clearCache()
Expand Down Expand Up @@ -218,15 +216,15 @@ def addExpiresAt(self) -> bool:
if not os.path.isfile(".cache"):
return False

with open(".cache", "r", encoding = "utf8") as file:
with open(".cache", "r", encoding="utf8") as file:
data = json.loads(file.read())

if "expires_at" in data:
return False

data["expires_at"] = data["expires_in"] + int(time())

with open(".cache", "w", encoding = "utf8") as file:
with open(".cache", "w+", encoding="utf8") as file:
file.write(json.dumps(data))

return True

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added src/ui/dist/assets/Album-4b441c69.js.gz
Binary file not shown.
Binary file removed src/ui/dist/assets/Album-867d822f.js.gz
Binary file not shown.
Loading

0 comments on commit b090a5f

Please sign in to comment.