Laravel load middleware in routes under condition - laravel

I have a route files for my api and im using this package to cache the whole response.
routes/api.php
<?php
Route::get('/types', 'TypeController#indexType')->middleware('cacheResponse:600');
This works fine but i need to skip this middleware loading when i have a specific header in the request so i make this extra middleware
conditionalCacheResponse.php
<?php
namespace App\Http\Middleware;
use Closure;
class ConditionalCacheResponse
{
public function handle($request, Closure $next)
{
if (request()->header('Draft') != true) {
$this->middleware('cacheResponse:3600');
}
return $next($request);
}
}
and setup like this
routes/api.php
<?php
Route::get('/types', 'TypeController#indexType')->middleware('conditionalCacheResponse');
But is not working, im not sure if i can append a middleware in this way.

There's a few ways to do this, one way would be to use the handle() method of the HttpKernel to unset the CacheResponse middleware based on a check of the request header.
So in app/Http/Kernel.php, add this method:
public function handle($request)
{
if ($request->header('Draft')) {
if (($key = array_search('Spatie\ResponseCache\Middlewares\CacheResponse', $this->middleware)) !== false) {
unset($this->middleware[$key]);
}
}
return parent::handle($request);
}
I haven't checked this is working, but it should do the job.

Related

Laravel-redirects even authenticated users to login

Before minus this question, or report a duplicate, please read it completely.
I use a default Laravel Autentification. But for some reason, it's somehow broke down.
When I try to login or register, if auth is success it redirects try to redirects me to a correct link, but but at the same time returns me to /login.
Example with dump
Debugbar after trying auth
Source files
1. My routes:
Auth::routes();
Route::get('/confirm', function () {
return view('confirm');
})->name('confirm');
Route::post('/confirm', 'EmployeeController#store')->name('addworker');
Route::get('users/{id}', 'EmployeeController#show')->where('id', '[0-9]+')->name('account');
Route::get('/home', 'HomeController#index')->name('home');
2. Changes into login and register controllers:
protected function redirectTo()
{
return route('account',['id'=> auth()->user()->id]);
}
3.Methods in a EmployeeController, that action in auth:
public function __construct()
{
$this->middleware('auth');
$this->middleware('confirmated');
}
public function show($id)
{
return view('account');
}
4. My middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\Employee;
class CheckConfirm
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
$id = Auth::id();
$empl = Employee::where('user_id', '=', $id)->first();
Debugbar::info($empl);
if ($empl == null) {
return redirect()->route('confirm');
} else {
dump($empl);
return $next($request);
}
} else {
return redirect()->route('login');
}
}
}
What did not help me
clearing the cache and browser history including the artisan commands: cache:clear and config:clean
Disable my middleware or auth midlleware in controllers constructor
Disable all middleware in contructor led to this
Solutions in question duplicates, or in other forums
If there is not enough information in the question, you can download my entire project on GitHub: https://github.com/Vladislav2018/last.chance/

Laravel set cookie not working

I have the following code in a custom middleware:
public function handle($request, Closure $next)
{
if($request->hasCookie('uuid')) {
return $next($request);
}
$uuid = 99;
$response = $next($request);
return $response->withCookie(cookie()->forever('uuid', $uuid));
}
I have registered the middleware in the app.php file, but cookies is still not being written. Please can anyone help. Additionally can this above be run as a singleton, so that it is executed once on app start?
Thanks
If you are on a local environment, make sure to set 'secure' => env('SESSION_SECURE_COOKIE', false), around lines #165-170 in your config/session.php file.
On a non-SSL domain (like http://localhost/), this directive must be false. Otherwise cookies will not be set in browser.
Here, I'm mention set and get a cookie in laravel simple example following.
First of the create a controller.
1.php artisan make:controller CookieController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CookieController extends Controller {
**/* below code a set a cookie in browser */**
public function setCookie(Request $request){
$response = new Response('Hello World');
$response->withCookie(cookie('name', 'Anything else'));
return $response;
}
**/* below code a get a cookie in browser */**
public function getCookie(Request $request){
$value = $request->cookie('name');
echo $value;
}
}
Add a following line code in routes/web.php file (Laravel 5.4)
Route::get('/cookie/set','CookieController#setCookie');
Route::get('/cookie/get','CookieController#getCookie');
And all files add-in project than a run program easily sets and get a cookie.
You can obtain the response object in middleware like so:
public function handle($request, Closure $next)
{
$response = $next($request);
// Do something after the request is handled by the application
return $response;
}
So you could do something like this
if($request->hasCookie('uuid')) {
return $next($request);
}
$uuid = Uuid::generate();
$response = $next($request);
return $response->withCookie(cookie()->forever('uuid', $uuid));
You can use the laravel helper function cookie(). This worked for me.
<?php
//Create:
cookie()->queue(cookie($name, $value, $minutes));
// forever
cookie()->queue(cookie()->forever($name, $value));
//get
request()->cookie($name);
//forget
cookie()->queue(cookie()->forget($name));

Laravel: how to check middleware in blade template

i've created Middleware
php artisan make:middleware isTeacher
in App/Http/isTeacher.php i've placed the check:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class isTeacher
{
public function handle($request, Closure $next)
{
$user = Auth::user();
if($user && $user->capability == 3)
{
return $next($request);
}
else
return redirect('/login');
}
}
than, i've defined the middleware in app/Http/Kernel.php
protected $routeMiddleware = [
...
'auth.teacher' => \App\Http\Middleware\isTeacher::class,
...
];
The question is: how I check the teacher capability in blade template?
I'm trying with this:
#if (Auth::isTeacher())
but doesn't work
any help are appreciated
The blade directive only needs to return true or false, nothing else.
You could just do the following in the boot() method of the AppServiceProvider.php
Blade::if('teacher', function () {
return auth()->user() && $user->capability == 3;
});
Then you will be able to do the following in blade templates:
#teacher
Only teachers will see this
#endteacher
Well there is an issue here Middlewares are used to filter HTTP requests or its outter layer of the onion in laravel app. It is not defined to be used in blade to decide which part of html should be rendered.
You can filter a controller function to only be usable if it passes the middleware (if authenticated for example) and the controller only runs the function if it passes on the middleware.
When using Auth in blades you are not using a middleware but a facade whan you could do its use Session for your case like:
In your middleware
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class isTeacher
{
public function handle($request, Closure $next)
{
$user = Auth::user();
if($user && $user->capability == 3)
{
\session('isTeacher', true);
return $next($request);
}
return redirect('/login');
}
Then in your blades do like:
#if (Session::get('isTeacher', 0));
This will show content only to teachers, if session its not set it will fall back to 0 or false.
In this scenario, using middleware is not really the solution. I will rather suggest blade directive, which allows you to create a custom blade function like:
#author
//Do something
#else
//Something else
#endauthor
To use the above syntax, you can register a new blade directive in your AppServiceProvider.php file
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('author', function () {
$isAuth = false;
// check if the user authenticated is teacher
if (auth()->user() && auth()->user()->capability == 3) {
$isAuth = true;
}
return "<?php if ($isAuth) { ?>";
});
Blade::directive('endauthor', function () {
return "<?php } ?>";
});
}
}
After the above changes in the AppServiceProvider.php file, run php artisan view:clear
For a better understanding, you can refer to the documentation here
This is an improved version of Prince Lionel's answer. Pay attention to the return value of Blade::directive callback function.
#author
//Do something
#else
//Something else
#endauthor
AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('author', function () {
$isAuth = false;
// check if the user authenticated is teacher
if (auth()->user() && auth()->user()->capability == 3) {
$isAuth = true;
}
return "<?php if (" . intval($isAuth) . ") { ?>";
});
Blade::directive('endauthor', function () {
return "<?php } ?>";
});
}
}

How do i make a page unaccessible when a session is set with middleware laravel 5.4

I'm trying to make a page unaccessible when a session is set in laravel
The middleware i tried is App\Http\Middleware\TwoStep.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class TwoStep
{
public function handle($request, Closure $next)
{
if (Auth::user()) {
if (session('validate') === 'true') {
back();
} else {
return redirect('/auth');
}
} else {
return redirect('/login');
}
}
}
the way i tried to use the middleware :
Route::get('/auth', 'AuthController#index')->middleware('twostep');
This gave me a redirect loop though.
Unless back() is a helper you have created, it should be:
return redirect()->back();

Laravel : run specific middleware after Auth middleware

I've created a middleware that should be run for every request so i added that to $middleware property of Http\Kernel . I've also used Auth::check() inside this middleware , so my middleware should be run after Auth middleware unless Auth::check() will not work, how should i do that?
As far as i understand, you have already do that.
You should put your code into Auth::check() statement like below:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Test
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
// your logic here
}
return $next($request);
}
}

Resources