I’m playing around with the WP REST API and have setup a route that is used to create a new user when a form is submitted from the homepage. Here is how I setup the endpoint:
add_action('init', 'test_init');
function test_init() {
// register the route
add_action('rest_api_init', function () {
register_rest_route( 'test/api/v1', '/user/add', array(
'methods' => 'POST',
'callback' => 'test_add_user',
));
});
}
function test_add_user() {
// make sure all data is available
if (!isset($_POST['firstname'],
$_POST['surname'],
$_POST['email'],
$_POST['password'])) {
exit;
}
// check so the user not already exists
if (username_exists($_POST['firstname'])) {
exit;
}
// create a new user
$user = array(
'user_pass' => $_POST['password'],
'user_login' => $_POST['firstname'],
'user_email' => $_POST['email'],
'first_name' => $_POST['firstname'],
'last_name' => $_POST['surname'],
'role' => 'author'
);
$user_id = wp_insert_user($user);
// return the id of the created user
echo json_encode(array('id' => $user_id));
exit;
}
What I’m wondering is how to best prevent external access to this route? I only want data from the actual form on the homepage to be able to post data to this endpoint.
I tried to check the origin in the callback, but I’m unsure if this is the correct way to do this:
function test_add_user() {
// only allow request from the same origin
if (get_http_origin() != home_url()) {
exit;
}
...
}
I though about perhaps using nonces or something along that line?
Perhaps I also should mention that the user submitting the form is not logged in so I cannot use a cookie based authentication or similar.