以下是需要修改的脚本部分。当前它会匹配用户提供的电子邮件地址中@后面的任何单词。我需要它能够匹配直接在@后面或在另一个单词和点(.)之前的任何单词,例如:user@domain.com.au 应该匹配 domain,user@someword.domain.com 也应该匹配 domain,无论前面是否有.someword(这将把user更改为user,对于某些用户而言存在但对于其他用户则不存在。)
PHP代码:
以下是已更改敏感信息以确保安全性的完整代码。
PHP代码:
preg_match('|@([0-9a-zA-Z]+)\.|i', $username, $match);
以下是已更改敏感信息以确保安全性的完整代码。
<?php
// PHP code in child theme of WordPress multisite network functions.php
add_filter( 'authenticate', 'external_auth', 10, 3 );
add_filter( 'login_redirect', 'ds_login_redirect', 10, 3 );
function external_auth( $user, $username, $password ){
// Make sure a username and password are present for us to work with
if($username == '' || $password == '') return;
// Try to log into the external service or database with username and password
$args = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'username' => $username, 'password' => $password ),
'cookies' => array()
);
$ext_auth = wp_remote_post("http://auth-server:port-number/api-token-auth/",$args);
// if external authentication was successful
if($ext_auth['response']['code'] == 200) {
$userobj = new WP_User();
$user = $userobj->get_data_by( 'login', $username );
// Does not return a WP_User object :(
$user = new WP_User($user->ID);
// Attempt to load up the user with that ID
if( $user->ID == 0 ) {
// The user does not currently exist in the WordPress user table.
// If you do not want to add new users to WordPress if they do not
// already exist uncomment the following line and remove the user creation code
//$user = new WP_Error( 'denied', __("ERROR: Not a valid user for this system") );
// Setup the minimum required user information
$new_user_id = wpmu_create_user($username, $password, $username);
// A new user has been created
preg_match('|@([0-9a-zA-Z]+)\.|i', $username, $match);
$path = '/'.$match[1].'/';
$domain = 'the-wordpress-network-site.com';
// Figure out their blog to add permission to
$blog_id = get_blog_id_from_url ( $domain, $path );
// Specify their role
$role = 'subscriber';
// Give the user access to their blog.
add_user_to_blog($blog_id, $new_user_id, $role);
// Load the new user info
$user = new WP_User ($new_user_id);
}
}else if($ext_auth['response']['code'] == 400){
$user = new WP_Error( 'denied', __("ERROR: User/pass bad") );
}
// Comment this line if you wish to fall back on WordPress authentication
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}
function ds_login_redirect( $redirect_to, $request_redirect_to, $user )
{
if ($user->ID != 0) {
$user_info = get_userdata($user->ID);
if ($user_info->primary_blog) {
$primary_url = get_blogaddress_by_id($user_info->primary_blog) . 'index/';
if ($primary_url) {
//echo $primary_url; die();
wp_redirect($primary_url);
die();
}
}
}
return $redirect_to;
}
?>