From 0007a8ba03521d9648bfab59cc59a856ea041738 Mon Sep 17 00:00:00 2001
From: Lari Taskula <lari.taskula@hypernova.fi>
Date: Wed, 18 Sep 2024 10:21:47 +0000
Subject: [PATCH] [24.05.x] Bug 28907: Add REST exceptions for public routes
 auth

To test:
1. perl -c Koha/REST/Plugin/Exceptions.pm
2. perl -c Koha/Exceptions/REST.pm

More tests coming in following patches.

Signed-off-by: Victor Grousset/tuxayo <victor@tuxayo.net>

Signed-off-by: Marcel de Rooy <m.de.rooy@rijksmuseum.nl>
---
 Koha/Exceptions/REST.pm        |  6 ++++++
 Koha/REST/Plugin/Exceptions.pm | 17 +++++++++++++++++
 2 files changed, 23 insertions(+)

diff --git a/Koha/Exceptions/REST.pm b/Koha/Exceptions/REST.pm
index bbcd0fed6b..f0150503c5 100644
--- a/Koha/Exceptions/REST.pm
+++ b/Koha/Exceptions/REST.pm
@@ -8,6 +8,12 @@ use Exception::Class (
     'Koha::Exceptions::REST' => {
         isa => 'Koha::Exception',
     },
+    'Koha::Exceptions::REST::Public::Authentication::Required' => {
+        description => "This public route requires authentication",
+    },
+    'Koha::Exceptions::REST::Public::Unauthorized' => {
+        description => "Unprivileged user cannot access another user's resources",
+    },
     'Koha::Exceptions::REST::Query::InvalidOperator' => {
         description => "Invalid operator found in query",
         fields      => ['operator']
diff --git a/Koha/REST/Plugin/Exceptions.pm b/Koha/REST/Plugin/Exceptions.pm
index 5107af103d..55c9cfc2c6 100644
--- a/Koha/REST/Plugin/Exceptions.pm
+++ b/Koha/REST/Plugin/Exceptions.pm
@@ -68,6 +68,23 @@ sub register {
                     }
                 );
             }
+            elsif ( blessed $exception
+                && ref($exception) eq 'Koha::Exceptions::REST::Public::Authentication::Required' )
+            {
+                return $c->render(
+                    status => 401,
+                    json   => {
+                        error => $exception->error,
+                    }
+                );
+            } elsif ( blessed $exception && ref($exception) eq 'Koha::Exceptions::REST::Public::Unauthorized' ) {
+                return $c->render(
+                    status => 403,
+                    json   => {
+                        error => $exception->error,
+                    }
+                );
+            }
 
             if ( blessed $exception ) {
                 $type = "(" . ref($exception) . ")";
-- 
2.34.1