/** * Handle an incoming request. * * @param Request $request * @param Closure $next * * @return mixed */ public function handle($request, Closure $next) { $validationResult = Spec::define(['content-hash' => PrimitiveTypeConstraint::forType(ScalarTypes::SCALAR_STRING), 'authorization' => PrimitiveTypeConstraint::forType(ScalarTypes::SCALAR_STRING)], [], ['content-hash', 'authorization'])->check(array_map(function ($entry) { return $entry[0]; }, $request->headers->all())); if ($validationResult->failed()) { return ApiResponse::makeFromSpec($validationResult)->toResponse(); } $authorization = str_replace('Hash ', '', $request->headers->get('Authorization')); $content = $request->getContent(); try { $pair = $this->finder->byPublicId($authorization, KeyPairTypes::TYPE_HMAC); $hasher = new HmacHasher(); $verificationResult = $hasher->verify($request->headers->get('Content-Hash'), $content . Carbon::now()->format($this->format), $pair->getSecretKey()); if ($verificationResult) { $request->attributes->set(static::ATTRIBUTE_KEYPAIR, $pair); return $next($request); } return ApiResponse::create([], ApiResponse::STATUS_INVALID, ['HMAC content hash does not match the expected hash.'])->toResponse(); } catch (ModelNotFoundException $ex) { if ($ex->getModel() === KeyPair::class) { return ApiResponse::create([], ApiResponse::STATUS_INVALID, ['Unable to locate public ID. Check your credentials'])->toResponse(); } throw $ex; } }
public function testDefineWithInvalid() { $definition = Arguments::define(PrimitiveTypeConstraint::forType(ScalarTypes::SCALAR_STRING), EitherConstraint::create(MaybeConstraint::forType(PrimitiveTypeConstraint::forType(CompoundTypes::COMPOUND_ARRAY)), PrimitiveTypeConstraint::forType(ScalarTypes::SCALAR_BOOLEAN))); $definition->check('wow', true); $definition->check('wow', []); $definition->check('wow', null); $this->setExpectedException(InvalidArgumentException::class); $definition->check('wow', 25); }
public function testCheck() { $instance = new PrimitiveTypeConstraint(CompoundTypes::COMPOUND_OBJECT); $this->assertEqualsMatrix([[false, $instance->check(null)], [false, $instance->check('hello world')], [false, $instance->check('hello world' . null)], [false, $instance->check(27645)], [false, $instance->check(276.564)], [true, $instance->check(new stdClass())]]); }