<?php

namespace App\Http\Middleware;

use Closure;
use App\Http\Controllers\Core\Auth;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

/**
 * 接口请求权限中间件
 * Class Permission
 * @package App\Http\Middleware
 */
class Permission
{
    /**
     * ComplaintHandle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!in_array(config('app.env'), ['testing', 'production'])) {
            return $next($request);
        }
        try {
            $uid = Auth::auth();
        } catch (\Exception $exception) {
            $uid = 0;
        }
        $host = $_SERVER['HTTP_HOST'];
        $path = $request->route()->uri();
        $uri = DB::table('koudai.ta_permission_api')->where('host', $host)->where('path', $path)->first();
        if ($uri) {
            $permission_id = $uri->permission_id;
            if (
                !DB::table('koudai.user_permissions')->where('uid', $uid)->where(function (/** @var Builder $query */$query) use ($permission_id) {
                    return $query->whereIn('permission_id', [$permission_id, 1]);
                })->first()
            ) {
                return response([
                    'code' => 403,
                    'message' => '无权限',
                ]);
            }
        }
        return $next($request);
    }
}
