<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends Middleware
{
    protected $except = [];
    
    protected function tokensMatch($request)
    {
        $token = $this->getTokenFromRequest($request);
        
        if (!is_string($request->session()->token())) {
            throw new TokenMismatchException('CSRF session token missing');
        }
        
        if (!is_string($token)) {
            throw new TokenMismatchException('CSRF request token missing');
        }
        
        return hash_equals($request->session()->token(), $token);
    }
    
    protected function getTokenFromRequest($request)
    {
        $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
        
        if (!$token && $header = $request->header('X-XSRF-TOKEN')) {
            try {
                $token = $this->encrypter->decrypt($header);
            } catch (\Exception $e) {
                return null;
            }
        }
        
        return $token;
    }
}