Created
November 16, 2019 05:33
-
-
Save Sebuliba-Adrian/4ef3947fc7ea9beac7d9b4dbabc0c02b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Exception; | |
use App\Models\User; | |
use Firebase\JWT\JWT; | |
use Firebase\JWT\ExpiredException; | |
class JwtMiddleware | |
{ | |
public function handle($request, Closure $next, $guard = null) | |
{ | |
$token = $request->header('Authorization'); | |
if (!$token) { | |
return response()->json([ | |
'error' => 'Token not provided.' | |
], 401); | |
} | |
try { | |
$credentials = JWT::decode($token, env('JWT_SECRET'), ['HS256']); | |
} catch (ExpiredException $e) { | |
return response()->json([ | |
'error' => 'Provided token is expired.' | |
], 400); | |
} catch (Exception $e) { | |
return response()->json([ | |
'error' => 'An error while decoding token.' | |
], 400); | |
} | |
$user = User::find($credentials->sub); | |
$request->auth = $user; | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment