Laravel test Passport::actingAs($user) use routes? - laravel-5

I have custom passport user login validation (i made it following this) so i make my custom /oauth/token with this route:
/routes/auth.php
Route::post('/oauth/token', [
'uses' => 'Auth\CustomAccessTokenController#issueUserToken'
]);
/app/controllers/auth/CustomAccessTokenController.php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Psr\Http\Message\ServerRequestInterface;
class CustomAccessTokenController extends Controller
{
public function issueUserToken(ServerRequestInterface $request)
{
$httpRequest = request();
if ($httpRequest->grant_type == 'password') {
$user = User::where('email', $httpRequest->username)->first();
return $this->issueToken($request);
}
}
}
If i make a manual POST request to domain.com/oauth/token is correctly handled by the custom controller but when i use Passport::actingAs($user); in a phpunit test not. This Passport::actingAs(); use the routes or have other way to get the authentication token?

You should be able to get the authentication token using
$this->actingAs($user, 'api');

Related

Laravel Auth return null

I'm using 2 routes, one for loginUsingId(1), and the second one for test if user is logged.
When try to see Auth::id(), it is ever null.
//My Routes
Route::get('/login', [\App\Http\Controllers\UserController::class,'login']);
Route::get('/test_login', [\App\Http\Controllers\UserController::class, 'getUser']);
This are the methods in UserController
namespace App\Http\Controllers;
use App\Http\Middleware\Authenticate;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function login()
{
$auth = Auth::loginUsingId(3);
return var_dump($auth); // <--- here return 3
}
public function getUser()
{
return response(['user'=>Auth::id()]);
}
you need to apply middleware to work Auth::user()
Route::get('/test_login', [\App\Http\Controllers\UserController::class, 'getUser'])->middleware('auth');
then try
If you don't want to use the default Auth middleware it's not gonna work.
Although, remember there is the
auth()->user()
method that you can try instead ; it's more convenient as you don't need to import any model to use it.

Laravel api routes not working, it's always redirecting

I am having an issue with laravel doing my backend Api.
What I am trying to do is return logged user data with Auth::user();
I wrote the controller, the route for the controller method in api.php but when I try to go to the /api/route I am redirected to Home.
I also tried to remove the __construct() method from the controller, When I do this and try to go to the /api/route, dd($user) is returning null.
My controller:
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\TeacherResource;
use Illuminate\Support\Facades\Auth;
class teacherApiController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
public function information(){
$user = Auth::user();
dd($user);
}
}
Api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('information', 'API\teacherApiController#information');
Anything I am doing wrong?
I am using the laravel authentication for register and login users.
I suppose you are not authenticated before calling this route that's why when the __construct was there it redirected you to the home, that's also why Auth::user() returns you null.
You are probably not authenticated before calling this route.
To manage the authentication you used laravel passport or even used JWT

Laravel controller / store

I am new to laravel, i am trying to store a tweet to database and i need to insert user id, but this gives me an error
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tweet;
class TweetController extends Controller
{
public function store(Request $request){
return Tweet::create([ 'tweet' => request('tweet'), 'user_id' => Auth::id()]);
}
}
error i recive:
App\Http\Controllers\Auth' not found in file
/Applications/AMPPS/www/Twitter/Twitter/app/Http/Controllers/TweetController.php
Any idea?
Yes, you are missing the import, that's why it tries to find it in the Controller location, so put
use Illuminate\Support\Facades\Auth;
// or
use Auth; // you must have the Auth alias in the config/app.php array
as an import, or use the helper function auth()->id() instead.
So instead of mass-assigning the user, you can do the following, in your User model add this:
public function tweets()
{
return $this->hasMany(Tweet::class);
}
Then in your controller just do this:
auth()->user()->tweets()->create([ 'tweet' => request('tweet') ]);
You can use auth() helper to get user id:
auth()->user()->id

Laravel - Custome Auth Throttlelogins

I have created a custom authentication and everything is working fine.
Now I am trying to add the Throttlelogins to prevent multiple incorrect login attempts. But The ThrottleLogins doesn't seem to load.
Q: What am I missing here? or am I doing something wrong?
The exception:
Method
App\Http\Controllers\Auth\CustomersLoginController::hasTooManyLoginAttempts
does not exist.
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Auth;
class CustomersLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:customers');
}
public function ShowLoginForm()
{
return view('auth.customer-login');
}
public function login(Request $request)
{
$v = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if(Auth::guard('customers')->attempt(['email'=>$request->email,'password'=>$request->password],$request->remember)){
return redirect()->intended(route('customerdashboard'));
};
return $this->sendFailedLoginResponse($request);
}
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
public function username()
{
return 'email';
}
}
Error Message
Can someone please explain what am I mssing?
The error says you are missing a function: hasTooManyLoginAttempts
In the function login you can see it's trying to call the function but it does not exist in your class. This is where it goes wrong.
update
In the AuthenticateUsers class, which you tried to copy, it's using ThrottlesLogins trait, which you are missing in your controller.
Update your controller like so:
class CustomersLoginController extends Controller
{
use ThrottlesLogins;
Another update
You tried to import the Trait which Laravel uses in their own Login. However this will not work here's why:
When you define a class, it can only have access to other classes within its namespaces. Your controller for instance is defined within the following namespace.
namespace App\Http\Controllers\Auth;
So to use other classes, you need to import them from their own namespaces so you can access them. e.g.:
use Illuminate\Foundation\Auth\ThrottlesLogins;
Now that you have imported the ThrottlesLogins, which is actually a trait, now inside the class you use it to expose all of the methods inside.

Getting this error continuously: MethodNotAllowedHttpException in RouteCollection.php line 218:

When I tried to log in, on my website. It responded with the message:
FatalErrorException in UserController.php line 37:
Class 'App\Http\Controllers\Auth' not found
But, the file there is controllers folder in Http containing Auth where there are four files.
UserController:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
//use Illuminate\Support\Facades\Flash;
use InvalidConfirmationCodeException;
use Flash;
//use Mail;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class UserController extends Controller
{
public function getDashboard()
{
return view('dashboard');
}
public function postSignUp(Request $request)
{
$email = $request['email'];
$name = $request['name'];
$password = bcrypt($request['password']);
$user = new User();
$user -> email = $email;
$user -> name = $name;
$user -> password = $password;
Auth::login('$user');
$user->save();
return redirect()->route('dashboard')
}
public function postSignIn(Request $request)
{
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
also, I am getting an error while signup:
MethodNotAllowedHttpException in RouteCollection.php line 218:
And I am trying to solve this error from a very long time but no success till now.
Please help me with both the errors.
change Auth::login($user) --> \Auth::login($user)
and let me know if you are getting anything in database after signup . :)
To get rid off
FatalErrorException in UserController.php line 37: Class
'App\Http\Controllers\Auth' not found
Add use Auth at the top
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use Auth;
Change Auth::login($User) to \Auth::login($user), your $user variable is incorrect as well.
Check your signup route, is it doing a POST (most likely it is) and you're sending a GET request?
You need add
use Auth;
to your Controller.
I highly doubt that the Auth class is inside your Controllers directory. The Auth you are looking for, is probably the Auth facade, can be included this way:
use Illuminate\Support\Facades\Auth;

Resources