Skip to content
This repository has been archived by the owner on Jun 1, 2023. It is now read-only.

Commit

Permalink
Merge branch 'release/v1.0.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
ja573 committed Feb 14, 2019
2 parents a47d980 + ba7a44b commit cbe8f46
Show file tree
Hide file tree
Showing 13 changed files with 51 additions and 44 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: python
python:
- "2.7"
- "3.5"
install:
- pip install -r ./config/requirements.txt
script:
- flake8 --ignore=E221,E241 ./src/
- flake8 --ignore=E221,E241 ./src/*
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:2
FROM python:3.5

RUN apt-get update && apt-get upgrade -y && \
pip install --upgrade pip
Expand Down
5 changes: 2 additions & 3 deletions config/api.env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
API_DEBUG=False
JWT_DISABLED=False
SECRET_KEY=an_up_to_255_bytes_random_key
TOKEN_LIFETIME=3600
PBKDF2_ITERATIONS=10000
ALLOW_ORIGIN=https://metrics-broker.com
ALLOW_ORIGIN=https://openbookpublishers.com
6 changes: 2 additions & 4 deletions config/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
flake8==3.6.0
pbkdf2==1.3
PyJWT==1.6.1
flake8==3.6.0
psycopg2-binary==2.7.5
uri==2.0.0
urllib3==1.23
web.py==0.39
web.py==0.40-dev1
48 changes: 29 additions & 19 deletions src/api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Identifier Translator JSON API. Simple web.py based API to a
Expand All @@ -10,12 +10,10 @@
Use of this software is governed by the terms of the MIT license
Dependencies:
pbkdf2==1.3
PyJWT==1.6.1
PyJWT==1.7.1
psycopg2-binary==2.7.5
uri==2.0.0
urllib3==1.20
web.py==0.39
web.py==0.40-dev1
"""

import os
Expand All @@ -24,13 +22,24 @@
import json
from aux import logger_instance, debug_mode
from errors import Error, internal_error, not_found, \
FATAL, NORESULT, BADFILTERS, UNAUTHORIZED, FORBIDDEN
NORESULT, BADFILTERS, UNAUTHORIZED, FORBIDDEN

# get logging interface
logger = logger_instance(__name__)
web.config.debug = debug_mode()
# Get secret key to check jwt against
SECRET_KEY = os.environ['SECRET_KEY']
# You may disable JWT auth. when implementing the API in a local network
JWT_DISABLED = False
# Get secret key to check JWT
SECRET_KEY = ""
try:
if 'JWT_DISABLED' in os.environ:
JWT_DISABLED = os.environ['JWT_DISABLED'] in ('true', 'True')
if 'SECRET_KEY' in os.environ:
SECRET_KEY = os.environ['SECRET_KEY']
assert JWT_DISABLED or SECRET_KEY
except AssertionError as error:
logger.error(error)
raise

# Define routes
urls = (
Expand All @@ -50,7 +59,7 @@
db=os.environ['IDENTIFIERSDB_DB'])
except Exception as error:
logger.error(error)
raise Error(FATAL)
raise


def api_response(fn):
Expand Down Expand Up @@ -82,15 +91,16 @@ def response(self, *args, **kw):
def check_token(fn):
"""Decorator to act as middleware, checking authentication token"""
def response(self, *args, **kw):
intoken = get_token_from_header()
try:
jwt.decode(intoken, SECRET_KEY)
except jwt.exceptions.DecodeError:
raise Error(FORBIDDEN)
except jwt.ExpiredSignatureError:
raise Error(UNAUTHORIZED, msg="Signature expired.")
except jwt.InvalidTokenError:
raise Error(UNAUTHORIZED, msg="Invalid token.")
if not JWT_DISABLED:
intoken = get_token_from_header()
try:
jwt.decode(intoken, SECRET_KEY)
except jwt.exceptions.DecodeError:
raise Error(FORBIDDEN)
except jwt.ExpiredSignatureError:
raise Error(UNAUTHORIZED, msg="Signature expired.")
except jwt.InvalidTokenError:
raise Error(UNAUTHORIZED, msg="Invalid token.")
return fn(self, *args, **kw)
return response

Expand Down Expand Up @@ -124,7 +134,7 @@ def build_parms(filters):
raise Error(BADFILTERS, msg="Unknown filter '%s'" % (p))

process = {"work_type": types, "uri_scheme": schemes, "canonical": canoncl}
for key, values in process.items():
for key, values in list(process.items()):
if len(values) > 0:
try:
andclause, ops = build_clause(key, values)
Expand Down
6 changes: 3 additions & 3 deletions src/aux.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
Expand All @@ -17,7 +17,7 @@ def logger_instance(name):


def strtolist(data):
if isinstance(data, basestring):
if isinstance(data, str):
return [data]
elif type(data) is list:
elif isinstance(data, list):
return data
2 changes: 1 addition & 1 deletion src/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(self, level=DEFAULT, msg='', data=[]):
httpcode = self.get_code(level)
headers = {'Content-Type': 'application/json'}
message = self.get_message(level)
params = web.input() if web.input() else web.data()
params = web.input() if web.input() else web.data().decode('utf-8')
output = json.dumps(
self.make_output(httpcode, message, msg, params, data))

Expand Down
4 changes: 1 addition & 3 deletions src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,12 +416,10 @@ def results_to_works(results, include_relatives=False):
uris = [] # temp array of work URIs (strings, used for comparison)
uris_fmt = [] # temporary array of work URIs (Identifier objects)
last = len(results) - 1
cur = results[0]

i = 0
for e in results:
if i == 0:
# we can't do cur=results[0] outsise--it moves IterBetter's pointer
cur = e
if e["work_id"] != cur["work_id"]:
cur["titles"] = titles
cur["URI"] = uris_fmt
Expand Down
2 changes: 1 addition & 1 deletion src/relationsctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def POST(self, name):
"""Create a work relation"""
logger.debug("Data: %s" % (web.data()))

data = json.loads(web.data())
data = json.loads(web.data().decode('utf-8'))
parent_uuid = data.get('parent_UUID') or data.get('parent_uuid')
child_uuid = data.get('child_UUID') or data.get('child_uuid')

Expand Down
2 changes: 1 addition & 1 deletion src/titlesctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def POST(self, name):
"""Add titles to an existing work"""
logger.debug("Data: %s" % (web.data()))

data = json.loads(web.data())
data = json.loads(web.data().decode('utf-8'))
title = data.get('title')
work_id = data.get('UUID') or data.get('uuid')

Expand Down
8 changes: 5 additions & 3 deletions src/translator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import web
import urllib
import urllib.request
import urllib.parse
import urllib.error
from aux import logger_instance, debug_mode
from api import build_parms, json_response, api_response, check_token
from errors import Error, BADPARAMS, NORESULT, NOTALLOWED, \
Expand Down Expand Up @@ -41,7 +43,7 @@ def GET(self, name):
scheme, value = Identifier.split_uri(uri)
assert scheme and value
if title:
title = urllib.unquote(title.strip())
title = urllib.parse.unquote(title.strip())
assert title
assert uri or title
except BaseException:
Expand All @@ -60,7 +62,7 @@ def GET(self, name):
if not results:
raise Error(NORESULT)

return self.process_results(results, strict)
return self.process_results(list(results), strict)

def POST(self, name):
raise Error(NOTALLOWED)
Expand Down
2 changes: 1 addition & 1 deletion src/urisctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def POST(self, name):
"""Add identifiers to an existing work"""
logger.debug("Data: %s" % (web.data()))

data = json.loads(web.data())
data = json.loads(web.data().decode('utf-8'))
uri = data.get('URI') or data.get('uri')
canonical = data.get('canonical') in (True, "true", "True")
work_id = data.get('UUID') or data.get('uuid')
Expand Down
4 changes: 2 additions & 2 deletions src/worksctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def GET(self, name):
raise Error(NORESULT)

include_relatives = work_id is not None
data = results_to_works(results, include_relatives)
data = results_to_works(list(results), include_relatives)

if sort:
reverse = order == "desc"
Expand All @@ -59,7 +59,7 @@ def POST(self, name):
"""Create a work"""
logger.debug("Data: %s" % (web.data()))

data = json.loads(web.data())
data = json.loads(web.data().decode('utf-8'))
wtype = data.get('type')
title = data.get('title')
uri = data.get('URI') or data.get('uri')
Expand Down

0 comments on commit cbe8f46

Please sign in to comment.