1<?php
2
3namespace App\Http\Middleware;
4
5use Closure;
6use JWTAuth;
7use Exception;
8use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
9
10class JwtMiddleware extends BaseMiddleware
11{
12
13 /**
14 * Handle an incoming request.
15 *
16 * @param \Illuminate\Http\Request $request
17 * @param \Closure $next
18 * @return mixed
19 */
20 public function handle($request, Closure $next)
21 {
22 try {
23 $user = JWTAuth::parseToken()->authenticate();
24 } catch (Exception $e) {
25 if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
26 return response()->json(['status' => 'Token is Invalid']);
27 }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
28 return response()->json(['status' => 'Token is Expired']);
29 }else{
30 return response()->json(['status' => 'Authorization Token not found']);
31 }
32 }
33 return $next($request);
34 }
35}
1<?php
2
3namespace App\Http\Controllers;
4
5use Illuminate\Http\Request;
6use Illuminate\Support\Facades\Auth;
7use App\Http\Controllers\Controller;
8
9class AuthController extends Controller
10{
11 /**
12 * Create a new AuthController instance.
13 *
14 * @return void
15 */
16 public function __construct()
17 {
18 $this->middleware('auth:api', ['except' => ['login']]);
19 }
20
21 /**
22 * Get a JWT token via given credentials.
23 *
24 * @param \Illuminate\Http\Request $request
25 *
26 * @return \Illuminate\Http\JsonResponse
27 */
28 public function login(Request $request)
29 {
30 $credentials = $request->only('email', 'password');
31
32 if ($token = $this->guard()->attempt($credentials)) {
33 return $this->respondWithToken($token);
34 }
35
36 return response()->json(['error' => 'Unauthorized'], 401);
37 }
38
39 /**
40 * Get the authenticated User
41 *
42 * @return \Illuminate\Http\JsonResponse
43 */
44 public function me()
45 {
46 return response()->json($this->guard()->user());
47 }
48
49 /**
50 * Log the user out (Invalidate the token)
51 *
52 * @return \Illuminate\Http\JsonResponse
53 */
54 public function logout()
55 {
56 $this->guard()->logout();
57
58 return response()->json(['message' => 'Successfully logged out']);
59 }
60
61 /**
62 * Refresh a token.
63 *
64 * @return \Illuminate\Http\JsonResponse
65 */
66 public function refresh()
67 {
68 return $this->respondWithToken($this->guard()->refresh());
69 }
70
71 /**
72 * Get the token array structure.
73 *
74 * @param string $token
75 *
76 * @return \Illuminate\Http\JsonResponse
77 */
78 protected function respondWithToken($token)
79 {
80 return response()->json([
81 'access_token' => $token,
82 'token_type' => 'bearer',
83 'expires_in' => $this->guard()->factory()->getTTL() * 60
84 ]);
85 }
86
87 /**
88 * Get the guard to be used during authentication.
89 *
90 * @return \Illuminate\Contracts\Auth\Guard
91 */
92 public function guard()
93 {
94 return Auth::guard();
95 }
96}
97