简体   繁体   English

登录 WP - 将单个字段连接到外部 api

[英]Login WP - Connect single field to an external api

I made a plugin to allow wordpress login with external api.我制作了一个插件,允许 wordpress 使用外部 api 登录。

Everything works, now what I have to do is that when a user logs in for the first time, the plugin checks to see if it is already present on wp, and where it was not already present, it creates a new user by taking behind username, email and password.一切正常,现在我要做的是,当用户第一次登录时,插件会检查它是否已经存在于 wp 上,以及它不存在的地方,它通过在后面创建一个新用户用户名、email 和密码。

The new user is created but I would like it to bring with it also the id field from the external api saving it in an ACF field.新用户已创建,但我希望它还带有来自外部 api 的 id 字段,将其保存在 ACF 字段中。

This is the code created so far:这是到目前为止创建的代码:

function au_auth($user, $username, $password)
{
    $options = get_option('au_options');
    $endpoint = $options['au_apiurl'];

    $user_email_key = 'email';
    $password_key = 'password';

    // Makes sure there is an endpoint set as well as username and password
    if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
        return false;
    }

    // Check user exists locally
    $user_exists = wp_authenticate_username_password(null, $username, $password);

    if ($user_exists && $user_exists instanceof WP_User) {
        $user = new WP_User($user_exists);
        return $user;
    }

    // Build the POST request
    $login_data = array(
        $user_email_key => $username,
        $password_key => $password
    );

    $auth_args = array(
        'method' => 'POST',
        'headers' => array(
            'Content-type: application/x-www-form-urlencoded'
        ),
        'sslverify' => false,
        'body' => $login_data
    );


    $response = wp_remote_post($endpoint, $auth_args);

    // Token if success; Not used right now
    $response_token = json_decode($response['response']['token'], true);

    $response_code = $response['response']['code'];
    if ($response_code == 400) {
        // User does not exist, send back an error message
        $user = new WP_Error('denied', __("<strong>Error</strong>: Your username or password are incorrect."));
    } else if ($response_code == 200) {
        // External user exists, try to load the user info from the WordPress user table
        $userobj = new WP_User();
        // Does not return a WP_User object but a raw user object
        $user = $userobj->get_data_by('email', $username);
        if ($user && $user->ID) {
            // Attempt to load the user with that ID
            $user = new WP_User($user->ID);
        }
    } else {
        // The user does not currently exist in the WordPress user table.
        // Setup the minimum required user information
        $userdata = array(
            'user_email' => $username,
            'user_login' => $username,
            'user_pass' => $password
        );
        // A new user has been created
        $new_user_id = wp_insert_user($userdata);
        // Assign editor role to the new user (so he can access protected articles)
        wp_update_user(
            array(
                'ID' => $new_user_id,
                'role' => 'editor'
            )
        );
        // Load the new user info
        $user = new WP_User ($new_user_id);
    }
}
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);

return $user;
}

Anyone have any way how to help me?有人有什么办法可以帮助我吗?

Resolved: I hope this will help those who have found themselves in the same situation as me:已解决:我希望这将帮助那些发现自己处于与我相同情况的人:

add_filter('authenticate', 'au_auth', 10, 3);
add_filter('register_new_user', 'au_registration', 10, 3);
// add_filter('profile_update', 'au_profile_update', 10, 3);
// add_filter('edit_user_profile_update', 'au_profile_edit', 10, 3);

function au_auth($user, $username, $password)
{
    $options = get_option('au_options');
    $endpoint = $options['au_apiurl'];

    // Makes sure there is an endpoint set as well as username and password
    if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
        return false;
    }

    $auth_args = [
        'method' => 'POST',
        'headers' => [
            'Content-type: application/x-www-form-urlencoded',
        ],
        'sslverify' => false,
        'body' => [
            'email' => $username,
            'password' => $password,
        ],
    ];

    $response = wp_remote_post($endpoint, $auth_args);

    // Token if success; Not used right now
    $response_token = json_decode($response['response']['token'], true);

    $body = json_decode($response['body'], true);

    $response_status_code = $response['response']['code'];

    $success = $body !== 'KO';

    if (!$success) {
        // User does not exist, send back an error message
        $user = new WP_Error('denied', __('<strong>Error</strong>: Your username 
    or password are incorrect.'));
    } elseif ($success) {
        $idExternal = $body['Id'];
        $nome = $body['Name'];
        $cognome = $body['Surname'];
        $email = $body['Email'];

        $userobj = new WP_User();
        $user = $userobj->get_data_by('email', $email);
        if ($user && $user->ID) {
            $user = new WP_User($user->ID);
        } else {
            $userdata = [
                'user_email' => $email,
                'user_login' => join(' ', [$name, $surname]),
                'user_pass' => '----',
            ];
            $new_user_id = wp_insert_user($userdata);
            $new_user_composite_id = 'user_' . $new_user_id;
            update_field('field_60084ad3970a8', $idExternal, $new_user_composite_id);
            update_field('field_5f22ca201c7b0', $name, $new_user_composite_id);
            update_field('field_5f22ccd498f40', $surname, $new_user_composite_id);
            update_field('field_5f22ce7b7c1db', $email, $new_user_composite_id);

            $user = new WP_User($new_user_id);
        }
    }
    remove_action('authenticate', 'wp_authenticate_username_password', 20);

    return $user;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM