Skip to content

Commit fed5b5d

Browse files
committed
better error handling
1 parent 51baf64 commit fed5b5d

File tree

2 files changed

+70
-40
lines changed

2 files changed

+70
-40
lines changed

client.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import os
1010
import argparse
1111

12-
version = 10
12+
version = 11
1313

1414
limit_traffic = True
1515

@@ -35,7 +35,7 @@
3535
fname = args.tex
3636
server = args.server
3737
if server[-1] != '/': server += "/"
38-
if not server.endswith("/v1/"): server += "/v1/"
38+
if not server.endswith("/v1/"): server += "v1/"
3939

4040
def get_keys(filename, import_base=None):
4141
content = open(filename).read()
@@ -197,7 +197,11 @@ def show_error(obj):
197197
elif obj["reason"] == "policy":
198198
for entry in obj["entries"]:
199199
print("\u001b[31m[!] Server policy rejected entry %s\u001b[0m. Reason: %s" % (entry["ID"], entry["reason"]))
200-
200+
else:
201+
print("\u001b[31m[!] Unhandled error occurred!\u001b[0m Reason (%s) %s" % (obj["reason"], obj["message"] if "message" in obj else ""))
202+
else:
203+
print("\u001b[31m[!] Unknown error occurred!\u001b[0m")
204+
sys.exit(1)
201205

202206
action = args.action
203207

@@ -218,7 +222,12 @@ def show_error(obj):
218222
sys.exit(1)
219223

220224
response = requests.get(server + "version")
221-
version_info = response.json()
225+
try:
226+
version_info = response.json()
227+
except:
228+
print("\u001b[31m[!] Could not get version info from server.\u001b[0m Is the server URL \"%s\" correct?" % server)
229+
sys.exit(1)
230+
222231
if version_info["version"] > version:
223232
print("[!] New version available, updating...")
224233
script = requests.get(server + version_info["url"])

server.py

Lines changed: 57 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import sys
88
import importlib
99

10-
VERSION = 10
10+
VERSION = 11
1111

1212
app = Flask(__name__)
1313
tokens = True
@@ -19,14 +19,20 @@
1919

2020
def check_token(token, operation):
2121
if not tokens:
22-
return True
22+
return (True, None)
23+
24+
if len(token_db) == 0:
25+
return (False, {"success": False, "reason": "server_problem", "message": "The token database on the server seems to be corrupted, please inform your BibTool administrator."})
2326

2427
if not token in token_db:
25-
return False
28+
return (False, {"success": False, "reason": "access_denied", "message": "Invalid token. Check your 'token' file."})
2629
if not operation in token_db[token]:
27-
return False
28-
return token_db[token][operation]
29-
30+
return (False, {"success": False, "reason": "access_denied", "message": "Your token does not grant %s access." % operation})
31+
ok = token_db[token][operation]
32+
if not ok:
33+
return (False, {"success": False, "reason": "access_denied", "message": "Your token does not grant %s access." % operation})
34+
else:
35+
return (True, None)
3036

3137
def entry_to_bibtex(entry):
3238
newdb = bibtexparser.bibdatabase.BibDatabase()
@@ -100,25 +106,28 @@ def get_reqtxt():
100106
@app.route("/v1/entry/<string:key>", defaults={"token": None}, methods=["GET"])
101107
@app.route("/v1/entry/<string:key>/<string:token>", methods=["GET"])
102108
def get_entry(key, token):
103-
if not check_token(token, "read"):
104-
return jsonify({"success": False, "reason": "access_denied", "message": "Your token does not grant read access."})
109+
ok, reason = check_token(token, "read")
110+
if not ok:
111+
return jsonify(reason)
105112
return jsonify({"success": True, "entry": entry_by_key(key)})
106113

107114

108115
@app.route("/v1/bibentry/<string:key>", defaults={"token": None}, methods=["GET"])
109116
@app.route("/v1/bibentry/<string:key>/<string:token>", methods=["GET"])
110117
def get_bibentry(key, token):
111-
if not check_token(token, "read"):
112-
return "Access denied!"
118+
ok, reason = check_token(token, "read")
119+
if not ok:
120+
return reason["message"]
113121
return entry_to_bibtex(entry_by_key(key))
114122

115123

116124
@app.route("/v1/get", methods=["POST"])
117125
def get_bibfile():
118126
if not request.json or not "entries" in request.json or not "token" in request.json:
119127
return "Invalid request"
120-
if not check_token(request.json["token"], "read"):
121-
return "Access denied!"
128+
ok, reason = check_token(request.json["token"], "read")
129+
if not ok:
130+
return reason["message"]
122131

123132
bib = ""
124133
for entry in request.json["entries"]:
@@ -130,9 +139,10 @@ def get_bibfile():
130139
@app.route("/v1/get_json", methods=["POST"])
131140
def get_bibfile_as_json():
132141
if not request.json or not "entries" in request.json or not "token" in request.json:
133-
return "Invalid request"
134-
if not check_token(request.json["token"], "read"):
135-
return jsonify({"success": False, "reason": "access_denied", "message": "Your token does not grant read access."})
142+
return jsonify({"success": False, "reason": "invalid_request", "message": "Invalid request"})
143+
ok, reason = check_token(request.json["token"], "read")
144+
if not ok:
145+
return jsonify(reason)
136146

137147
bib = []
138148
for entry in request.json["entries"]:
@@ -144,8 +154,9 @@ def get_bibfile_as_json():
144154
@app.route("/v1/suggest/<string:key>", defaults={"token": None}, methods=["GET"])
145155
@app.route("/v1/suggest/<string:key>/<string:token>", methods=["GET"])
146156
def suggest_entry(key, token):
147-
if not check_token(token, "search"):
148-
return jsonify({"success": False, "reason": "access_denied"})
157+
ok, reason = check_token(token, "search")
158+
if not ok:
159+
return jsonify(reason)
149160

150161
entry = entry_by_key(key)
151162
if not entry:
@@ -175,8 +186,9 @@ def suggest_entry(key, token):
175186
@app.route("/v1/search/<string:query>", defaults={"token": None}, methods=["GET"])
176187
@app.route("/v1/search/<string:query>/<string:token>", methods=["GET"])
177188
def search_entry(query, token):
178-
if not check_token(token, "search"):
179-
return "Access denied!"
189+
ok, reason = check_token(token, "search")
190+
if not ok:
191+
return reason["message"]
180192

181193
query_parts = query.split(" ")
182194
for q in query_parts:
@@ -201,8 +213,9 @@ def search_entry(query, token):
201213
def add_entry(key):
202214
if not request.json or not "entry" in request.json or not "token" in request.json:
203215
return jsonify({"success": False, "reason": "missing_entry"})
204-
if not check_token(request.json["token"], "write"):
205-
return jsonify({"success": False, "reason": "access_denied", "message": "Your token does not allow adding new bibliography entries."})
216+
ok, reason = check_token(request.json["token"], "write")
217+
if not ok:
218+
return jsonify(reason)
206219

207220
if "ID" not in request.json["entry"]:
208221
request.json["entry"]["ID"] = key
@@ -227,8 +240,9 @@ def add_entry(key):
227240
def replace_entry(key):
228241
if not request.json or not "entry" in request.json or not "token" in request.json:
229242
return jsonify({"success": False, "reason": "missing_entry"})
230-
if not check_token(request.json["token"], "write"):
231-
return jsonify({"success": False, "reason": "access_denied", "message": "Your token does not allow changing bibliography entries."})
243+
ok, reason = check_token(request.json["token"], "write")
244+
if not ok:
245+
return jsonify(reason)
232246

233247
for (idx, entry) in enumerate(bib_database.entries):
234248
if entry["ID"] == key:
@@ -242,8 +256,9 @@ def replace_entry(key):
242256
@app.route("/v1/entry/<string:key>", defaults={"token": None}, methods=["DELETE"])
243257
@app.route("/v1/entry/<string:key>/<string:token>", methods=["DELETE"])
244258
def remove_entry(key, token):
245-
if not check_token(token, "delete"):
246-
return jsonify({"success": False, "reasons": "access_denied", "message": "Your token does not allow deleting bibliography entries."})
259+
ok, reason = check_token(token, "delete")
260+
if not ok:
261+
return jsonify(reason)
247262

248263
for (idx, entry) in enumerate(bib_database.entries):
249264
if entry["ID"] == key:
@@ -258,8 +273,9 @@ def remove_entry(key, token):
258273
def add_entries():
259274
if not request.json or not "entries" in request.json or not "token" in request.json:
260275
return jsonify({"success": False, "reason": "missing_entry"})
261-
if not check_token(request.json["token"], "write"):
262-
return jsonify({"success": False, "reason": "access_denied", "message": "Your token does not allow modifying the bibliography. Remove the bib file to get a fresh one from the server"})
276+
ok, reason = check_token(request.json["token"], "write")
277+
if not ok:
278+
return jsonify(reason)
263279

264280
dups = []
265281
changes = False
@@ -301,7 +317,7 @@ def add_entries():
301317

302318
@app.route("/v1/sync", methods=["GET"])
303319
def sync():
304-
global repo, bib_database, token_db
320+
global repo, bib_database, token_db, tokens
305321

306322
parser = BibTexParser(common_strings=True)
307323
parser.ignore_nonstandard_types = False
@@ -317,17 +333,22 @@ def sync():
317333
with open(repo_path + "/" + repo_name) as bibtex_file:
318334
bib_database = bibtexparser.load(bibtex_file, parser)
319335

320-
for e in bib_database.entries:
321-
if policy:
322-
accept, reason = policy.check(e, bib_database.entries)
323-
if not accept:
324-
print("Reject %s: %s" % (e["ID"], reason))
336+
# uncomment for debug purposes
337+
#for e in bib_database.entries:
338+
#if policy:
339+
#accept, reason = policy.check(e, bib_database.entries)
340+
#if not accept:
341+
#print("Reject %s: %s" % (e["ID"], reason))
325342

326343
try:
327-
with open(repo_path + "/tokens.json") as tokens:
328-
token_db = json.load(tokens)
329-
except:
344+
tdb = open(repo_path + "/tokens.json")
345+
token_db = json.load(tdb)
346+
except IOError:
347+
print("No tokens.json, disable token checks")
330348
tokens = False
349+
except:
350+
print("Error: error in the tokens.json, could not load it!")
351+
token_db = {}
331352

332353
return "Synced!"
333354

0 commit comments

Comments
 (0)