From 19bc31e6e3e4b1eceefa265bd353ebfd621bebe2 Mon Sep 17 00:00:00 2001 From: Davor Date: Thu, 9 Jun 2022 12:21:47 +0200 Subject: [PATCH] MR comments - added error handler for unauthorized --- app.py | 3 +++ areas/roles/role_service.py | 1 + helpers/auth_guard.py | 4 ++-- helpers/error_handler.py | 6 ++++++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/app.py b/app.py index 44c28c7..97f6ffb 100644 --- a/app.py +++ b/app.py @@ -23,11 +23,13 @@ from helpers import ( BadRequest, KratosError, HydraError, + Unauthorized, bad_request_error, validation_error, kratos_error, global_error, hydra_error, + unauthorized_error, ) from config import * @@ -56,6 +58,7 @@ app.register_error_handler(BadRequest, bad_request_error) app.register_error_handler(ValidationError, validation_error) app.register_error_handler(KratosError, kratos_error) app.register_error_handler(HydraError, hydra_error) +app.register_error_handler(Unauthorized, unauthorized_error) jwt = JWTManager(app) diff --git a/areas/roles/role_service.py b/areas/roles/role_service.py index a117985..90ad064 100644 --- a/areas/roles/role_service.py +++ b/areas/roles/role_service.py @@ -12,6 +12,7 @@ class RoleService: def get_role_by_id(role_id): return Role.query.filter_by(id=role_id).first() + @staticmethod def is_user_admin(userId): dashboard_role_id = AppRole.query.filter_by(user_id=userId, app_id=1).first().role_id return dashboard_role_id == 1 \ No newline at end of file diff --git a/helpers/auth_guard.py b/helpers/auth_guard.py index d40cd3d..0a28c3d 100644 --- a/helpers/auth_guard.py +++ b/helpers/auth_guard.py @@ -1,10 +1,10 @@ from functools import wraps -from flask import jsonify from areas.roles.role_service import RoleService from flask_jwt_extended import verify_jwt_in_request from flask_jwt_extended import get_jwt +from helpers import Unauthorized def admin_required(): def wrapper(fn): @@ -17,7 +17,7 @@ def admin_required(): if isAdmin: return fn(*args, **kwargs) else: - return jsonify(msg="Admins only!"), 403 + raise Unauthorized("You need to have admin permissions.") return decorator diff --git a/helpers/error_handler.py b/helpers/error_handler.py index e6c696f..bd32c46 100644 --- a/helpers/error_handler.py +++ b/helpers/error_handler.py @@ -13,6 +13,8 @@ class HydraError(Exception): class BadRequest(Exception): pass +class Unauthorized(Exception): + pass def bad_request_error(e): message = e.args[0] if e.args else "Bad request to the server." @@ -42,3 +44,7 @@ def hydra_error(e): def global_error(e): message = str(e) return jsonify({"errorMessage": message}), 500 + +def unauthorized_error(e): + message = str(e) + return jsonify({"errorMessaeg": message}), 403