Created
April 16, 2020 15:13
-
-
Save csinghdev/e949632c9f7dd4262c2f7e0145d0eaf0 to your computer and use it in GitHub Desktop.
Auth APIs using JWT in Laravel
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\Controllers; | |
use Illuminate\Http\Request; | |
class AuthController extends Controller | |
{ | |
public function __construct() | |
{ | |
$this->middleware('auth:api', ['except' => ['login']]); | |
} | |
public function login() { | |
$credentials = request(['email', 'password']); | |
if (! $token = auth()->attempt($credentials)) { | |
return response()->json(['error' => 'Invalid email or password'], 401); | |
} | |
return $this->respondWithToken($token); | |
} | |
private function respondWithToken($token) { | |
return response()->json([ | |
'token' => $token, | |
'access_type' => 'bearer', | |
'expires_in' => auth()->factory()->getTTL() * 60 | |
]); | |
} | |
public function logout() { | |
auth()->logout(); | |
return response()->json(['msg' => 'User successfully logged out']); | |
} | |
public function refresh() { | |
return $this->respondWithToken(auth()->refresh()); | |
} | |
public function me() { | |
return response()->json(auth()->user()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment