| 1 |
<?php |
| 2 |
|
| 3 |
namespace FlyWP\Frontend; |
| 4 |
|
| 5 |
/** |
| 6 |
* Magic Login. |
| 7 |
* |
| 8 |
* @since 1.0.0 |
| 9 |
*/ |
| 10 |
class MagicLogin { |
| 11 |
|
| 12 |
/** |
| 13 |
* Plugin Constructor. |
| 14 |
* |
| 15 |
* @return void |
| 16 |
*/ |
| 17 |
public function __construct() { |
| 18 |
add_action( 'setup_theme', [ $this, 'login_user' ] ); |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Check if the request is valid. |
| 23 |
* |
| 24 |
* @return bool |
| 25 |
*/ |
| 26 |
private function is_valid_request() { |
| 27 |
return isset( $_SERVER['REQUEST_URI'] ) && isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_URI'] === '/flywp-magic-login' && $_SERVER['REQUEST_METHOD'] === 'POST'; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Redirect to home. |
| 32 |
* |
| 33 |
* @return void |
| 34 |
*/ |
| 35 |
public function redirect_to_home() { |
| 36 |
wp_safe_redirect( site_url() ); |
| 37 |
exit; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Redirect to admin. |
| 42 |
* |
| 43 |
* @return void |
| 44 |
*/ |
| 45 |
public function redirect_to_admin() { |
| 46 |
wp_safe_redirect( admin_url() ); |
| 47 |
exit; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Login an user. |
| 52 |
* |
| 53 |
* @return void |
| 54 |
*/ |
| 55 |
public function login_user() { |
| 56 |
if ( ! $this->is_valid_request() ) { |
| 57 |
return; |
| 58 |
} |
| 59 |
|
| 60 |
// phpcs:disable WordPress.Security.NonceVerification.Missing |
| 61 |
$api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : ''; |
| 62 |
$username = isset( $_POST['username'] ) ? sanitize_text_field( wp_unslash( $_POST['username'] ) ) : ''; |
| 63 |
// phpcs:enable WordPress.Security.NonceVerification.Missing |
| 64 |
|
| 65 |
if ( ! $api_key || ! $username ) { |
| 66 |
$this->redirect_to_home(); |
| 67 |
} |
| 68 |
|
| 69 |
if ( $api_key !== flywp()->get_key() ) { |
| 70 |
$this->redirect_to_home(); |
| 71 |
} |
| 72 |
|
| 73 |
if ( is_user_logged_in() ) { |
| 74 |
$this->redirect_to_admin(); |
| 75 |
} |
| 76 |
|
| 77 |
$user = get_user_by( 'login', $username ); |
| 78 |
|
| 79 |
// if user not found, use the first admin |
| 80 |
if ( ! $user ) { |
| 81 |
$admins = get_users( [ 'role' => 'administrator', 'mumber' => 1 ] ); |
| 82 |
|
| 83 |
if ( ! $admins ) { |
| 84 |
$this->redirect_to_home(); |
| 85 |
} |
| 86 |
|
| 87 |
$user = $admins[0]; |
| 88 |
} |
| 89 |
|
| 90 |
wp_set_current_user( $user->ID, $user->user_login ); |
| 91 |
wp_set_auth_cookie( $user->ID ); |
| 92 |
|
| 93 |
// redirect to admin |
| 94 |
$this->redirect_to_admin(); |
| 95 |
} |
| 96 |
} |
| 97 |
|