Last active
December 4, 2016 10:05
-
-
Save thedavidmeister/1561fdd47f444bca0932d8de102714ac to your computer and use it in GitHub Desktop.
Alias auth0 users in mixpanel, expects `MIXPANEL_TOKEN` to be set in auth0 and `mpDistinctID` to be sent in `state` as base64 encoded JSON
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
function (user, context, callback) { | |
// https://github.com/auth0/rules/blob/master/rules/signup.md | |
user.app_metadata = user.app_metadata || {}; | |
var state64 = context.request.query.state || context.request.body.state; | |
// https://github.com/node-browser-compat/atob/blob/master/node-atob.js | |
var state = new Buffer(state64, 'base64').toString('binary'); | |
var statep = JSON.parse(state); | |
// short-circuit if the user has already been aliased. | |
if (user.app_metadata.mp_aliased) return callback(null, user, context); | |
// https://github.com/auth0/rules/blob/master/rules/mixpanel-track-event.md | |
// https://mixpanel.com/help/reference/http#distinct-id-alias | |
var mpEvent = { | |
"event": "$create_alias", | |
"properties": { | |
"distinct_id": statep.mpDistinctID, | |
"alias": user.user_id, | |
"token": configuration.MIXPANEL_TOKEN | |
} | |
}; | |
var base64Event = new Buffer(JSON.stringify(mpEvent)).toString('base64'); | |
request.get({ | |
url: 'http://api.mixpanel.com/track/', | |
qs: { | |
data: base64Event | |
} | |
}, function (e, r, b){ | |
if (!e && r.statusCode === 200) { | |
// https://github.com/auth0/rules/blob/master/rules/signup.md | |
user.app_metadata.mp_aliased = true; | |
auth0.users.updateAppMetadata(user.user_id, user.app_metadata) | |
.then(function() { | |
console.log('requested an alias for user ' + user.user_id + ' to ' + statep.mpDistinctID + ' with mixpanel'); | |
callback(null, user, context); | |
}) | |
.catch(function(e) { | |
console.log('error updating auth0 metadata for mixpanel aliasing'); | |
callback(e); | |
}); | |
} | |
else { | |
console.log('error aliasing user with mixpanel'); | |
callback(e); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment