手順

  • \App\Http\Middleware\IPAuthMiddleware を作成
  • \App\Http\Kernel に登録
  • Herokuの Config Variables にIPアドレスをカンマ区切りで追加

ポイント

  • Heroku上のAppではIPアドレスを取得するときは先に setTrustedProxies を通す
IPAuthMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class IPAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $isPrd = !$this->isDebug();
        $isDenied = !$this->whetherThisIpAccepted();
        if ($isPrd && $isDenied) {
            return Response::create(view("errors.403"), 403);
        }
        return $next($request);
    }

    protected function isDebug()
    {
        if (env('APP_DEBUG') !==  true) {
            return false;
        }
        return true;
    }

    protected function whetherThisIpAccepted()
    {
        $ipArr = explode(',', env("APP_IP_chatbox", ""));
        \Request::setTrustedProxies([\Request::ip()]);

        if ($ipArr && !in_array(\Request::ip(), $ipArr)) {
            return false;
        }
        return true;
    }
}

参考

https://www.messiahworks.com/archives/14930
http://pdo99.hatenablog.com/entry/2017/06/27/175316

その他の手法

https://stackoverflow.com/questions/18264304/get-clients-real-ip-address-on-heroku/18517550#18517550

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.