Skip to content

Instantly share code, notes, and snippets.

@bradt
Created April 28, 2014 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bradt/11381535 to your computer and use it in GitHub Desktop.
Save bradt/11381535 to your computer and use it in GitHub Desktop.
Automatic Logins for WordPress
<?php
class DBrains_Auto_Login {
protected static $_instance = null;
function __construct() {
global $wpdb;
$this->expires = DAY_IN_SECONDS * 30 * 4;
$this->table = $wpdb->prefix . 'dbrns_auto_login_keys';
add_action( 'init', array( $this, 'handle_auto_login' ), 10 );
}
public function handle_auto_login() {
if ( !isset( $_GET['login_key'] ) || !isset( $_GET['user_id'] ) ) {
return;
}
// Limit Login Attempts plugin
if ( function_exists( 'is_limit_login_ok' ) ) {
if ( !is_limit_login_ok() ) {
return;
}
}
$user = new WP_User( $_GET['user_id'] );
if ( !$user->ID ) {
return;
}
$user_id = $this->get_user_id_for_key( $_GET['login_key'] );
if ( !$user_id || $user_id != $user->ID ) {
do_action( 'wp_login_failed', $user->user_login );
return;
}
wp_set_auth_cookie( $user->ID );
do_action( 'wp_login', $user->user_login, $user );
$redirect = remove_query_arg( array( 'login_key', 'user_id' ) );
wp_redirect( $redirect );
exit;
}
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
public function get_user_id_for_key( $key ) {
global $wpdb;
$sql = $wpdb->prepare(
"SELECT `user_id`, `created`
FROM {$this->table} WHERE `login_key` = %s",
$key
);
$row = $wpdb->get_row( $sql );
if ( !$row ) {
return false;
}
if ( mysql2date( 'G', $row->created ) < time() - $this->expires ) {
return false;
}
return $row->user_id;
}
public function create_key( $user_id ) {
global $wpdb;
// Cleanup expired keys
$expired_date = gmdate( 'Y-m-d H:i:s', ( time() - $this->expires ) );
$wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table} WHERE `created` < %s", $expired_date ) );
do {
$key = wp_generate_password( 40, false );
$sql = $wpdb->prepare( "SELECT `user_id` FROM {$this->table} WHERE `login_key` = %s", $key );
$already_exists = $wpdb->get_var( $sql );
}
while ( $already_exists );
$result = $wpdb->insert( $this->table, array(
'login_key' => $key,
'user_id' => $user_id,
'created' => gmdate( 'Y-m-d H:i:s' )
) );
if ( !$result ) {
return false;
}
return $key;
}
}
DBrains_Auto_Login::instance();
CREATE TABLE `oiz6q8a_dbrns_auto_login_keys` (
`login_key` varchar(60) NOT NULL,
`user_id` bigint(20) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`login_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@ionurboz
Copy link

Looks nice,

What exactly is the code here? So I don't understand exactly what the code does, but it looks like it adds a nice feature. Can you explain?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment