Skip to content

Commit e82b476

Browse files
AjayAjay
authored andcommitted
Feat: unauthenticated error
1 parent f24a86e commit e82b476

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

src/Exceptions/ErrorCodes.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ class ErrorCodes
66
{
77
const REQUEST_PARSE_EXCEPTION = 100;
88
const UNKNOWN_EXCEPTION = 1;
9+
const UNAUTHENTICATION_EXCEPTION = 401;
910
const UNAUTHORIZED_EXCEPTION = 403;
1011
const VALIDATION_EXCEPTION = 422;
1112
const RESOURCE_NOT_FOUND_EXCEPTION = 404;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
namespace Froiden\RestAPI\Exceptions;
4+
5+
class UnauthenticationException extends ApiException
6+
{
7+
protected $statusCode = 401;
8+
9+
protected $code = ErrorCodes::UNAUTHENTICATION_EXCEPTION;
10+
11+
protected $message = "Not authenticated to perform this request";
12+
}

src/Handlers/ApiExceptionHandler.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@
66
use Froiden\RestAPI\ApiResponse;
77
use Froiden\RestAPI\Exceptions\ApiException;
88
use Froiden\RestAPI\Exceptions\Parse\UnknownFieldException;
9+
use Froiden\RestAPI\Exceptions\UnauthenticatedException;
10+
use Froiden\RestAPI\Exceptions\UnauthenticationException;
911
use Froiden\RestAPI\Exceptions\UnauthorizedException;
1012
use Froiden\RestAPI\Exceptions\ValidationException;
13+
use Illuminate\Auth\AuthenticationException;
1114
use Illuminate\Database\Eloquent\ModelNotFoundException;
1215
use Illuminate\Database\QueryException;
1316
use Illuminate\Http\Exceptions\HttpResponseException;
@@ -25,6 +28,12 @@ public function render($request, Throwable $e)
2528
// This is done to prevent default error message show in otherwise application
2629
// which are not using the api
2730
if (!$debug && $request->is($prefix.'/*')) {
31+
32+
// When the user is not authenticated or logged show this message with status code 401
33+
if ($e instanceof AuthenticationException) {
34+
return ApiResponse::exception(new UnauthenticationException());
35+
}
36+
2837
if ($e instanceof HttpResponseException || $e instanceof \Illuminate\Validation\ValidationException) {
2938
if ($e->status == 403) {
3039
return ApiResponse::exception(new UnauthorizedException());

src/Middleware/ApiMiddleware.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,4 @@ public function handle($request, Closure $next)
2929

3030
return $response;
3131
}
32-
}
32+
}

0 commit comments

Comments
 (0)