| |
| <?php
|
|
|
| add_action('wp_login', 'send_otp_to_admin', 10, 2);
|
| function send_otp_to_admin($user_login, $user) {
|
|
|
| if (in_array('administrator', $user->roles)) {
|
|
|
| $otp = wp_rand(100000, 999999);
|
|
|
|
|
| set_transient('otp_' . $user->ID, $otp, 5 * MINUTE_IN_SECONDS);
|
|
|
|
|
| $to = $user->user_email;
|
| $subject = 'Your OTP for Admin Login';
|
| $message = 'Your OTP for admin login is: ' . $otp;
|
| wp_mail($to, $subject, $message);
|
|
|
|
|
| set_transient('otp_verification_required_' . $user->ID, true, 5 * MINUTE_IN_SECONDS);
|
| }
|
| }
|
|
|
|
|
| add_action('login_form', 'modify_login_form_for_otp');
|
| function modify_login_form_for_otp() {
|
| if (isset($_GET['user_id'])) {
|
| $user_id = intval($_GET['user_id']);
|
| if (get_transient('otp_verification_required_' . $user_id)) {
|
|
|
| echo '<style>#loginform > p:not(.otp-field), #loginform > div { display: none; }</style>';
|
|
|
|
|
| echo '<p class="otp-field">
|
| <label for="otp">OTP<span class="required">*</span></label>
|
| <input type="text" name="otp" id="otp" class="input" value="" size="20" required>
|
| </p>';
|
| echo '<input type="hidden" name="user_id" value="' . esc_attr($user_id) . '">';
|
| }
|
| }
|
| }
|
|
|
|
|
| add_filter('authenticate', 'handle_otp_verification', 30, 3);
|
| function handle_otp_verification($user, $username, $password) {
|
| if (isset($_POST['otp']) && isset($_POST['user_id'])) {
|
| $user_id = intval($_POST['user_id']);
|
| $stored_otp = get_transient('otp_' . $user_id);
|
|
|
| if ($_POST['otp'] == $stored_otp) {
|
|
|
| delete_transient('otp_' . $user_id);
|
| delete_transient('otp_verification_required_' . $user_id);
|
|
|
|
|
| $user = get_user_by('id', $user_id);
|
| return $user;
|
| } else {
|
|
|
| return new WP_Error('invalid_otp', '<strong>ERROR</strong>: Invalid OTP. Please try again.');
|
| }
|
| } elseif (isset($_POST['log']) && isset($_POST['pwd'])) {
|
|
|
| $user = get_user_by('login', $username);
|
| if ($user && in_array('administrator', $user->roles)) {
|
| if (get_transient('otp_verification_required_' . $user->ID)) {
|
|
|
| wp_redirect(add_query_arg('user_id', $user->ID, wp_login_url()));
|
| exit;
|
| }
|
| }
|
| }
|
| return $user;
|
| }
|
|
|
|
|
| add_action('admin_init', 'restrict_admin_access');
|
| function restrict_admin_access() {
|
| if (current_user_can('administrator')) {
|
| $user = wp_get_current_user();
|
| if (get_transient('otp_verification_required_' . $user->ID)) {
|
| wp_redirect(wp_login_url());
|
| exit;
|
| }
|
| }
|
| }
|
| |
| |
Comments