laravel passport Method logoutOtherDevices does not exist - laravel-8

I'm trying to logout from other devices using laravel passport but couldnot.
Route::post('logoutotherdevices', [PassportController::class, 'logoutOtherDevices']);
public function logoutOtherDevices(Request $request,$password)
{
Auth::logoutOtherDevices($password);
return response()->json([
'success' => true,
'message' => 'User logout successfully.'
], 200);
}

Related

Laravel 8: after successful log in Auth session destroying on its own whenever I'm trying to redirect it to another route

web.php
Route::get('/', [AdminLoginController::class, 'index'])->name('admin.login');
Route::post('/login', [AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::group(['middleware' => 'admin.middle' ] , function() {
Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('admin.dashboard');
});
AdminLoginController.php
public function login(Request $request)
{
$validator = Validator::make($request->all(),[
'email' => 'required|email:rfc,dns|exists:admins,email',
'password' => 'required',
],[
'email.required' => "Email is required",
'email.email' => "Email is invlaid",
'email.exists' => "Email does not exist",
'password.required' => "Password is required"
]);
if($validator->fails())
{
$this->sendResponse(400,$validator->errors()->first(),[]);
}
else
{
if (Auth::guard('admin')->attempt(["email" => $request->email , "password" => $request->password])) {
$this->sendResponse(
200,
"Successfully Logged In",
[
'location' => route('admin.dashboard')
]);
}
else {
$this->sendResponse(
500,
"Email or Password is incorrect",
[]);
}
}
}
AdminAuthenticate.php
class AdminAuthentication
{
public function handle(Request $request, Closure $next)
{
if (Auth::guard('admin')->check())
{
if (Auth::guard('admin')->user()){
return $next($request);
}
}
return redirect('/admin');
}
}
Maybe your sendResponse is not set corresponding headers (Set-cookie)? It looks like you mixing api responses with responses for browser.

SERVICE UNAVAILABLE error at REST API calling

My API route in routes/api.php file is like below.
Route::post('/register', [RegisterController::class, 'register']);
My register function of RegisterController is like below
public function register(RegistrationValidate $request)
{
$user = User::create([
'username' => request('username'),
'email' => request('email'),
'full_name' => request('full_name'),
'store_name' => request('store_name'),
'store_logo' => $fileName,
'password' => Hash::make(request('password')),
]);
$token = $user->createToken($this->clientToken())->accessToken;
return response()->json([
'user' => $user,
'token' => $token,
], 201);
}
I am getting SERVICE UNAVAILABLE error like below
I used php artisan up command and clear the cache. But the result is as like before.

Laravel api returning 401 (Authentication failed) even when logged in

i have created a simple crud app using Laravel 6 and VueJs it was working fine before but when i added middleware auth to api routes group it returns error 401 even when logged in.
here is api.php
Route::group(['middleware' => ['api','auth']], function(){
Route::get('contacts',function(){
return Contact::latest()->orderBy('created_at','desc')->get();
});
Route::get('contact/{id}',function($id){
return Contact::findOrFail($id);
});
Route::post('contact/store',function(Request $request){
return Contact::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone
]);
});
Route::patch('contact/{id}',function(Request $request, $id){
$contact = Contact::findOrFail($id);
$contact->name = $request->name;
$contact->email = $request->email;
$contact->phone = $request->phone;
$contact->save();
return $contact;
});
Route::delete('contact/{id}',function($id){
return Contact::destroy($id);
});
});

Error trying to test laravel/passport auth cicle

I'm issuing some problems with Laravel/Passport while trying to test the auth flow of my application...
The stranger thing is that it only happens when I'm on testing env. The expects the 200 http code but instead receive a 500.
I'm using the Laravel 5.8 version, I'm also have installed Horizon and Telescope. My PHP version is 7.3.4.
My test
public function testLogin()
{
$user = factory(\App\Models\User::class)->create();
$response = $this->json('post', 'v1/login', [
'email' => $user->email,
'password' => 'secret',
]);
$response->assertStatus(Response::HTTP_OK);
}
My AuthController
public function login(AuthRequest $request)
{
try {
$credentials = $request->only(['email', 'password']);
throw_if(!auth()->attempt($credentials), UnauthorizedAccess::class, __('auth.auth_required'));
$accessToken = $this->handleAccessToken($credentials);
return response()->json($accessToken);
} catch (UnauthorizedAccess $ex) {
return response()->json([
'success' => false,
'message' => $ex->getMessage()
], Response::HTTP_UNAUTHORIZED);
}
}
private function handleAccessToken(array $credentials)
{
$user = User::where(['email' => $credentials['email']])->first();
$http = new Client();
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => $user->client->id,
'client_secret' => $user->client->secret,
'username' => $credentials['email'],
'password' => $credentials['password'],
'scope' => '*',
],
]);
return json_decode((string) $response->getBody(), true);
}
This is the erro that is produced:
on terminal
1) Tests\Feature\AuthTest::testLogin
Expected status code 200 but received 500.
Failed asserting that false is true.
laravel.log
[2019-04-26 09:02:53] local.ERROR: Client authentication failed {"exception":"[object] (League\\OAuth2\\Server\\Exception\\OAuthServerException(code: 4): Client authentication failed at /home/***/workspace/***/vendor/league/oauth2-server/src/Exception/OAuthServerException.php:138)
[stacktrace]
[2019-04-26 09:02:53] testing.ERROR: Client error: `POST http://***/oauth/token` resulted in a `401 Unauthorized` response:
{"error":"invalid_client","error_description":"Client authentication failed","message":"Client authentication failed"}
{"userId":"52b19d0d-e0c5-4924-84ae-d07700c672df","exception":"[object] (GuzzleHttp\\Exception\\ClientException(code: 401): Client error: `POST http://***/oauth/token` resulted in a `401 Unauthorized` response:
{\"error\":\"invalid_client\",\"error_description\":\"Client authentication failed\",\"message\":\"Client authentication failed\"}
at /home/***/workspace/***/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113)
[stacktrace]
Well, the error seems to be something with Guzzle itself while in testing env. That happens because Guzzle is set for the default env.
Then, I solve it following the answer gave by #lawrencedawson, that you can see here

Method Illuminate\Auth\RequestGuard::attempt does not exist

I am new to both laravel and lumen.
I was creating a login api with oauth2.0 in lumen 5.6, i have installed passport and generated token.
Below is my login controller function and it is working fine. It returns token.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
//use Illuminate\Support\Facades\DB;
use App\User;
use Auth;
public function login(Request $request)
{
global $app;
$proxy = Request::create(
'/oauth/token',
'post',
[
'grant_type' => env('API_GRAND_TYPE'),
'client_id' => env('API_CLIENT_ID'),
'client_secret' => env('API_CLIENT_SECRET'),
'username' => $request->username,
'password' => $request->password,
]
);
return $app->dispatch($proxy);
}
Since i have to check user status apart from username and password, i need to check the user credential first. so i do like this.
public function login(Request $request)
{
$credentials = $request->only('username', 'password');
if (Auth::attempt($credentials)) {
return ['result' => 'ok'];
}
return ['result' => 'not ok'];
}
Here i am getting this error.
Method Illuminate\Auth\RequestGuard::attempt does not exist.
So i tried Auth::check instead of Auth::attempt.
Now there is no error but it always return false even though the credentials are valid.
I searched a lot for a solution but i didn't get.
The function guard is only available for routes with web middleware
public function login() {
if(Auth::guard('web')->attempt(['email' => $email, 'password' => $password], false, false)) {requests
// good
} else {
// invalid credentials, act accordingly
}
}
Changing default guard to "web" fixed my problem.
config/auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
using jwt it's worked for me
1-Auth::attempt($credentials)
just replace line 1 to line 2
2-$token = Auth::guard('api')->attempt($credentials)