Call to a member function setCookie() on null in middleware web - php

i used from modular structure in laravel that all module in Module folder that routes registerd in ModuleService provider with:
$this->loadRoutesFrom(__DIR__.'/../Routes/web.php');
when i not use from middleware('web') in route then csrf token return null and when i use from this middleware then when user not logined and try to show dashboard page then show error:
Call to a member function setCookie() on null in middleware
Route
Route::get('account/dashboard', [StaffController::class, 'dashboard'])
->middleware(['web','staff'])->name('staff-dashboard');
middleware:staff
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class staff
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(Auth::guard('staff')->check() == false)
{
return view('staffauth::login');
}
return $next($request);
}
}
how to resolve this problem?

Related

middleware keeps directing me to the login page

I'm working on a website where I have designed an authentication system. The client logs in through email and password. If it is correct it should proceed to the dashboard and should not be able to go back to the login page as long as he/she is logged in. However, middleware keeps directing to the login page saying that 'you have to login first'. Both middleware are registered properly in kernel.php
Kernel.php
protected $routeMiddleware = [
'alreadyLoggedIn' => \App\Http\Middleware\AlreadyLoggedIn::class,
'isLoggedIn' => \App\Http\Middleware\AuthCheck::class ];
Web.php
Route::post('/signin', [customAuthController::class,'loginClient']);
Route::get('/client',[customAuthController::class,'dashboard'])->middleware('isLoggedIn');
Route::get('/signin', [customAuthController::class, 'login'])->middleware('alreadyLoggedIn');
Route::get('/sign_up',[customAuthController::class,'registration'])>middleware('alreadyLoggedIn');
AlreadyLoggedIn (1st Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AlreadyLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId')&& (url('signin')==$request->url()|| url('sign_up')==$request->url()))
return $next($request);
return back();
}
}
IsloggedIn (2nd Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class AuthCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId'))
return redirect('signin')->with('fail','You have to login first');
return $next($request);
}
}
customAuthCheck Controller
class customAuthController extends Controller
{
public function dashboard(){
$data = array();
if(Session::has('loginId')){
$data = client::where('id','=',Session::get('loginId'))->first();
}
return view('auth.client', compact('data'));
}
public function logout(){
if(Session::has('loginId')){
Session::pull('loginId');
return redirect('signin');
}
}
}
https://github.com/faaiz99/web-tech-project
In your AuthCheck class (as you named it isLoggedIn in your kernel) first condition is not what you really want to check .
you want to redict user to login if hes not already logged in .
so condition should be something like :
if(!Session()->has('loginId'))
{
return redirect('signin')->with('fail','You have to login first');
}
addition : Its really better if you use laravel auth .
i strongly suggest you to see laravel auth docs
with laravel authentication you can simply use auth facade in your middleware and that would be something like :
if(!auth()->check())
{
return redirect('signin')->with('fail','You have to login first');
}
Hope that helps .

Trying to get property of non-object on Laravel Middleware Role

I'm trying to make middleware role for my authentication in my project, this is my middleware called sales.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Sales
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()->role == "sales"){
return $next($request);
}
return redirect()->route('login')->with('error',"You don't have an access");
}
}
and this is the route i protect from middleware
Route::get('dashboard','DashboardController#index')->middleware('sales')->name('dashboard');
and when i try to access dashboard to make sure my route is protected by middleware, it shows error like this
Trying to get property of non-object
i appreciate if you answer this !
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Sales
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::User()->role=='sales'){
return $next($request);
}
return redirect()->route('login')->with('error',"You don't have an access");
}
}

Creating Multiple Auth Providers in Lumen

I am trying to create multiple Auth Guards and services for my API. I want specific group to be available to specific users (more like RBAC without sessions).
If a user tries to access a group that has admin:auth as middleware its privileges will be checked. If it has api:auth then no privilege check.
I can't understand how to do this. I have added the following lines in the bootstrap/app.php
$app->routeMiddleware([
'admin' => App\Http\Middleware\Admin::class,
'api' => App\Http\Middleware\Api::class,
]);
And:
$app->register(App\Providers\AdminServiceProvider::class);
$app->register(App\Providers\ApiServiceProvider::class);
and created the Files Admin.php and APi.php in Middleware folder with the following content (basically same as Authenticate.php with name changes)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Admin
{
/**
* The authentication guard factory instance.
*
* #var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param \Illuminate\Contracts\Auth\Factory $auth
* #return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
And the AdminServiceProvider and ApiServiceProvider in the App\Providers folder with just this in function boot():
var_dump($this->app['api']);exit;
And this on top:
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class ApiServiceProvider extends ServiceProvider
But I get the Following Error:
What am I missing? I have already done composer dump-autoload, no difference.
Regards
Well what I ended up using is more like a work around, but I think this might be how it is supposed to be used.
So what I did was that I created two groups (a parent and a child) with the middlewares I needed as follows:
$app->group(["middleware" => "middleware1"], function() use ($app){
$app->group(["middleware" => "middleware1"], function() use ($app){
$app->post("/signin", "AppController#signin");
}
}
This way, the signin route is reached after going through 2 middlewares.
Regards

laravel how to make middleware redirect

I have create form for user to comment in my post but I want need check Auth has Login before submit the form. How can i do that ?
For me I have use middleware to protect it, But If use not login it redirect to Login Form when user has been login it is not redirect back to posts route/show-posts/{post},It redirect to back to route/comments . How can i solve this ?
URL Show Single Post
Route::get( '/show-post/{post}', 'HomePageController#single_show')
->name('home.post.show' );
URL form Comments form
Route::resource('/comments', 'CommentsController');
CommentsController
public function __construct() {
$this->middleware( 'auth')->except(['index', 'show']);
}
You can create a middleware class and redirect like so:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectToComments
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::check()) {
return redirect()->route('comments');
}
return $next($request);
}
}
That is the general form of redirection through middleware, simply modify which route to redirect to or add more conditional logic as needed.

Laravel: How to access session value in AppServiceProvider?

Is there any way available to access Session values in AppServiceProvider? I would like to share session value globally in all views.
You can't read session directly from a service provider: in Laravel the session is handled by StartSession middleware that executes after all the service providers boot phase
If you want to share a session variable with all view, you can use a view composer from your service provider:
public function boot()
{
view()->composer('*', function ($view)
{
$view->with('your_var', \Session::get('var') );
});
}
The callback passed as the second argument to the composer will be called when the view will be rendered, so the StartSession will be already executed at that point
Add new web middleware ShareDataForView
in \app\Http\Kernel.php:
protected $middlewareGroups = [
'web' => [
// ...
\Illuminate\Session\Middleware\StartSession::class,
// I will always ShareDataForView after StartSession
\App\Http\Middleware\ShareDataForView::class,
...
and write your code in method "handle" of app\Http\Middleware\ShareDataForView.php, for example:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Closure;
use Log, Exception, View;
class ShareDataForView
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Auth::user();
$bank = NULL;
if ( $user ){
$bank = $user->bank;
}
View::share('user', $user);
session()->put(['bank' => $bank]);
return $next($request);
}
}
The following works for me on Laravel 5.2, is it causing errors on your app?
AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
\Session::put('lang', 'en_US');
view()->share('lang', \Session::get('lang', 'de_DE'));
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
home.blade.php
<h1>{{$lang}}</h1>
Shows "en_US" in the browser.

Categories