Wordpress login used for rails application
Monday, February 22nd, 2010in order to use the rails login mechanism with another non-php application there are two solutions. for both you need to read the rails login cookie. it is named wordpress_logged_in_XXXX. Where XXXX is a random string. it contains a string of the form: admin|YYYY|ZZZZ. YYYY is the expiration date, in seconds i think, and ZZZZ is a hash calculated from lots of different inputs.
the first solution is to get the cookie from the browser, fetch the different input parameters for the hash from the config-files and the database and compare this hash with the hash given by the cookie. but it’s quite hard to calculate the hash. it uses not only username and password, it uses also salt values from the config file or the database, depending on many configuration options. to make it properly it would be quite hard. but there is an easier, not much more unsecure way. instead of only sending the cookie and it’s value to the browser we could write it also somewhere in a tempfolder to the filesystem. so we can read the cookie from the second application and check it againts the one from the filesystem. instead of the filesystem we could also use memcached to store the cookie infos.
whenever wordpress writes the cookie we have to write it also to the filesystem. this can be done inside the wp_set_auth_cookie function inside the file wp-includes/pluggable.php. but there is another problem. the name of the cookie is the same for different clients. so we have to use another name. i’d propose to use the username of the logged in user. the value which has to be written is stored in the logged_in_cookie -variable inside the wp_set_auth_cookie method.
$user = get_userdata($user_id);
file_put_contents('/tmp/wp_rails_'.$user->user_login.'_'.$expiration, $logged_in_cookie);
with the code above the cookies content for each logged in user is writen to a file in the tmp folder. in the rails or whatever application this file can be read and compared to the actual cookie sendt by the browser. if it matches, the user is properly logged into rails.