EnisaAuthController.php
1 <?php 2 3 namespace App\Http\Controllers; 4 5 use Illuminate\Http\Request; 6 7 class EnisaAuthController extends Controller 8 { 9 public function __construct() 10 { 11 $this->middleware('auth:api', ['except' => ['login']]); 12 } 13 14 /** 15 * Get a JWT via given credentials. 16 * 17 * @return \Illuminate\Http\JsonResponse 18 */ 19 public function login() 20 { 21 $credentials = request(['username', 'password']); 22 if (! $token = auth('api')->claims( 23 ['user' => [ 24 'username' => $credentials['username'], 25 'role' => 'ENISA', 26 'ip' => request()->ip(), 27 ]] 28 )->attempt($credentials)) { 29 return response()->json(['error' => 'Unauthorized'], 401); 30 } 31 32 return $this->respondWithToken($token); 33 } 34 35 36 /** 37 * Log the user out (Invalidate the token). 38 * 39 * @return \Illuminate\Http\JsonResponse 40 */ 41 public function logout() 42 { 43 auth()->logout(); 44 45 return response()->json(['message' => 'Successfully logged out']); 46 } 47 48 /** 49 * Refresh a token. 50 * 51 * @return \Illuminate\Http\JsonResponse 52 */ 53 public function refresh() 54 { 55 return $this->respondWithToken(auth()->refresh()); 56 } 57 58 /** 59 * Get the token array structure. 60 * 61 * @param string $token 62 * 63 * @return \Illuminate\Http\JsonResponse 64 */ 65 protected function respondWithToken($token) 66 { 67 return response()->json([ 68 'success' => true, 69 'access_token' => $token, 70 ]); 71 } 72 }