我们正在从之前创建的自定义框架迁移我们的网站到laravel 5.我们有一个生产网站以及一个开发网站。除非满足某些情况,否则是否有限制访问开发站点的简单解决方案?
我对下列方法之一感兴趣:
我正在寻找的解决方案是从开发到生产上传时我不想改变的,并希望在可能的情况下遵循以下逻辑:
if(liveSite){
Show everything, no restrictions
}elseif(developmentSite){
Hide everything, unrestrict based on logic
}
我们目前使用单独的.htaccess文件执行此操作,但我不想跟踪两个单独的文件并覆盖可能性
答案 0 :(得分:7)
您可以为此创建Middleware并使用当前配置的环境,请求IP和身份验证系统来限制访问。首先运行:
创建中间件php artisan make:middleware DevelopmentAccess
然后在新的app/Http/Middleware/DevelopmentAccess.php
文件中添加以下逻辑:
namespace App\Http\Middleware;
use Closure;
class DevelopmentAccess
{
/**
* Client IPs allowed to access the app.
* Defaults are loopback IPv4 and IPv6 for use in local development.
*
* @var array
*/
protected $ipWhitelist = ['127.0.0.1', '::1'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (app()->environment() != 'production' && $this->clientNotAllowed()) {
return abort(403, 'You are not authorized to access this');
}
return $next($request);
}
/**
* Checks if current request client is allowed to access the app.
*
* @return boolean
*/
protected function clientNotAllowed()
{
$isAllowedIP = in_array(request()->ip(), $this->ipWhitelist);
return (!$isAllowedIP && auth()->guest())
|| ($isAllowedIP && !auth()->guest());
}
}
将中间件注册到$routeMiddleware
内核的app/Http/Kernel.php
数组中:
protected $routeMiddleware = [
....
'dev' => \App\Http\Middleware\DevelopmentAccess::class,
];
然后相应地限制路线:
Route::group(['middleware' => 'dev'], function()
{
// All routes that need restricting for non-approved clients go here
});
// Routes that need access such as "login" go outside the group
get('/login', 'SessionController@login');
逻辑很简单:如果环境不是production
(非实时),并且用户IP已列入白名单或用户已通过身份验证,则他们可以访问。