我正在网站上工作,我只能为在其他数据库中注册的用户显示其内容。如果用户存在与否,我设法从其他系统获得API响应,但我真的不知道如何继续该过程。你能帮帮我吗?
PS:我无法对WP数据库中的用户进行身份验证,我希望让管理员用户以该方式登录。
这是我的API请求:
$username = '';
$password = '';
$token = '';
$url = "";
$cookie = "h8gkh8.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/' . $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/' . $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch))
die(curl_error($ch));
$doc = new DOMDocument();
$doc->loadHTML($response);
$el = $doc->getElementsByTagName("input");
for ($i = 0; $i < $el->length; $i++) {
$attr = $el->item($i)->getAttribute('name');
if ($attr == '_csrfhash') {
$token = $el->item($i)->getAttribute('value');
}
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
$params = array(
'scemail' => $username,
'scpassword' => $password,
'_csrfhash' => $token
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
$r = curl_exec($ch);
if (curl_errno($ch))
print curl_error($ch);
答案 0 :(得分:0)
对于extrnal / custom登录,您必须使用 authenticate 过滤器。 每当触发登录时,都会触发验证过滤器 可以应用自定义逻辑。过滤器可以设置为 以下代码。
add_filter( 'authenticate', 'my_auth', 10, 3 );
function my_auth( $user, $username, $password ){
return $user;
}
my_auth
函数将替换内置的身份验证方法。身份验证过滤器发送三个参数:
以下是完整的my_auth
代码:
function my_auth($user, $username, $password)
{
// Make sure a username and password are present for us to work with
if ($username == '' || $password == '')
return;
/* my_api_section
* your API code goes here
* Assuming it returns 0 for username and password missmatch
* and 1 for match; store the result in $ext_auth['result']
*/
if ($ext_auth['result'] == 0) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __("ERROR: Username/password missmatch or not exists"));
} else if ($ext_auth['result'] == 1) {
// External user exists, try to load the user info from the WordPress user table
$userobj = new WP_User();
$user = $userobj->get_data_by('email', $ext_auth['email']); // 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.
// So creating the user.
// Setup the minimum required user information for this example
$userdata = array(
'user_email' => $ext_auth['email'],
'user_login' => $ext_auth['email'],
'first_name' => $ext_auth['first_name'],
'last_name' => $ext_auth['last_name']
);
$new_user_id = wp_insert_user($userdata); // A new user has been created
// Load the new user info
$user = new WP_User($new_user_id);
}
}
return $user;
}
上面的代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
请注意