保护页面 - Laravel

Protecting pages - Laravel

在老式的 php 中,如果出于某种原因(不一定是身份验证)我想阻止访问页面,我会使用下面的代码;

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;
}

我如何在 Laravel 中实现这一目标?

谢谢

只需创建自己的中间件并将它们分配给您要保护的路由:

<?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);
    }

}

那么你需要在内核中分配这个中间件:(来自文档)

如果您希望中间件在对您的应用程序的每个 HTTP 请求期间成为 运行,只需在您的 app/Http/Kernel 的 $middleware 属性 中列出中间件 class .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,
];

所有这些之后,您将 i 分配给所需的特定网址:

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

您可以在这里阅读所有相关信息: https://laravel.com/docs/5.2/middleware#defining-middleware