|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers\Auth; |
| 4 | + |
| 5 | +use App\Http\Controllers\Controller; |
| 6 | +use App\Http\Requests\Auth\LoginRequest; |
| 7 | +use Illuminate\Http\Request; |
| 8 | +use Illuminate\Http\JsonResponse; |
| 9 | +use Illuminate\Http\Response; |
| 10 | +use Illuminate\Support\Facades\Auth; |
| 11 | + |
| 12 | +/** |
| 13 | + * @tags Auth (JWT) |
| 14 | + */ |
| 15 | +class AuthController extends Controller |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Create a new AuthController instance. |
| 19 | + * |
| 20 | + * @return void |
| 21 | + */ |
| 22 | + public function __construct() |
| 23 | + { |
| 24 | + $this->middleware('auth:api', ['except' => ['login']]); |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Login |
| 29 | + * |
| 30 | + * Get a JWT via given credentials. |
| 31 | + */ |
| 32 | + public function login(LoginRequest $request): JsonResponse |
| 33 | + { |
| 34 | + $credentials = request(['email', 'password']); |
| 35 | + |
| 36 | + if (! $token = auth()->attempt($credentials)) { |
| 37 | + return response()->json(['error' => 'Unauthorized'], 401); |
| 38 | + } |
| 39 | + |
| 40 | + return $this->respondWithToken($token); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Authenticated user data |
| 45 | + * |
| 46 | + * Get the authenticated User. |
| 47 | + */ |
| 48 | + public function me() : JsonResponse |
| 49 | + { |
| 50 | + return response()->json(auth()->user()); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + /** |
| 55 | + * Logout |
| 56 | + * |
| 57 | + * Log the user out (Invalidate the token). |
| 58 | + */ |
| 59 | + public function logout(Request $request): Response |
| 60 | + { |
| 61 | + auth()->logout(true); |
| 62 | + |
| 63 | + return response()->noContent(); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Token refresh |
| 68 | + * |
| 69 | + * Refresh a token. |
| 70 | + */ |
| 71 | + public function refresh() : JsonResponse |
| 72 | + { |
| 73 | + return $this->respondWithToken(auth()->refresh(true, true)); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Get the token array structure. |
| 78 | + * |
| 79 | + * @param string $token |
| 80 | + * |
| 81 | + * @return \Illuminate\Http\JsonResponse |
| 82 | + */ |
| 83 | + protected function respondWithToken($token) |
| 84 | + { |
| 85 | + return response()->json([ |
| 86 | + 'access_token' => $token, |
| 87 | + 'token_type' => 'bearer', |
| 88 | + 'expires_in' => auth()->factory()->getTTL() * 60 |
| 89 | + ]); |
| 90 | + } |
| 91 | +} |
0 commit comments