-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
60 lines (50 loc) · 1.78 KB
/
auth.py
File metadata and controls
60 lines (50 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import datetime
import os
from base64 import b64encode
from datetime import datetime as dt
from urllib.error import HTTPError
import requests
import streamlit as st
DATE_FORMAT = "%m/%d/%y %H:%M:%S"
class Authenticator:
def __init__(
self,
client_id: str = st.secrets["CLIENT_ID"],
client_secret: str = st.secrets["CLIENT_SECRET"],
) -> str:
self.client_id = client_id
self.client_secret = client_secret
if 'token' not in st.session_state:
self.get_token()
def get_token(self):
if (
'token' in st.session_state
and 'expiry' in st.session_state
and dt.now() < st.session_state["expiry"]
):
return st.session_state["token"]
encoded = b64encode(
(self.client_id + ":" + self.client_secret).encode("ascii")
).decode("ascii")
headers = {"Authorization": f"Basic {encoded}"}
request_time = dt.now()
r = requests.post(
url="https://accounts.spotify.com/api/token",
data={"grant_type": "client_credentials"},
headers=headers,
)
if r.status_code == 200:
response_data = r.json()
st.session_state["token"] = response_data["access_token"]
st.session_state["expiry"] = request_time + datetime.timedelta(
seconds=response_data["expires_in"]
)
return st.session_state["token"]
else:
raise HTTPError(
url="https://accounts.spotify.com/api/token",
code=r.status_code,
msg=f"For more info, check out https://developer.spotify.com/documentation/web-api/concepts/api-calls",
hdrs=headers,
fp=None,
)