From 541d87c3a5eb2f6aab629f98f5352037d81754e7 Mon Sep 17 00:00:00 2001 From: Ian Dunn Date: Wed, 11 Jan 2023 11:36:41 -0500 Subject: [PATCH] Modularize QR code URL generation for reuse This lets other plugins reuse the function. --- providers/class-two-factor-totp.php | 54 ++++++++++++++++++----------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/providers/class-two-factor-totp.php b/providers/class-two-factor-totp.php index 841fe121..1b353233 100644 --- a/providers/class-two-factor-totp.php +++ b/providers/class-two-factor-totp.php @@ -184,6 +184,38 @@ public function rest_setup_totp( $request ) { ]; } + /** + * Generates a URL that can be used to create a QR code. + * + * @param WP_User $user The user to generate a URL for. + * @param string $key The secret key. + * + * @return string + */ + public static function generate_qr_code_url( $user, $secret_key ) { + $site_name = get_bloginfo( 'name', 'display' ); + + // Must follow TOTP format for a "label": + // https://github.com/google/google-authenticator/wiki/Key-Uri-Format#label + // Do not URL encode, that will be done later. + $totp_title = apply_filters( 'two_factor_totp_title', $site_name . ':' . $user->user_login, $user ); + + $totp_url = add_query_arg( + array( + 'secret' => rawurlencode( $secret_key ), + 'issuer' => rawurlencode( $site_name ), + ), + 'otpauth://totp/' . rawurlencode( $totp_title ) + ); + + // Must follow TOTP format: + // https://github.com/google/google-authenticator/wiki/Key-Uri-Format + $totp_url = apply_filters( 'two_factor_totp_url', $totp_url, $user ); + $totp_url = esc_url( $totp_url, array( 'otpauth' ) ); + + return $totp_url; + } + /** * Display TOTP options on the user settings page. * @@ -206,26 +238,8 @@ public function user_two_factor_options( $user ) { generate_key(); - $site_name = get_bloginfo( 'name', 'display' ); - - // Must follow TOTP format for a "label": - // https://github.com/google/google-authenticator/wiki/Key-Uri-Format#label - // Do not URL encode, that will be done later. - $totp_title = apply_filters( 'two_factor_totp_title', $site_name . ':' . $user->user_login, $user ); - - $totp_url = add_query_arg( - array( - 'secret' => rawurlencode( $key ), - 'issuer' => rawurlencode( $site_name ), - ), - 'otpauth://totp/' . rawurlencode( $totp_title ) - ); - - // Must follow TOTP format: - // https://github.com/google/google-authenticator/wiki/Key-Uri-Format - $totp_url = apply_filters( 'two_factor_totp_url', $totp_url, $user ); - $totp_url = esc_url( $totp_url, array( 'otpauth' ) ); + $key = $this->generate_key(); + $totp_url = $this->generate_qr_code_url( $user, $key ); ?>