Skip to content

Commit

Permalink
Fix WP Telegram Login race condition to prevent duplicate Mini App users
Browse files Browse the repository at this point in the history
  • Loading branch information
irshadahmad21 committed Dec 1, 2024
1 parent 85fac93 commit ce379e3
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/three-games-wink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wptelegram-login": patch
---

Fixed WP Telegram Login race condition to prevent duplicate Mini App users
12 changes: 10 additions & 2 deletions plugins/wptelegram-login/src/includes/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public static function get_default_settings() {
*
* @since 1.10.3
*
* @param int $tg_user_id Telegram User ID.
* @param int|string $tg_user_id Telegram User ID.
*
* @return WP_User|false User object or false
*/
Expand All @@ -106,6 +106,14 @@ public static function get_user_by_telegram_id( $tg_user_id ) {

$users = get_users( $args );

return reset( $users );
$user = reset( $users );

/**
* Filter the user found by its Telegram ID.
*
* @param WP_User|false $user The user object or false.
* @param int|string $tg_user_id Telegram User ID.
*/
return apply_filters( 'wptelegram_login_get_user_by_telegram_id', $user, $tg_user_id );
}
}
17 changes: 13 additions & 4 deletions plugins/wptelegram-login/src/shared/LoginHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ public function telegram_login() {
try {
$auth_data = $this->validate_auth_data( $input );

// Add a lock using transients to prevent multiple concurrent requests.
$transient_key = 'wptelegram_login_' . $auth_data['id'];

if ( get_transient( $transient_key ) ) {
sleep( 5 ); // Wait for 5 seconds.
}

set_transient( $transient_key, current_time( 'mysql' ), 10 );

/**
* Fires before the user data is saved after validation.
*
Expand Down Expand Up @@ -261,6 +270,10 @@ public function validate_auth_data( $input_data ) {
$auth_data = ! empty( $auth_data['user'] ) ? Utils::sanitize( json_decode( $auth_data['user'], true ) ) : [];
}

if ( empty( $auth_data['id'] ) || empty( $auth_data['first_name'] ) ) {
throw new Exception( esc_html__( 'Invalid! The data is incomplete', 'wptelegram-login' ) );
}

/**
* Filter the validated auth data.
*
Expand Down Expand Up @@ -440,10 +453,6 @@ public function unique_email( $user, $host ) {
*/
public function save_telegram_user_data( $data ) {

if ( empty( $data['id'] ) || empty( $data['first_name'] ) ) {
throw new Exception( esc_html__( 'Invalid! The data is incomplete', 'wptelegram-login' ) );
}

$data = array_map( 'htmlspecialchars', $data );

// Check if the request is from a logged in user.
Expand Down

0 comments on commit ce379e3

Please sign in to comment.