Protecting pages - Laravel

- 1 answer

Ad

In old fashioned php, if I wanted to prevent access to a page for some reason (not necessarily authentication) I would use the code below;

if (!isset($_GET["token"])) {
    header("Location: password-link-invalid.html");
    exit;
}

if (!isset($_GET["timestamp"])) {
    header("Location: password-link-invalid.html");
    exit;
}

if ($_SERVER["REQUEST_TIME"] - $timestamp > 3600)
{
    header("Location: password-link-expired.html");
    exit;
}

How would I achieve this in Laravel?

Thanks

Ad

Answer

Ad

simply create yourself middlewares and assign them to the routes you want to protect:

<?php

namespace App\Http\Middleware;

use Closure;

class TokenDateCheckerMiddleware
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (is_null($request->input('token')) ||
            is_null($request->input('timestamp'))) {

            return redirect('password-link-invalid.html');
        }

        return $next($request);
    }

}

then you will need to assign this middleware in the kernel: (from docs)

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'tokenDateCheck' => \App\Http\Middleware\TokenDateCheckerMiddleware::class,
];

and after all of that, you assign i to the specific urls needed:

Route::get('admin/profile', ['middleware' => 'tokenDateCheck', function () {
    //
}]);

you can read all about it here: https://laravel.com/docs/5.2/middleware#defining-middleware

Ad
source: stackoverflow.com
Ad