After WordCamp 2012 in San Francisco, I started to realize how many people were using WordPress as a platform for their web based application. Well with web based application come API’s and with that, unique user keys. I’ve been working on such a service lately and was in need of setting up a quick script that assigns an API Key to a user when they signup on a WordPress site. Here’s the code, and a quick explanation.
user_email . timestamp();
$user_api_key = sha1( $pre_obfu );
update_user_meta( $user_id, ‘wpcronme_user_api’, $user_api_key );
add_action( ‘user_register’, ‘ck_assign_api_key’ );
Ok, so what we did was hook onto the user_register hook. This passes along a user ID. From there we can get all the information we need about the newly registered user.
So, what’s the next part:
$pre_obfu = $user_id . NONCE_SALT . $user_data->user_email . timestamp();
We’re making a string that’s unique to this user, this site, and this timestamp (important later). When creating User API Keys the important thing is that they be unique. With WordPress this is pretty easy in that, by default, an email address can only be assigned to one account. Using the user ID and the email address as part of the hash assures we don’t get a duplicate. You may be asking about the other two parts NONCE_SALT and timestamp().
If you are following best security practices you have added unique keys and salts to your wp-config.php file right? …Right?! Go do this now if you haven’t. Now, this is a unique string to your site, meaning that unless someone else has the same key as you, they can’t replicate the exact same User API Keys.
The timestamp call does one thing and it’s very important. The first 3 items are unique, and don’t typically change. If someone’s User API Key get’s missused, you need a way for the users to recreate a new key so the previous one is invalidated. This timestamp will allow the API Key to be different if you run the same function again after a user edit, or something of the likes (I’ll leave that code up to you).
So that’s it, quickly generated unique keys for new users in WordPress. Hope this helps someone out.