connections = $connections; } /** * Credentials for a connection. * * @param Connection $connection Connection. * @return Credentials * @throws ApiException When the connection isn't finished or its secrets are unreadable. */ public function for_connection( Connection $connection ) { if ( ! $connection->is_connected() ) { throw new ApiException( __( 'This Google connection hasn\'t finished setting up. An administrator needs to complete it on the Connections screen.', 'turtlereport' ), ApiException::NOT_CONFIGURED ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Plain domain exception, not HTML output; preserve message bytes and escape at the response boundary. } if ( Connection::TYPE_SERVICE_ACCOUNT === $connection->type ) { try { $key = ServiceAccountCredentials::parse_key( $this->connections->secret( $connection->id, ConnectionRepository::SECRET_KEY ) ); } catch ( \InvalidArgumentException $e ) { throw new ApiException( self::unreadable_message(), ApiException::RECONNECT ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Plain domain exception, not HTML output; preserve message bytes and escape at the response boundary. } return new ServiceAccountCredentials( $connection->id, $key ); } $secret = $this->connections->secret( $connection->id, ConnectionRepository::SECRET_CLIENT_SECRET ); $refresh = $this->connections->secret( $connection->id, ConnectionRepository::SECRET_REFRESH_TOKEN ); if ( '' === $secret || '' === $refresh ) { throw new ApiException( self::unreadable_message(), ApiException::RECONNECT ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Plain domain exception, not HTML output; preserve message bytes and escape at the response boundary. } return new OAuthCredentials( $connection->id, $connection->client_id, $secret, $refresh, $connection->scopes ); } /** * Message for secrets that can't be decrypted. * * @return string */ private static function unreadable_message() { return __( 'This connection\'s saved credentials can\'t be read, usually because the site\'s security keys (salts) changed. Reconnect it on the Connections screen.', 'turtlereport' ); } }