More javascript (nodejs) to go with the passport wrapper I just posted:
UserBook.js
/*
* A wrapper for user Registration for a web site.
* This is an MYSQL version of the client to provide persistent state.
*
* Exports a single function that returns the object (UserBook) that does the work.
* UserBook exposes two public methods:
*
* updateUser(profile, userRegister(profile))
* profile: An object with information about the user.
* From this we will try and retrieve the local-id of the user.
* If there is no local-user we create one.
* userRegister: A callback used when the user-id is found.
* The id is added to the profile and this is passed as the
* parameter to the callback.
* getSavedUser(localId, userRegister(profile))
* localId: The local-id of a user retrieved from the session information.
* userRegister: A callback used when the user information is found.
*
*/
module.exports = function() {
// Local DB connection
var mysql = require('mysql');
var theDB = mysql.createConnection({
host: '127.0.0.1',
user: 'user',
password: 'password',
database: 'db'
});
// Create the UserBook object
return {
// The db object kept locally
db: theDB,
updateUser: function(profile, userRegistered) {
var db = this.db;
// See if the user exists.
db.query( 'SELECT * FROM Users WHERE Provider=? AND ProviderId=? LIMIT 1',
[profile.provider, profile.providerId],
function(err, rows) {
if (err) throw err;
if (rows.length == 1) {
// If we have found a local user the set the ID
profile.id = rows[0].ID;
if (profile.displayName != rows[0].DisplayName) {
// See if we need to update the display name.
db.query( 'UPDATE Users SET DisplayName=? WHERE Provider=? AND ProviderId=?',
[profile.displayName, profile.provider, profile.providerId],
function(err) {
if (err) throw err;
});
}
// Callback when user is identified.
userRegistered(profile);
} else {
// No local user found.
// So lets create a new one.
db.query( 'INSERT INTO Users (Provider, ProviderId, DisplayName) VALUES(?,?,?)',
[profile.provider, profile.providerId, profile.displayName],
function(err, result) {
if (err) throw err;
profile.id=result.insertId;
// Callback when new user is created
userRegistered(profile);
});
}
});
},
getSavedUser: function(localId, userRegistered) {
var db = this.db;
// get the local user from the DB
db.query( 'SELECT * FROM Users WHERE ID=? LIMIT 1',
[localId],
function(err, rows) {
if (err) throw err;
if (rows.length == 1) {
profile = { id: rows[0].ID,
provider: rows[0].Provider,
providerId: rows[0].ProviderId,
displayName:rows[0].DisplayName};
// Callback when information is retrieved.
userRegistered(profile);
}
});
},
};
}