tokens = $tokens; } /** * Declaring the token routes. * * @return array> Route path => arguments. */ protected function routes(): array { $args = array( 'methods' => 'POST', 'callback' => array( $this, 'issue_token' ), // Cannot require a token here, so the API key and secret are verified instead. 'permission_callback' => array( $this, 'require_credentials' ), 'args' => array( 'api_key' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'api_secret' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), ), ); return array( '/oauth/token' => $args, '/oauth2/token' => $args, ); } /** * Issuing an access token. * * @param WP_REST_Request>|WP_REST_Request $request Incoming request. * * @return WP_REST_Response The token, or a 500 when it could not be stored. */ public function issue_token( $request ): WP_REST_Response { unset( $request ); $token = $this->token_repository()->issue(); if ( null === $token ) { return Response::message( __( 'Could not issue an access token', 'kordiam' ), 500 ); } $response = Response::ok( array( 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => Config::TOKEN_TTL, ) ); return $this->apply_cross_origin_header( $response ); } /** * Adding a cross-origin header when the site asks for one. * * @param WP_REST_Response $response Response to decorate. * * @return WP_REST_Response The response. */ private function apply_cross_origin_header( WP_REST_Response $response ): WP_REST_Response { /** * Filters the Access-Control-Allow-Origin header on the token endpoint. * * Defaults to an empty string, which sends no header. * * @param string $origin Origin to allow. */ $origin = (string) apply_filters( 'kordiam_access_control_allow_origin', '' ); if ( '' !== $origin ) { $response->header( 'Access-Control-Allow-Origin', $origin ); } return $response; } /** * Getting the token store, building a default one on first use. * * @return TokenStore The store. */ private function token_repository(): TokenStore { if ( null === $this->tokens ) { $this->tokens = new TokenRepository(); } return $this->tokens; } }