Skip to content

Commit

Permalink
Removes API keys from source code. They are now fetched at runtime from
Browse files Browse the repository at this point in the history
the server.
  • Loading branch information
cfangmeier committed May 23, 2019
1 parent 58a887a commit 74eff44
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 13 deletions.
24 changes: 24 additions & 0 deletions key_server_example.py
@@ -0,0 +1,24 @@
#!/usr/bin/env python
import rsa
import base64
from flask import Flask, request, jsonify

KEYS = dict(
LASTFM_API_KEY="REDACTED",
LASTFM_API_SECRET="READACTED",
GOOGLE_DEVELOPER_KEY="READACTED",
)

app = Flask(__name__)


@app.route("/", methods=["POST"])
def submit_person():
req_data = request.json
pub_key = rsa.PublicKey.load_pkcs1(req_data["public_key"])
keys = {}
for id_ in req_data["ids"]:
crypt_bytes = rsa.encrypt(KEYS[id_].encode(), pub_key)
b64_utf = base64.encodebytes(crypt_bytes).decode()
keys[id_] = b64_utf
return jsonify(keys)
3 changes: 2 additions & 1 deletion requirements.txt
@@ -1,4 +1,5 @@
requests
rsa>=4.0
requests>=2.21.0
gmusicapi==11.0.0
urwid==2.0.1
pyYAML>=4.2b1
Expand Down
8 changes: 6 additions & 2 deletions tuijam/app.py
Expand Up @@ -23,6 +23,7 @@
from .music_objects import serialize, deserialize
from .ui import SearchInput, SearchPanel, QueuePanel, PlayBar
from tuijam import CONFIG_DIR
from tuijam.utility import lookup_keys


class App(urwid.Pile):
Expand Down Expand Up @@ -55,7 +56,7 @@ def __init__(self):

from apiclient.discovery import build

developer_key = "AIzaSyBtETg1PDC124WUAZ5JhJH_pu2xboHVIS0"
developer_key, = lookup_keys("GOOGLE_DEVELOPER_KEY")
self.youtube = build("youtube", "v3", developerKey=developer_key)

@self.player.event_callback("end_file")
Expand Down Expand Up @@ -641,7 +642,7 @@ def main():
parser.add_argument(
"action", choices=["", "configure_last_fm"], default="", nargs="?"
)
parser.add_argument("-v", "--verbose", action="store_true")
parser.add_argument("-v", "--verbose", action="store_true") # TODO: use this
args = parser.parse_args()

print("starting up.")
Expand All @@ -653,6 +654,9 @@ def main():
if args.action == "configure_last_fm":
LastFMAPI.configure()
exit(0)
elif args.action != "":
print(f"Unrecognized option: {args.action}")
exit(0)

app = App()
print("logging in.")
Expand Down
11 changes: 8 additions & 3 deletions tuijam/lastfm.py
Expand Up @@ -6,18 +6,23 @@
import yaml

from tuijam import __version__, CONFIG_DIR
from tuijam.utility import lookup_keys


class LastFMAPI:
API_KEY = "5cc045ddea219f89adb7efec168d64ac"
API_SECRET = "8397b63671b211c4e70f6ba1d8ea7825"
API_KEY = None
API_SECRET = None
API_ROOT_URL = "http://ws.audioscrobbler.com/2.0/"
USER_AGENT = "TUIJam/" + __version__

def __init__(self, sk=None):
# Initialize session key with None
self.sk = sk
pass

if LastFMAPI.API_KEY is None or LastFMAPI.API_SECRET is None:
LastFMAPI.API_KEY, LastFMAPI.API_SECRET = lookup_keys(
"LASTFM_API_KEY", "LASTFM_API_SECRET"
)

def call_method(self, method_name: str, params=None) -> dict:
# Construct API request parameters dict
Expand Down
17 changes: 10 additions & 7 deletions tuijam/ui.py
Expand Up @@ -2,7 +2,15 @@

import urwid

from .music_objects import Song, Artist, YTVideo, Album, Situation, RadioStation, Playlist
from .music_objects import (
Song,
Artist,
YTVideo,
Album,
Situation,
RadioStation,
Playlist,
)
from .utility import sec_to_min_sec

WELCOME = """
Expand Down Expand Up @@ -45,9 +53,7 @@ def keypress(self, size, key):


class SearchPanel(urwid.ListBox):

class SearchResults:

def __init__(self, categories):
self.artists = []
self.albums = []
Expand Down Expand Up @@ -150,10 +156,7 @@ def back(self):
pass

def update_search_results(
self,
*categories,
title="Search Results",
isprevsong=False,
self, *categories, title="Search Results", isprevsong=False
):
if not self.viewing_previous_songs: # only remember search history
self.search_history.append((self.get_focus()[1], self.search_results))
Expand Down
19 changes: 19 additions & 0 deletions tuijam/utility.py
@@ -1,3 +1,22 @@
def sec_to_min_sec(sec_tot):
s = int(sec_tot or 0)
return s // 60, s % 60


def lookup_keys(*key_ids):
import rsa
import base64
import requests

(pub, priv) = rsa.newkeys(512)

host = "https://tuijam.fangmeier.tech"

res = requests.post(
host, json={"public_key": pub.save_pkcs1().decode(), "ids": key_ids}
)

keys = []
for id_, key_enc in res.json().items():
keys.append(rsa.decrypt(base64.decodebytes(key_enc.encode()), priv).decode())
return keys

0 comments on commit 74eff44

Please sign in to comment.