import re
import subprocess
import sys
import six
_RE_INFO_USER_EMAIL = r'Logged in as (?P<email>\S+)\.$'
class AuthorizationError(Exception):
pass
def _RunCommand(command):
try:
return six.ensure_str(
subprocess.check_output(['luci-auth', command],
stderr=subprocess.STDOUT,
universal_newlines=True))
except subprocess.CalledProcessError as exc:
raise AuthorizationError(exc.output.strip())
def CheckLoggedIn():
"""Check that the user is currently logged in.
Otherwise sys.exit immediately with the error message from luci-auth
instructing the user how to log in.
"""
try:
GetAccessToken()
except AuthorizationError as exc:
sys.exit(str(exc))
def GetAccessToken():
"""Get an access token to make requests on behalf of the logged in user."""
return _RunCommand('token').rstrip()
def GetUserEmail():
"""Get the email address of the currently logged in user."""
output = _RunCommand('info')
m = re.match(_RE_INFO_USER_EMAIL, output, re.MULTILINE)
assert m, 'Failed to parse luci-auth info output.'
return m.group('email')