Sunday, 29 September 2013

Authentication with NodeJS Express Passport RedisStore ForcedotCom strategy

Authentication with NodeJS Express Passport RedisStore ForcedotCom strategy

I'm going around in circles with my authentication strategy. I have a
solution working where I'm serializing the entire user object. However, I
want to do things differently but can't figure out how to customize the
solution.
I'm authenticating using the ForceDotCom PassportJS oauth strategy. I want
to use the user id returned by Salesforce as my session key.
Unfortunately, the id is embedded in a URL and I'm using regex to extract
the last section -
https://login.salesforce.com/id/00Di0000000dyRoEAI/005i0000001GM5rAAG
The reason I want to use this as my key is because later I will monitor
for updates on Salesforce objects and use socket.io to emit related events
to specific users, i.e. the owner of the object. When I receive object
updates I only get the last part of what Salesforce calls the id during
oauth.
Additionally, I want to add custom fields to my session hash, e.g. profile
photo url. These fields are returned by Salesforce API call to retrieve
user details and this happens independently of oauth.
Anyway, it looks like I can use Passport serialize and deserialize to
customize the key for the session object. I've attempted to do this below.
I'm confused as to how this relates to my Express configuration which
specifies a RedisStore for my sessions and a key of expressSid. Do I need
to change anything in my Express settings to make the custom key work?
What I have below seems to work. However, in Redis I end up with hashes
prepended with my custom identifier "user:" and other hashes prepended
with "sess:" which I assume Express is creating on session creation? My
custom hash doesn't contain any of the oauth information which makes me
concerned about token expiration etc.
I'd really like to have a single custom hash with both oauth tokens and my
additional user details in it.
Passport serialize / deserialize functions:
passport.serializeUser(function(user, done) {
var userId = RegExp('[^/]*$').exec(user.id)||[,null][1];
console.log(userId);
done(null, userId);
});
passport.deserializeUser(function(id, done) {
redis.hgetall("user:"+id, function(err, data) {
done(null, data);
});
});
Express config:
appSecure.use(express.session({ secret: expressSecret, store:
sessionStore, key:'expressSid', cookie: { domain:'.domain.com'}}));
appSecure.use(passport.initialize());
appSecure.use(passport.session());

No comments:

Post a Comment