← Back
Editing: wpck-autologin.php
<?php /** * Plugin Name: WPCK Auto Login * Description: One-click admin login for the WPmanage control panel. * Consumes a single-use token that an authenticated panel operator created * server-side over SSH, logs the matching WordPress user in, and redirects to * wp-admin. Tokens live in a short-lived transient (~2 min) and are deleted the * moment they are used, so a link cannot be replayed. Installed as a MUST-USE * plugin so it is always active and survives backup/restore (wp-restore.sh leaves * mu-plugins/ untouched). * Version: 1.0 * Author: WPmanage */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Read a one-time login token. * * Stored as a normal option (uid|expiry) so Redis object-cache cannot hide a * value that WP-CLI wrote into the database. The old transient key is still * accepted so a link minted just before this file was updated keeps working. */ function wpck_sso_take_user_id( $token ) { $key = 'wpck_sso_' . $token; $raw = get_option( $key, false ); if ( false !== $raw && '' !== $raw ) { delete_option( $key ); $parts = explode( '|', (string) $raw, 2 ); $uid = isset( $parts[0] ) ? (int) $parts[0] : 0; $expiry = isset( $parts[1] ) ? (int) $parts[1] : 0; if ( $uid > 0 && ( 0 === $expiry || time() <= $expiry ) ) { return $uid; } return 0; } $uid = get_transient( $key ); if ( false === $uid || '' === $uid ) { return 0; } delete_transient( $key ); return (int) $uid; } // init, not plugins_loaded: WordPress defines the auth-cookie names after // plugins_loaded, so a cookie set any earlier is ignored and the next request // to /wp-admin looks logged-out. Secure Login skips requests that carry // wpck_sso, so this still runs before that plugin can 404 the page. add_action( 'init', function () { if ( empty( $_GET['wpck_sso'] ) ) { return; } // Tokens are hex only; reject anything else outright. $token = preg_replace( '/[^a-f0-9]/', '', (string) $_GET['wpck_sso'] ); if ( strlen( $token ) < 16 ) { return; } $uid = wpck_sso_take_user_id( $token ); if ( $uid <= 0 ) { wp_die( 'This one-time login link has expired or was already used. Generate a new one from the control panel.', 'Login link expired', array( 'response' => 403 ) ); } $user = get_user_by( 'id', $uid ); if ( ! $user ) { wp_die( 'The account for this login link no longer exists.', 'Login failed', array( 'response' => 403 ) ); } wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID, false ); do_action( 'wp_login', $user->user_login, $user ); // Stay on the host the operator opened. admin_url() follows the siteurl // option, which can be a different host than the custom domain, and the // cookie we just set would not be sent. $host = isset( $_SERVER['HTTP_HOST'] ) ? preg_replace( '/[^A-Za-z0-9.:_-]/', '', (string) $_SERVER['HTTP_HOST'] ) : ''; $target = $host ? ( is_ssl() ? 'https' : 'http' ) . '://' . $host . '/wp-admin/' : admin_url(); wp_redirect( $target ); exit; }, 0 );
Save File
Cancel