In Drupal 7 we had the LoginToboggan module, but this is not available for Drupal 8. I needed to replace the "Delete unvalidated users after" x days feature from LoginToboggan so I wrote some quick code that I want to add it in here.
In a module we can create a function that will delete our unvalidated [sic] users after a set number of days.
First, I need to define a timestamp for today (right now).
Then I need do an entity query to gather the users we want to examine. I then need to get the created value(s) for the user entities that are returned in the query and see if they are more than 2 days older than than today. If they are more than two days old I delete the user entity.
These users will not have content (in our case and most cases because they are not validated). Use caution if your users will have content.
function my_module_tool_delete_unvalidated_users_after_2_days(){
$today = time();
$q = \Drupal::entityQuery('user');
$q->accessCheck(FALSE); //This will be used during cron
$q->condition('created', 0, '!=');
$q->condition('login', 0);
$q->condition('access', 0);
$q->condition('status', 0);
$q->condition('uid', 0, '!=');
$users = $q->execute();
foreach ($users as $user){
$user_entity = \Drupal\user\Entity\User::load($user);
$created = $user_entity->get('created')->value;
$datediff = $today - $created;
if (round($datediff / (60 * 60 * 24)) > 2) {
$user_entity->delete();
}
}
}
Now we need to invoke hook_cron so that when cron runs our module will do something on cron. Our cron hook will need to call our function.
/**
* Implements hook_cron().
*/
function my_module_cron() {
my_module_delete_unvalidated_users_after_2_days();
}