Use the user_activation_key for other purposes

Do you think this will be safe?

Maybe. Two issues.

You also need to make sure the key isn’t guessable. No incrementing numbers. You can use something like wp_generate_password to get some psuedo random characters. Use a random “salt” plus the user’s email and sign up time or uniqid and you stand a pretty good chance of ensuring uniqueness (see below) and creating a non-guessable key.

$user_email = some_function_to_get_user_email();
$salt = wp_generate_password(20); // 20 character "random" string
$key = sha1($salt . $user_email . uniqid(time(), true));

You’ll also need to ensure the uniqueness of the key: there’s shouldn’t be any collisions.

There’s no constraints on on the user_activation_key column in the database that ensure uniqueness, so it’s up to your app (eg. WordPress and the PHP side of things) to make sure it is. In other words, either before or after you generate the key make sure it doesn’t exist already in the database. Simple, untested example:

<?php
$key = some_function_that_generates_a_key();
$res = $wpdb->get_col($wpdb->prepare("SELECT EXISTS(SELECT 1 FROM {$wpdb->users} WHERE user_activation_key = %s)", $key));
if ($res) {
    // the key exists, try again!
} else {
    // good to go.
}

If you need a guide, trying looking at how WordPress does password reset emails. The process is the same: generate a non-guessable key, make sure it’s unique, insert into the database with the corresponding user, then send them an email with a link to reset the password.

Leave a Comment