Last active
December 14, 2016 18:29
-
-
Save passatgt/70b3e8f97dff7dcc10877eb880a38b6f to your computer and use it in GitHub Desktop.
Custom email verification logic for Stormpath
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
// Init Stormpath for user management and authentication | |
app.use(stormpath.init(app, { | |
//Your other options you might have | |
expand: { | |
//The verification code will be saved to customData, so expand it first | |
customData: true | |
}, | |
postRegistrationHandler: function(account, req, res, next) { | |
//Create a verification code to verify email address later | |
helpers.createVerificationCode(account); | |
next(); | |
} | |
})); | |
//Function to create a new verification code | |
function createVerificationCode(account) { | |
var verificationCode = chance.guid(); //I used Chance.js to generate a unique ID: http://chancejs.com | |
//Save the verification status and the code into customData | |
account.customData.verified = false; | |
account.customData.verificationCode = verificationCode; | |
account.customData.save(function(err) { | |
// Check for error | |
if (err) return helpers.handleError(err, res); | |
//Send email to user, i'm using AWS SES for this | |
mailer.sendEmailTemplate(account.email, 'verification', { | |
verificationCode: verificationCode | |
}); | |
}); | |
} | |
//Custom endpoint to validate the verification code | |
module.exports.verify = function(req, res) { | |
//Check if maybe already verified | |
if (req.user.customData.verified) { | |
return res.status(403).send({ | |
status: 'fail', | |
code: 'already_verified', | |
message: 'Your account is already verified.' | |
}); | |
} else if (req.body.verificationCode != req.user.customData.verificationCode) { | |
//Check if verification code is valid | |
return res.status(400).send({ | |
status: 'fail', | |
code: 'not_valid_verification_code', | |
message: 'The verification code is not valid.' | |
}); | |
} else { | |
//All good, verify the user | |
req.user.customData.verified = true; | |
req.user.customData.verificationCode = null; | |
req.user.customData.save(function(err) { | |
// Check for error | |
if (err) return helpers.handleError(err, res); | |
//Return response | |
return res.status(200).send({ | |
status: 'success', | |
code: 'account_verified', | |
message: 'Email successfully verified!' | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment