openmedialibrary/oml/directory.py

57 lines
1.4 KiB
Python
Raw Normal View History

2014-05-04 17:26:43 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
2014-05-17 14:26:59 +00:00
# DHT placeholder
2014-09-02 22:32:44 +00:00
2014-05-04 17:26:43 +00:00
2014-05-17 14:26:59 +00:00
import logging
2014-05-04 17:26:43 +00:00
import requests
import ed25519
import json
2014-09-02 22:32:44 +00:00
2014-05-04 17:26:43 +00:00
import settings
2014-05-17 14:26:59 +00:00
logger = logging.getLogger('oml.directory')
2014-05-04 17:26:43 +00:00
base = settings.server['directory_service']
def get(vk):
2014-09-08 19:17:35 +00:00
id = vk.to_ascii(encoding='base64').decode()
url = '%s/%s' % (base, id)
2014-08-09 21:05:36 +00:00
headers = {
'User-Agent': settings.USER_AGENT
}
2015-02-27 10:49:56 +00:00
try:
r = requests.get(url, headers=headers)
except:
logger.info('get failed %s', url)
return None
2014-05-04 17:26:43 +00:00
sig = r.headers.get('X-Ed25519-Signature')
data = r.content
if sig and data:
vk = ed25519.VerifyingKey(id, encoding='base64')
try:
vk.verify(sig, data, encoding='base64')
2014-09-02 22:32:44 +00:00
data = json.loads(data.decode('utf-8'))
2014-05-04 17:26:43 +00:00
except ed25519.BadSignatureError:
2014-05-17 14:26:59 +00:00
logger.debug('invalid signature')
2014-05-04 17:26:43 +00:00
data = None
return data
def put(sk, data):
2014-09-08 19:17:35 +00:00
id = sk.get_verifying_key().to_ascii(encoding='base64').decode()
2014-09-09 10:08:04 +00:00
data = json.dumps(data).encode()
2014-05-04 17:26:43 +00:00
sig = sk.sign(data, encoding='base64')
url ='%s/%s' % (base, id)
headers = {
2014-08-09 21:05:36 +00:00
'User-Agent': settings.USER_AGENT,
2014-05-04 17:26:43 +00:00
'X-Ed25519-Signature': sig
}
try:
2014-05-17 00:14:15 +00:00
r = requests.put(url, data, headers=headers, timeout=2)
2014-05-04 17:26:43 +00:00
except:
2015-02-27 10:49:56 +00:00
logger.info('put failed: %s', data)
2014-05-04 17:26:43 +00:00
return False
return r.status_code == 200