diff --git a/sachet/server/models.py b/sachet/server/models.py index a8a02d1..bc5f1bc 100644 --- a/sachet/server/models.py +++ b/sachet/server/models.py @@ -87,6 +87,29 @@ class User(db.Model): return jwt.encode(payload, app.config.get("SECRET_KEY"), algorithm="HS256") + def read_token(token): + """Read a JWT and validate it. + + Returns a tuple: dictionary of the JWT's data, and the corresponding user + if available. + """ + + data = jwt.decode( + token, + app.config["SECRET_KEY"], + algorithms=["HS256"], + ) + + if BlacklistToken.check_blacklist(token): + raise jwt.ExpiredSignatureError("Token revoked.") + + user = User.query.filter_by(username=data.get("sub")).first() + if not user: + raise jwt.InvalidTokenError("No user corresponds to this token.") + + return data, user + + class PermissionField(fields.Field): """Field that serializes a Permissions bitmask to an array of strings.""" @@ -155,29 +178,6 @@ class BlacklistToken(db.Model): return True -def read_token(token): - """Read a JWT and validate it. - - Returns a tuple: dictionary of the JWT's data, and the corresponding user - if available. - """ - - data = jwt.decode( - token, - app.config["SECRET_KEY"], - algorithms=["HS256"], - ) - - if BlacklistToken.check_blacklist(token): - raise jwt.ExpiredSignatureError("Token revoked.") - - user = User.query.filter_by(username=data.get("sub")).first() - if not user: - raise jwt.InvalidTokenError("No user corresponds to this token.") - - return data, user - - def auth_required(f): """Decorator to require authentication. @@ -200,7 +200,7 @@ def auth_required(f): return jsonify({"status": "fail", "message": "Missing auth token"}), 401 try: - data, user = read_token(token) + data, user = User.read_token(token) except jwt.ExpiredSignatureError: # if it's expired we don't want it lingering in the db BlacklistToken.check_blacklist(token) diff --git a/sachet/server/users/views.py b/sachet/server/users/views.py index 8665d06..170ffe2 100644 --- a/sachet/server/users/views.py +++ b/sachet/server/users/views.py @@ -3,7 +3,6 @@ from flask import Blueprint, request, jsonify from flask.views import MethodView from sachet.server.models import ( auth_required, - read_token, patch, Permissions, User, @@ -66,7 +65,7 @@ class LogoutAPI(MethodView): return jsonify({"status": "fail", "message": "Token already revoked."}), 400 try: - data, token_user = read_token(token) + data, token_user = User.read_token(token) except jwt.ExpiredSignatureError: return jsonify({"status": "fail", "message": "Token already expired."}), 400 except jwt.InvalidTokenError: