Skip to content

Commit

Permalink
fix: Moved clear token logic to server side
Browse files Browse the repository at this point in the history
  • Loading branch information
dogukanoksuz committed Jul 10, 2024
1 parent f5d9484 commit a21d51e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
9 changes: 7 additions & 2 deletions app/Http/Controllers/API/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public function __construct()
'resetPassword',
'loginBranding',
'authGate',
'logout',
]
]
);
Expand Down Expand Up @@ -190,11 +191,15 @@ public function logout(Request $request)
{
$deleteToken = Cookie::forget('token', '/', $request->getHost());
$deleteCurrentUser = Cookie::forget('currentUser', '/', $request->getHost());
auth('api')->logout();
try {
auth('api')->logout();
} catch (\Throwable $e) {}

return response()->json(['message' => 'User successfully signed out'])
->withCookie($deleteToken)
->withCookie($deleteCurrentUser);
->withCookie($deleteCurrentUser)
->withoutCookie('token')
->withoutCookie('currentUser');
}

/**
Expand Down
1 change: 1 addition & 0 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class Kernel extends HttpKernel
Middleware\TrustProxies::class,
Middleware\EncryptCookies::class,
Middleware\CookieJWTAuthenticator::class,
Middleware\ClearTokenOnUnauthorized::class,
];

protected $middlewareGroups = [
Expand Down
33 changes: 33 additions & 0 deletions app/Http/Middleware/ClearTokenOnUnauthorized.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ClearTokenOnUnauthorized
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$response = $next($request);

if ($response->getStatusCode() === 401) {
// Clear token
try {
auth('api')->logout();
} catch (\Throwable $e) {}

return $response->withoutCookie('token')
->withoutCookie('currentUser');
}

return $response;
}
}

0 comments on commit a21d51e

Please sign in to comment.