rpc works with authentication

This commit is contained in:
Alex Grintsvayg 2017-01-09 19:31:06 -05:00
parent 53acb2d9cd
commit 05725e0dc9
4 changed files with 30 additions and 37 deletions

View file

@ -261,7 +261,6 @@ class Daemon(AuthJSONRPCServer):
self.analytics_manager = analytics_manager self.analytics_manager = analytics_manager
self.lbryid = conf.settings.lbryid self.lbryid = conf.settings.lbryid
self.daemon_conf = conf.settings.get_conf_filename()
self.wallet_user = None self.wallet_user = None
self.wallet_password = None self.wallet_password = None
@ -1357,7 +1356,8 @@ class Daemon(AuthJSONRPCServer):
fn = self.callable_methods.get(p['function']) fn = self.callable_methods.get(p['function'])
if fn is None: if fn is None:
return self._render_response( return self._render_response(
"Function '" + p['function'] + "' is not a valid function") "No help available for '" + p['function'] + "'. It is not a valid function."
)
return self._render_response(textwrap.dedent(fn.__doc__)) return self._render_response(textwrap.dedent(fn.__doc__))
else: else:
return self._render_response(textwrap.dedent(self.jsonrpc_help.__doc__)) return self._render_response(textwrap.dedent(self.jsonrpc_help.__doc__))
@ -2220,29 +2220,26 @@ class Daemon(AuthJSONRPCServer):
""" """
exclude_previous = True
force = False
log_type = None
if p: if p:
if 'name_prefix' in p: if 'name_prefix' in p:
log_type = p['name_prefix'] + '_api' log_type = p['name_prefix'] + '_api'
elif 'log_type' in p: elif 'log_type' in p:
log_type = p['log_type'] + '_api' log_type = p['log_type'] + '_api'
else:
log_type = None
if 'exclude_previous' in p: if 'exclude_previous' in p:
exclude_previous = p['exclude_previous'] exclude_previous = p['exclude_previous']
else:
exclude_previous = True
if 'message' in p: if 'message' in p:
log.info("Upload log message: " + str(p['message'])) log.info("Upload log message: " + str(p['message']))
if 'force' in p: if 'force' in p:
force = p['force'] force = p['force']
else:
force = False
else: else:
log_type = "api" log_type = "api"
exclude_previous = True
d = self._upload_log(log_type=log_type, exclude_previous=exclude_previous, force=force) d = self._upload_log(log_type=log_type, exclude_previous=exclude_previous, force=force)
d.addCallback(lambda _: self._render_response(True)) d.addCallback(lambda _: self._render_response(True))

View file

@ -4,7 +4,7 @@ import os
import sys import sys
from lbrynet import conf from lbrynet import conf
from lbrynet.lbrynet_daemon.auth.client import LBRYAPIClient from lbrynet.lbrynet_daemon.auth.client import JSONRPCException, LBRYAPIClient
from lbrynet.lbrynet_daemon.Daemon import LOADING_WALLET_CODE from lbrynet.lbrynet_daemon.Daemon import LOADING_WALLET_CODE
from jsonrpc.common import RPCError from jsonrpc.common import RPCError
from urllib2 import URLError from urllib2 import URLError
@ -26,6 +26,7 @@ def main():
return 1 return 1
conf.initialize_settings() conf.initialize_settings()
conf.update_settings_from_file()
api = LBRYAPIClient.get_client() api = LBRYAPIClient.get_client()
# TODO: check if port is bound. Error if its not # TODO: check if port is bound. Error if its not
@ -67,22 +68,17 @@ def main():
print result print result
else: else:
print json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')) print json.dumps(result, sort_keys=True, indent=2, separators=(',', ': '))
except RPCError as err: except (RPCError, KeyError, JSONRPCException) as err:
handle_error(err, api, method) # TODO: The api should return proper error codes
except KeyError as err: # and messages so that they can be passed along to the user
handle_error(err, api, method) # instead of this generic message.
# https://app.asana.com/0/158602294500137/200173944358192
print "Something went wrong, here's the usage for %s:" % method
def handle_error(err, api, method): print api.help({'function': method})
# TODO: The api should return proper error codes if hasattr(err, 'msg'):
# and messages so that they can be passed along to the user print "Here's the traceback for the error you encountered:"
# instead of this generic message. print err.msg
# https://app.asana.com/0/158602294500137/200173944358192 return 1
print "Something went wrong, here's the usage for %s:" % method
print api.help({'function': method})
if hasattr(err, 'msg'):
print "Here's the traceback for the error you encountered:"
print err.msg
def guess_type(x): def guess_type(x):

View file

@ -37,22 +37,22 @@ class AuthAPIClient(object):
raise AttributeError # Python internal stuff raise AttributeError # Python internal stuff
def f(*args): def f(*args):
return self.call(name, args) return self.call(name, args[0] if args else {})
return f return f
def call(self, method, params={}): def call(self, method, params={}):
self.__id_count += 1 self.__id_count += 1
pre_auth_postdata = { pre_auth_post_data = {
'version': '1.1', 'version': '1.1',
'method': method, 'method': method,
'params': params, 'params': [params],
'id': self.__id_count 'id': self.__id_count
} }
to_auth = get_auth_message(pre_auth_postdata) to_auth = get_auth_message(pre_auth_post_data)
token = self.__api_key.get_hmac(to_auth) token = self.__api_key.get_hmac(to_auth)
pre_auth_postdata.update({'hmac': token}) pre_auth_post_data.update({'hmac': token})
postdata = json.dumps(pre_auth_postdata) post_data = json.dumps(pre_auth_post_data)
service_url = self.__service_url service_url = self.__service_url
auth_header = self.__auth_header auth_header = self.__auth_header
cookies = self.__cookies cookies = self.__cookies
@ -60,7 +60,7 @@ class AuthAPIClient(object):
req = requests.Request(method='POST', req = requests.Request(method='POST',
url=service_url, url=service_url,
data=postdata, data=post_data,
headers={ headers={
'Host': host, 'Host': host,
'User-Agent': USER_AGENT, 'User-Agent': USER_AGENT,
@ -97,7 +97,6 @@ class AuthAPIClient(object):
def config(cls, key_name=None, key=None, pw_path=None, def config(cls, key_name=None, key=None, pw_path=None,
timeout=HTTP_TIMEOUT, timeout=HTTP_TIMEOUT,
connection=None, count=0, connection=None, count=0,
service=None,
cookies=None, auth=None, cookies=None, auth=None,
url=None, login_url=None): url=None, login_url=None):
@ -153,8 +152,7 @@ class AuthAPIClient(object):
assert cookies.get(LBRY_SECRET, False), "Missing cookie" assert cookies.get(LBRY_SECRET, False), "Missing cookie"
secret = cookies.get(LBRY_SECRET) secret = cookies.get(LBRY_SECRET)
api_key = APIKey(secret, api_key_name) api_key = APIKey(secret, api_key_name)
return cls(api_key, timeout, conn, id_count, service, cookies, return cls(api_key, timeout, conn, id_count, cookies, auth_header, url, service_url)
auth_header, url, service_url)
class LBRYAPIClient(object): class LBRYAPIClient(object):

View file

@ -141,7 +141,8 @@ class AuthJSONRPCServer(AuthorizedBase):
self._set_headers(request, message, True) self._set_headers(request, message, True)
self._render_message(request, message) self._render_message(request, message)
return server.NOT_DONE_YET return server.NOT_DONE_YET
session.touch() else:
session.touch()
request.content.seek(0, 0) request.content.seek(0, 0)
content = request.content.read() content = request.content.read()
@ -284,6 +285,7 @@ class AuthJSONRPCServer(AuthorizedBase):
return False return False
def _verify_token(self, session_id, message, token): def _verify_token(self, session_id, message, token):
assert token is not None, InvalidAuthenticationToken
to_auth = get_auth_message(message) to_auth = get_auth_message(message)
api_key = self.sessions.get(session_id) api_key = self.sessions.get(session_id)
assert api_key.compare_hmac(to_auth, token), InvalidAuthenticationToken assert api_key.compare_hmac(to_auth, token), InvalidAuthenticationToken