schnittstabil/psr7-csrf-middleware

View on GitHub
src/MiddlewareBuilder.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php

namespace Schnittstabil\Psr7\Csrf;

use Schnittstabil\Csrf\TokenService\TokenService;
use Schnittstabil\Csrf\TokenService\TokenServiceInterface;

/**
 * CSRF protection middleware builder.
 */
class MiddlewareBuilder
{
    /**
     * TokenService for building.
     *
     * @var TokenServiceInterface
     */
    protected $tokenService;

    /**
     * Middleware class.
     *
     * @var string
     */
    protected $middlewareClass;

    /**
     * Create a new MiddlewareBuilder.
     *
     * @param TokenService $tokenService    TokenService for building
     * @param string       $middlewareClass Middleware class
     */
    public function __construct(TokenService $tokenService, $middlewareClass = Middleware::class)
    {
        $this->tokenService = $tokenService;
        $this->middlewareClass = $middlewareClass;
    }

    /**
     * Create a new MiddlewareBuilder.
     *
     * `$ttl` is used for calculating the expiration time of the tokens, its default value (1440sec === 24min)
     * correspond to the default `session.gc_maxlifetime`.
     *
     * @see http://php.net/manual/en/session.configuration.php Documentation of `session.gc-maxlifetime`
     *
     * @param string $key             Shared secret key used for generating token signatures
     * @param int    $ttl             Default Time to Live in seconds
     * @param string $algo            Name of hashing algorithm. See hash_algos() for a list of supported algorithms
     * @param string $middlewareClass Middleware class
     *
     * @return static
     */
    public static function create(
        $key,
        $ttl = 1440,
        $algo = 'SHA512',
        $middlewareClass = Middleware::class
    ) {
        return new self(new TokenService($key, $ttl, $algo), $middlewareClass);
    }

    /**
     * Build a AngularJS compatible stateless Cookie-To-Header CSRF proptection middleware.
     *
     * + Sends tokens via cookies
     * + Accepts tokens via request headers
     * + Always accepts GET requests
     *
     * @param string   $cookieName       Cookie name
     * @param string   $headerName       Header field name
     * @param callable $rejectMiddleware See `\Schnittstabil\Psr7\Csrf\Middlewares\Guard` for details
     * @param callable $cookieModifier   See `Schnittstabil\Psr7\Csrf\Middlewares\RespondWithCookieToken` for details
     *
     * @return static
     */
    public function buildCookieToHeaderMiddleware(
        $cookieName = 'XSRF-TOKEN',
        $headerName = 'X-XSRF-TOKEN',
        callable $rejectMiddleware = null,
        callable $cookieModifier = null
    ) {
        return (new $this->middlewareClass($this->tokenService))
            ->withGuard($rejectMiddleware)
            ->withAcceptHeaderToken($headerName)
            ->withAcceptMethods(['GET', 'OPTIONS'])
            ->withRespondWithCookieToken($cookieName, $cookieModifier);
    }

    /**
     * Build a stateless Header-To-Header CSRF proptection middleware.
     *
     * + Sends tokens via headers
     * + Accepts tokens via request headers
     * + Always accepts GET requests
     *
     * @param string   $responseHeaderName Response header field name
     * @param string   $requestHeaderName  Request header field name
     * @param callable $rejectMiddleware   See `\Schnittstabil\Psr7\Csrf\Middlewares\Guard` for details
     *
     * @return static
     */
    public function buildHeaderToHeaderMiddleware(
        $responseHeaderName = 'XSRF-TOKEN',
        $requestHeaderName = 'X-XSRF-TOKEN',
        callable $rejectMiddleware = null
    ) {
        return (new $this->middlewareClass($this->tokenService))
            ->withGuard($rejectMiddleware)
            ->withAcceptHeaderToken($requestHeaderName)
            ->withAcceptMethods(['GET', 'OPTIONS'])
            ->withRespondWithHeaderToken($responseHeaderName);
    }

    /**
     * Build a stateless Synchronizer Token Pattern CSRF proptection middleware.
     *
     * + Accepts tokens via request body (`ServerRequestInterface::getParsedBody`)
     * + Always accepts GET requests
     * + Tokens have to be generated by `getTokenService()->generate()` and manually rendered into HTML/JSON or XML.
     *
     *
     * @see https://github.com/schnittstabil/get Documentation of `Schnittstabil\Get\getValue`
     * @see http://www.php-fig.org/psr/psr-7     Documentation of `ServerRequestInterface::getParsedBody`
     *
     * @param string|int|mixed[] $path             a `Schnittstabil\Get\getValue` path
     * @param callable           $rejectMiddleware See `\Schnittstabil\Psr7\Csrf\Middlewares\Guard` for details
     *
     * @return static
     */
    public function buildSynchronizerTokenPatternMiddleware(
        $path = 'X-XSRF-TOKEN',
        callable $rejectMiddleware = null
    ) {
        return (new $this->middlewareClass($this->tokenService))
            ->withGuard($rejectMiddleware)
            ->withAcceptParsedBodyToken($path)
            ->withAcceptMethods(['GET', 'OPTIONS']);
    }
}