db->insert( $this->table, array( 'token_hash' => hash( 'sha256', $token ), 'customer_id' => $customer_id, 'purpose' => $purpose, 'expires_at' => self::dt( $expires ), ) ); } /** * The customer a live token belongs to; one-time tokens are used up. * * @param string $token Token. * @param string $purpose Purpose. * @param bool $use Mark it used. */ public function customer( string $token, string $purpose, bool $use = false ): int { $hash = hash( 'sha256', $token ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery $id = (int) $this->db->get_var( $this->db->prepare( "SELECT customer_id FROM {$this->table} WHERE token_hash = %s AND purpose = %s AND expires_at > %s AND used_at IS NULL", $hash, $purpose, self::now() ) ); if ( $id > 0 && $use ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery $used = (int) $this->db->query( $this->db->prepare( "UPDATE {$this->table} SET used_at = %s WHERE token_hash = %s AND used_at IS NULL", self::now(), $hash ) ); return 1 === $used ? $id : 0; } return $id; } /** * Forget a token, e.g. on log out. * * @param string $token Token. */ public function revoke( string $token ): void { $this->db->delete( $this->table, array( 'token_hash' => hash( 'sha256', $token ) ) ); } /** * Codes sent to a customer in the last hour, to limit abuse. * * @param int $customer_id Customer. * @param string $purpose Purpose. * @param int $lifetime Seconds the token lives. */ public function recent( int $customer_id, string $purpose, int $lifetime ): int { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery return (int) $this->db->get_var( $this->db->prepare( "SELECT COUNT(*) FROM {$this->table} WHERE customer_id = %d AND purpose = %s AND expires_at > %s", $customer_id, $purpose, self::dt( time() + $lifetime - 3600 ) ) ); } public function purge(): void { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery $this->db->query( $this->db->prepare( "DELETE FROM {$this->table} WHERE expires_at < %s", self::now() ) ); } }