<?php

namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;
use App\Exceptions\ControllerException;
//use Illuminate\Support\Facades\DB;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\DB;

class Apprialisal
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //DB::connection()->disableQueryLog();
        $headers = $request->header();
        if ($request->path() == 'api/v1/users' && request()->method() == 'POST') {
            return $next($request);
        }
        if (!isset($headers['authorization']) || empty($headers['authorization'][0])) {
            return error("请求异常:Authorization不存在",1013);
        }

        $token = substr($headers['authorization'][0],7);
        $user = DB::connection('mongodb')->collection("users")->where("token",$token)->first();

        if (empty($user)){
            return error("请求异常:Authorization不存在",1014);
        }

        try {
            $params = decrypt($token);
        } catch (DecryptException $e) {
            return error('token非法');
        }


        $idArr = ($user['_id'])->jsonSerialize();
        $_id = $idArr['$oid'];

        $request->replace(array_merge($request->all(), [
            'access_token' => substr($headers['authorization'][0], 7),
            'token_nickname' => $user['name'],
            'token_user_id' => $_id,
        ]));

        return $next($request);
    }
}
