Skip to content
This repository was archived by the owner on Aug 24, 2023. It is now read-only.

Store passwords in keyring #68

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ This project incorporates some code modified from the following projects:
`mlbv` requires the following software to be installed and configured:

* python
- python v3 (tested with 3.6)
- python v3 (tested with 3.7)
* python modules (installed by `pip install`):
- [requests](http://python-requests.org/) module
- [python-dateutil](https://dateutil.readthedocs.io/en/stable/) module
Expand Down
4 changes: 2 additions & 2 deletions config.template
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
# used. The default value is shown commented out.
# To change a value, copy the line, uncomment it, and provide your own value.

# Credentials. Fill out your username and password here. Or provide them via command-line options.
# Credentials are stored securely by the python module keyring.
# This uses the keyring service name "MLB.tv" and the username you provide.
# username=<Put your MLB username here>
# password=<Put your MLB password here>

# Favourite teams, This is a comma-separated list of favourite team codes.
# Favourite teams are identified by colour in the game listings, and can be
Expand Down
7 changes: 1 addition & 6 deletions mlbv/mlbam/common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,10 @@ def __init_configparser(self, script_name):
return parser[script_name]

@staticmethod
def generate_config(username=None, password=None, servicename="MLB.tv"):
def generate_config(username=None, servicename="MLB.tv"):
"""Creates config file from template + user prompts."""
script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
# use the script name minus any extension for the config directory
config_dir = None
config_dir = os.path.join(Config.config_dir_roots[1], script_name)
if not os.path.exists(config_dir):
print("Creating config directory: {}".format(config_dir))
Expand Down Expand Up @@ -141,17 +140,13 @@ def generate_config(username=None, password=None, servicename="MLB.tv"):

if username is None:
username = input("Enter {} username: ".format(servicename))
if password is None:
password = input("Enter {} password: ".format(servicename))

with open(template_config_path, "r") as infile, open(
config_file, "w"
) as outfile:
for line in infile:
if line.startswith("# username="):
outfile.write("username={}\n".format(username))
elif line.startswith("# password="):
outfile.write("password={}\n".format(password))
else:
outfile.write(line)
print("Finished creating config file: {}".format(config_file))
Expand Down
1 change: 0 additions & 1 deletion mlbv/mlbam/mlbconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
DEFAULTS = { # is applied to initial config before reading from file - these are the defaults:
"mlbv": {
"username": "",
"password": "",
"favs": "",
"fav_colour": "blue",
"scores": "true",
Expand Down
13 changes: 11 additions & 2 deletions mlbv/mlbam/mlbsession.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import re
import string

import keyring
import lxml
import lxml.etree
import pytz
Expand Down Expand Up @@ -45,6 +46,7 @@
"https://search-api-mlbtv.mlb.com/svc/search/v2/graphql/persisted/query/"
"core/Airings?variables={{%22partnerProgramIds%22%3A[%22{game_id}%22]}}"
)
SERVICE_NAME = "MLB.tv"


def gen_random_string(n):
Expand Down Expand Up @@ -74,10 +76,18 @@ def __init__(self):
# Override
def login(self):
"""Posts to the AUTHN_URL and saves the session token"""
password = keyring.get_password(SERVICE_NAME, config.CONFIG.parser["username"])
if password is None:
raise EnvironmentError(
f"""No password for MLB.tv username {config.CONFIG.parser["username"]} found in keyring.

Set up your username and password with mlbv --init!

""")

authn_params = {
"username": config.CONFIG.parser["username"],
"password": config.CONFIG.parser["password"],
"password": password,
"options": {
"multiOptionalFactorEnroll": False,
"warnBeforePasswordExpired": True,
Expand Down Expand Up @@ -264,7 +274,6 @@ def lookup_stream_url(self, game_pk, media_id):
"""game_pk: game_pk
media_id: mediaPlaybackId
"""
stream_url = None
headers = {
"Authorization": self.access_token,
"User-agent": USER_AGENT,
Expand Down
17 changes: 11 additions & 6 deletions mlbv/mlbam/mlbv.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import argparse
import getpass
import inspect
import logging
import os
Expand All @@ -18,6 +19,7 @@

from datetime import datetime
from datetime import timedelta
import keyring

import mlbv.mlbam.common.config as config
import mlbv.mlbam.common.gamedata as gamedata
Expand Down Expand Up @@ -235,9 +237,6 @@ def main():
parser.add_argument(
"--username", help=argparse.SUPPRESS
) # help="MLB.tv username. Required for live/archived games.")
parser.add_argument(
"--password", help=argparse.SUPPRESS
) # help="MLB.tv password. Required for live/archived games.")
parser.add_argument(
"--fetch",
"--record",
Expand Down Expand Up @@ -312,7 +311,15 @@ def main():
feedtype = None

if args.init:
return config.Config.generate_config(args.username, args.password, "MLB.tv")
# this causes the prompt for username to appear before we store the password
returned: bool = config.Config.generate_config(servicename="MLB.tv")
config.CONFIG = config.Config(mlbconfig.DEFAULTS, args)
if not config.CONFIG.parser["username"]:
print("No MLB.tv username specified, exiting.")
sys.exit(2)
print("Prompting for MLB.tv password for username '{}'".format(config.CONFIG.parser["username"]))
keyring.set_password("MLB.tv", config.CONFIG.parser["username"], getpass.getpass("MLB.tv password: "))
return returned

# get our config
config.CONFIG = config.Config(mlbconfig.DEFAULTS, args)
Expand Down Expand Up @@ -343,8 +350,6 @@ def main():
config.CONFIG.parser["cache"] = args.cache
if args.username:
config.CONFIG.parser["username"] = args.username
if args.password:
config.CONFIG.parser["password"] = args.password
if args.inning_offset is not None:
config.CONFIG.parser["stream_start_offset_secs"] = str(args.inning_offset)
if args.team:
Expand Down
Loading