Last active
August 29, 2015 14:06
-
-
Save ryo88c/418beeddc324c76c8a57 to your computer and use it in GitHub Desktop.
Authenticate WordPress by Node.js (Socket.IO) ref: http://qiita.com/ryo88c/items/bf255343d6e54259cd2a
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.'); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment