Skip to content

Commit

Permalink
Modularize QR code URL generation for reuse
Browse files Browse the repository at this point in the history
This lets other plugins reuse the function.
  • Loading branch information
iandunn committed Jan 11, 2023
1 parent 9344dff commit 541d87c
Showing 1 changed file with 34 additions and 20 deletions.
54 changes: 34 additions & 20 deletions providers/class-two-factor-totp.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -206,26 +238,8 @@ public function user_two_factor_options( $user ) {
<?php
if ( empty( $key ) ) :

$key = $this->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 );

?>

Expand Down

0 comments on commit 541d87c

Please sign in to comment.