// For database connection.
var DSN = '';
// WordPress database name.
var WPDB = '';
// Salt constants in wp-config.php.
var LOGGED_IN_KEY = '';
var LOGGED_IN_SALT = '';
// siteurl option in wp_options table.
var SITEURL = 'http://example.com/';
var crypto = require('crypto');
var md5 = crypto.createHash('md5');
var mysql = require('mysql2');
var dbh = mysql.createConnection(DSN);
dbh.connect();
dbh.query('USE ' + WPDB);
io.on('connection', function (socket) {
var cookies = {};
socket.request.headers.cookie.split(';').forEach(function(cookie) {
var parts = cookie.split('=');
cookies[parts[0].trim()] = (parts[1] || '').trim();
});
md5.update(SITEURL, 'utf8');
var authInfo = unescape(cookies['wordpress_logged_in_' + md5.digest('hex')]).split('|');
dbh.execute('SELECT * FROM `wp_users` WHERE `user_login` = ?', [authInfo[0]], function(err, res) {
// Generate hash-key
var hmac = crypto.createHmac('md5', LOGGED_IN_KEY + LOGGED_IN_SALT);
hmac.update(res[0].user_login + res[0].user_pass.substr(8, 4) + '|' + authInfo[1]);
var hashKey = hmac.digest('hex');
// Generate hmac-hash
var hmac = crypto.createHmac('md5', hashKey);
hmac.update(res[0].user_login + '|' + authInfo[1]);
var hash = hmac.digest('hex');
if (authInfo[2] === hash) {
// Authenticated.
socket.emit('chat message', 'Logged in. Hello ' + res[0].display_name + ' san.');
}
});
});
More than 5 years have passed since last update.
Authenticate WordPress by Node.js (Socket.IO)
Last updated at Posted at 2014-09-08
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme