Reputation: 546
I'm using laravel v5.8, VueJS and passport v7.4 for Authentication. Below is my login function:
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response([
'status' => 0,
'message' => $validator->errors()->first()
]);
}
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials))
return response()->json([
'status' => 0,
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('authToken');
$token = $tokenResult->token;
$token->save();
$user_role = Auth::user()->user_type;
$user->assignRole($user_role);
return response()->json([
'status' => 1,
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
]);
}
My issue is my token expires in 10 seconds(this is for testing purpose). So I check for every route if the token is expired using the below function in VueJS:
isValid(token) {
const payload = this.payload(token);
if (payload) {
const datetime = Math.floor(Date.now() / 1000);
return payload.exp >= datetime ? true : false;
}
return false;
}
So this works fine, but what should i do to refresh the token? Can we make a middleware to handle it by itself? Or Is there anyway to detect if the user is actively using the application like in normal session based authentication?
Upvotes: 3
Views: 1455
Reputation: 686
Looks like you are reinventing the wheel, I would recommend to make a request to passport /oauth/token which will then return the access_token and refresh token. Also to get away with a build authentication control layer I am using nuxtjs.
The below example requires guzzlehttp/guzzle package.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\User;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class AuthController extends Controller
{
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function user(Request $request)
{
return response()->json(['user' => new User($request->user())]);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse|\Psr\Http\Message\StreamInterface
*/
public function login (Request $request)
{
$http = new Client;
try {
$response = $http->post(config('app.url') . '/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => 'ugjAn1BD4Cs8gAP63RqixyCOD3Z1dUrrNiEgxQtN',
'username' => $request->get('email'),
'password' => $request->get('password')
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if (400 === $e->getCode()) {
return response()->json(['message' => 'Invalid request. Please enter username and password'], $e->getCode());
} else if (401 === $e->getCode()) {
return response()->json([message' => 'Your credentials are incorrect. Please try again.'], $e->getCode());
}
}
return response()->json(['message' => 'Something went wrong please try again later. ' . $e->getMessage()], $e->getCode());
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
function logout (Request $request)
{
$request->user()->tokens->each(function ($token, $key) {
$token->delete();
});
return response()->json(['message' => 'Logged out successfully'], 200);
}
}
Upvotes: 1