Laravel 8 Class 'Laravel\Fortify\Actions\Auth' not found - php

I'm trying to make an e-commerce admin/user authentication I use laravel 8 went register a test account and logged in and this error occured.
Error
Class 'Laravel\Fortify\Actions\Auth' not found
After i logged in a test account it was supposed to result like this
https://ibb.co/Vq5LxBk
C:\Users\ACER\laravel8ecommerce\vendor\laravel\fortify\src\Actions\AttemptToAuthenticate.php:58
This was the line 58
if(Auth::user()->utype === 'ADM')
My code on AttemptToAuthenticate.php
<?php
namespace Laravel\Fortify\Actions;
use Illuminate\Auth\Events\Failed;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\LoginRateLimiter;
class AttemptToAuthenticate
{
/**
* The guard implementation.
*
* #var \Illuminate\Contracts\Auth\StatefulGuard
*/
protected $guard;
/**
* The login rate limiter instance.
*
* #var \Laravel\Fortify\LoginRateLimiter
*/
protected $limiter;
/**
* Create a new controller instance.
*
* #param \Illuminate\Contracts\Auth\StatefulGuard $guard
* #param \Laravel\Fortify\LoginRateLimiter $limiter
* #return void
*/
public function __construct(StatefulGuard $guard, LoginRateLimiter $limiter)
{
$this->guard = $guard;
$this->limiter = $limiter;
}
/**
* Handle the incoming request.
*
* #param \Illuminate\Http\Request $request
* #param callable $next
* #return mixed
*/
public function handle($request, $next)
{
if (Fortify::$authenticateUsingCallback) {
return $this->handleUsingCustomCallback($request, $next);
}
if ($this->guard->attempt(
$request->only(Fortify::username(), 'password'),
$request->filled('remember'))
) {
if(Auth::user()->utype === 'ADM')
{
session(['utype'=>'ADM']);
return redirect(RouteServiceProvider::HOME);
}
elseif(Auth::user()->utype === 'USR')
{
session(['utype'=>'USR']);
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
$this->throwFailedAuthenticationException($request);
}
/**
* Attempt to authenticate using a custom callback.
*
* #param \Illuminate\Http\Request $request
* #param callable $next
* #return mixed
*/
protected function handleUsingCustomCallback($request, $next)
{
$user = call_user_func(Fortify::$authenticateUsingCallback, $request);
if (! $user) {
$this->fireFailedEvent($request);
return $this->throwFailedAuthenticationException($request);
}
$this->guard->login($user, $request->filled('remember'));
return $next($request);
}
/**
* Throw a failed authentication validation exception.
*
* #param \Illuminate\Http\Request $request
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
protected function throwFailedAuthenticationException($request)
{
$this->limiter->increment($request);
throw ValidationException::withMessages([
Fortify::username() => [trans('auth.failed')],
]);
}
/**
* Fire the failed authentication attempt event with the given arguments.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function fireFailedEvent($request)
{
event(new Failed(config('fortify.guard'), null, [
Fortify::username() => $request->{Fortify::username()},
'password' => $request->password,
]));
}
My Routes (web php)
<?php
use App\Http\Livewire\CartComponent;
use App\Http\Livewire\CheckoutComponent;
use App\Http\Livewire\HomeComponent;
use App\Http\Livewire\ShopComponent;
use App\Http\Livewire\User\UserDashboardComponent;
use App\Http\Livewire\Admin\AdminDashboardComponent;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
Route::get('/',HomeComponent::class);
Route::get('/shop',ShopComponent::class);
Route::get('/cart',CartComponent::class);
Route::get('/checkout',CheckoutComponent::class);
// Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
// return view('dashboard');
// })->name('dashboard');
// For User or Customer
Route::middleware(['auth:sanctum', 'verified'])->group(function(){
Route::get('user/dashboard',UserDashboardComponent::class,)->name('user.dashboard');
});
// For Admin
Route::middleware(['auth:sanctum', 'verified','authadmin'])->group(function(){
Route::get('admin/dashboard',AdminDashboardComponent::class,)->name('admin.dashboard');
});
I would really appreciate a help i'm doing this for my project on school

use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;
from to vendor\laravel\fortify\src\Actions\AttemptToAuthenticate
but you must remove line :
use Laravel\Fortify\Actions\RouteServiceProvider;
Because this line is duplicate for RouteServiceProvider.... but maybe just for my project

use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;
put these two on top of
vendor\laravel\fortify\src\Actions\AttemptToAuthenticate

adding two lines on the top of AttemptToAuthenticate.php file
use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;

For future users;
On AttemptToAuthenticate.php, right under AttemptToAuthenticate.php,
add use Auth;
it will still throw an error class '\laravel\fortify\actions\RouteServiceProvider' not found!
To solve this,
Simply add
use App\Providers\RouteServiceProvider;, to direct it to the default
RouteServiceProvider class.

add
use Illuminate\Support\Facades\Auth;
in class vendor\laravel\fortify\src\Actions\AttemptToAuthenticate

<?php
namespace Laravel\Fortify\Actions;
use Illuminate\Auth\Events\Failed;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\LoginRateLimiter;
use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;
class AttemptToAuthenticate
{
/**
* The guard implementation.
*
* #var \Illuminate\Contracts\Auth\StatefulGuard
*/
protected $guard;
/**
* The login rate limiter instance.
*
* #var \Laravel\Fortify\LoginRateLimiter
*/
protected $limiter;
/**
* Create a new controller instance.
*
* #param \Illuminate\Contracts\Auth\StatefulGuard $guard
* #param \Laravel\Fortify\LoginRateLimiter $limiter
* #return void
*/
public function __construct(StatefulGuard $guard, LoginRateLimiter $limiter)
{
$this->guard = $guard;
$this->limiter = $limiter;
}
/**
* Handle the incoming request.
*
* #param \Illuminate\Http\Request $request
* #param callable $next
* #return mixed
*/
public function handle($request, $next)
{
if (Fortify::$authenticateUsingCallback) {
return $this->handleUsingCustomCallback($request, $next);
}
if ($this->guard->attempt(
$request->only(Fortify::username(), 'password'),
$request->filled('remember'))
) {
if(Auth::user()->utype === 'ADM')
{
session(['utype'=>'ADM']);
return redirect(RouteServiceProvider::HOME);
}
elseif(Auth::user()->utype === 'USR')
{
session(['utype'=>'USR']);
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
$this->throwFailedAuthenticationException($request);
}
/**
* Attempt to authenticate using a custom callback.
*
* #param \Illuminate\Http\Request $request
* #param callable $next
* #return mixed
*/
protected function handleUsingCustomCallback($request, $next)
{
$user = call_user_func(Fortify::$authenticateUsingCallback, $request);
if (! $user) {
$this->fireFailedEvent($request);
return $this->throwFailedAuthenticationException($request);
}
$this->guard->login($user, $request->filled('remember'));
return $next($request);
}
/**
* Throw a failed authentication validation exception.
*
* #param \Illuminate\Http\Request $request
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
protected function throwFailedAuthenticationException($request)
{
$this->limiter->increment($request);
throw ValidationException::withMessages([
Fortify::username() => [trans('auth.failed')],
]);
}
/**
* Fire the failed authentication attempt event with the given arguments.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function fireFailedEvent($request)
{
event(new Failed(config('fortify.guard'), null, [
Fortify::username() => $request->{Fortify::username()},
'password' => $request->password,
]));
}
}

use Illuminate\Support\Facades\Auth;
This line should be added at the top of the AttemptAuthenticate.php file.

I had the same error and i solved by adding these lines. use Illuminate\Support\Facades\Auth; use App\Providers\RouteServiceProvider;

Add this to your AttemptToAuthenticate.php file.
use Illuminate\Support\Facades\Auth;
This works fine for me.

Related

User auth not working properly for tenant while using Stancl\Tenancy

I'm using Laravel 9 with Breeze and below is all the modifications. What I did was set the session_driver to database instead of file. Right now I am using subdomains for users but later on ill be adding the ability to buy and set a domain for each tenant so that is why im using the subdomainOrDomain middleware instead of just the domain middleware by stancl. My problem is that the auth session wont be set and i dont see any entries in the tenants database within the table sessions. So no session gets set at all. The central domain also has auth and it works perfectly but just not the tenant.
App\Http\Kernel.php
protected $middlewareGroups = [
//...
'tenant' => [
\App\Http\Middleware\InitializeTenancyByDomainOrSubdomain::class,
\Stancl\Tenancy\Middleware\PreventAccessFromCentralDomains::class,
],
'universal' => [],
];
App\Http\Middlware\InitializeTenancyByDomainOrSubdomain
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Str;
use App\Http\Middleware\InitializeTenancyByDomain;
use App\Http\Middleware\InitializeTenancyBySubdomain;
class InitializeTenancyByDomainOrSubdomain
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->isSubdomain($request->getHost()))
{
return app(InitializeTenancyBySubdomain::class)->handle($request, $next);
}
else
{
return app(InitializeTenancyByDomain::class)->handle($request, $next);
}
}
protected function isSubdomain(string $hostname): bool
{
return Str::endsWith($hostname, config('tenancy.central_domains'));
}
}
App\Http\Middlware\InitializeTenancyByDomain
namespace App\Http\Middleware;
use Closure;
use Stancl\Tenancy\Tenancy;
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
use Stancl\Tenancy\Middleware\IdentificationMiddleware;
class InitializeTenancyByDomain extends IdentificationMiddleware
{
/** #var callable|null */
public static $onFail;
/** #var Tenancy */
protected $tenancy;
/** #var DomainTenantResolver */
protected $resolver;
public function __construct(Tenancy $tenancy, DomainTenantResolver $resolver)
{
$this->tenancy = $tenancy;
$this->resolver = $resolver;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(in_array($request->getHost(), config('tenancy.central_domains'), true))
{
return $next($request);
}
return $this->initializeTenancy(
$request, $next, $request->getHost()
);
}
}
App\Http\Middlware\InitializeTenancyBySubdomain
namespace App\Http\Middleware;
use Closure;
use Exception;
use Illuminate\Support\Str;
use Illuminate\Http\Response;
use Stancl\Tenancy\Exceptions\NotASubdomainException;
class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
{
/**
* The index of the subdomain fragment in the hostname
* split by `.`. 0 for first fragment, 1 if you prefix
* your subdomain fragments with `www`.
*
* #var int
*/
public static $subdomainIndex = 0;
/** #var callable|null */
public static $onFail;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(in_array($request->getHost(), config('tenancy.central_domains'), true))
{
return $next($request);
}
$subdomain = $this->makeSubdomain($request->getHost());
if (is_object($subdomain) && $subdomain instanceof Exception) {
$onFail = static::$onFail ?? function ($e) {
throw $e;
};
return $onFail($subdomain, $request, $next);
}
// If a Response instance was returned, we return it immediately.
if (is_object($subdomain) && $subdomain instanceof Response) {
return $subdomain;
}
return $this->initializeTenancy(
$request,
$next,
$request->getHost()
);
}
/** #return string|Response|Exception|mixed */
protected function makeSubdomain(string $hostname)
{
$parts = explode('.', $hostname);
$isLocalhost = count($parts) === 1;
$isIpAddress = count(array_filter($parts, 'is_numeric')) === count($parts);
// If we're on localhost or an IP address, then we're not visiting a subdomain.
$isACentralDomain = in_array($hostname, config('tenancy.central_domains'), true);
$notADomain = $isLocalhost || $isIpAddress;
$thirdPartyDomain = ! Str::endsWith($hostname, config('tenancy.central_domains'));
if ($isACentralDomain || $notADomain || $thirdPartyDomain) {
return new NotASubdomainException($hostname);
}
return $parts[static::$subdomainIndex];
}
}
Routes\Tenant.php
Route::middleware(['tenant', 'web'])->group(function()
{
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
});
in the tenant routes i have also tried switching the web middleware to guest as is by default with laravel breeze but it trows the $errors not found error (the validation handling variable).

Laravel - Calling Service Class from Middleware - Class App\Http\Middleware\** does not exist

So i've got some middleware here:
namespace App\Http\Middleware;
use Closure;
use App\ChatLog;
use App\Http\Services;
class LogChat
{
protected $chatLogService;
public function __construct(ChatLogService $chatLogService)
{
$this->chatLogService = $chatLogService;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$chatLog = new ChatLog;
$chatLog->companyid = '5';
$chatLog->type = 'REQUEST';
$chatLog->ipaddress = '1';
$chatLog->name = 'bob';
$chatLog->message = 'testmessage';
$chatLog->action = 'click';
$chatLog->timeTaken = '1';
$chatLog->fullLog = 'all the log';
$this->chatLogService->store($chatLog);
return $next($request);
}
}
which calls this service here:
namespace App\Http\Services;
use App\ChatLog;
use Illuminate\Support\Facades\DB;
class ChatLogService
{
/**
* Display a listing of the resource.
*
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \App\ChatLog $chatLog
*/
public function store(ChatLog $chatLog)
{
$chatLog->save();
}
/**
* Display the specified resource.
*
* #param \App\ChatLog $chatLog
*/
public function show(ChatLog $chatLog)
{
//
}
}
which is injected in here:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->bind(ChatLogService::class, function ($app) {
return new ChatLogService();
});
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
}
But this gives me the following exception: ReflectionException
Class App\Http\Middleware\ChatLogService does not exist
What i want to do is call the "store" method in a nicely abstracted way and i feel this solution is very close - however, I can't seem to get around this error. I'm not sure if it's something simple that i'm missing, or if the approach is fundamentally wrong!
I can't see what's wrong!
Ta :)

Middleware function doesnt exist

In my web.php I have a route
Route::get('summary_average_fee', 'Summary#AverageFee')->middleware('CheckParams#dateLimits');
Im trying to refrence the dateLimits function in the CheckParams class
My CheckParams class, saved as CheckParams.php in the Middleware folder
<?php
namespace App\Http\Middleware;
use Closure;
class CheckParams
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function dateLimits($request, Closure $next)
{
isEmpty($request->input('startDate'), 'NO_START_DATE');
isEmpty($request->input('endDate'), 'NO_END_DATE');
return $next($request);
}
private function isEmpty($value, $error, $status)
{
if(empty($value))
{
return response()->json($error, 422);
}
}
}
In the kernal.php file I add this to the routeMiddleware array
'CheckParams' => \App\Http\Middleware\CheckParams::class
When it runs, I get the error that Class CheckParams#dateLimits does not exist
Seems to me that your middleware should be rewritten and update the usage:
use App\Http\Middleware\CheckParams;
Route::get('summary_average_fee', 'Summary#AverageFee')->middleware(CheckParams::class);
Middleware:
namespace App\Http\Middleware;
use Closure;
class CheckParams
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$this->isEmpty($request->input('startDate'), 'NO_START_DATE');
$this->isEmpty($request->input('endDate'), 'NO_END_DATE');
return $next($request);
}
private function isEmpty($value, $error, $status)
{
if(empty($value))
{
return response()->json($error, 422);
}
}
}

Laravel index policy

I using Laravel 5.4 and I am trying to write a policy for my index view. I am trying to use a Method Without a Model, I am receiving the following error:
HttpException in Handler.php line 133:
This action is unauthorized.
Here is my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\County;
use Session;
use App\Http\Controllers\Controller;
class CountyController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$counties = County::orderBy('id', 'desc')->paginate(5);
$this->authorize('index');
return view('county.index', array(
'counties' => $counties
));
}
Here is my AuthServicePovider:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Role;
use App\County;
use App\Policies\CountyPolicy;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
County::class => CountyPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('is-Admin', function ($user) {
if($user->roles()->where('name','Admin')->first()){
return true;
}
return false;
});
}
}
Here is my Policy:
<?php
namespace App\Policies;
use App\User;
use App\Role;
use App\County;
use Illuminate\Auth\Access\HandlesAuthorization;
class CountyPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function index(User $user)
{
$userRoles = $user->getRoleNames();
$acceptedRoles = ['Sudo','Admin'];
$testArr = array_intersect($acceptedRoles, $userRoles);
dd($testArr);
if(!empty($testArr)){
return true;
}
return false;
//
}
/**
* Determine whether the user can view the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function view(User $user, County $county)
{
$userRoles = $user->getRoleNames();
$acceptedRoles = ['Sudo','Admin','Client'];
$testArr = array_intersect($acceptedRoles, $userRoles);
if(!empty($testArr)){
return true;
}
return false;
//
}
/**
* Determine whether the user can create counties.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function update(User $user, County $county)
{
//
}
/**
* Determine whether the user can delete the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function delete(User $user, County $county)
{
//
}
}
I never get to dd($testArr) in the index policy. Also the view policy is working perfectly.
How do I write a policy for my index view?
keeping everything the same but changing:
$this->authorize('index');
to
$this->authorize('index', County::class);
fixed the problem. Apparently the model class needs to be passed on actions that don't require a model. This is only described under the middleware section of Laravel's docs, not the controller helpers... A little confusing.

Can't get user_context to pass into Sentry with Laravel 5.1

My goal is to pass User Context like email or ID into Sentry so I can see which users broke something.
I've configured a piece of Global Middleware to add user context to my Sentry errors. Here is the class:
class AddUserToSentry
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user())
{
//dd(Auth::user()->email);
app('sentry')->user_context(array(
'email' => Auth::user()->email
));
}
return $next($request);
}
}
In my Handler.php I have:
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* #param \Exception $e
* #return void
*/
public function report(Exception $e)
{
if ($this->shouldReport($e)) {
app('sentry')->captureException($e);
}
parent::report($e);
}
What am I missing to make this work? All I get for user context is the IP address, which is not very helpful in my case.
Thank you very much,
Josh
Here is a complete example, the source is from the official Sentry documentation. To avoid having to add use Auth; you can simply use the auth() helper function.
namespace App\Http\Middleware;
use Closure;
class SentryContext
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
*
* #return mixed
*/
public function handle($request, Closure $next)
{
if (app()->bound('sentry')) {
/** #var \Raven_Client $sentry */
$sentry = app('sentry');
// Add user context
if (auth()->check()) {
$sentry->user_context(['id' => auth()->user()->id, 'email' => auth()->user()->email]);
}
// Add tags context
// $sentry->tags_context(['foo' => 'bar']);
}
return $next($request);
}
}
You need to provide access to Laravel's Auth Facade in your controller like so:
Use Auth;

Categories