Created
December 29, 2017 22:17
-
-
Save adnan-i/f94691d1646b668d3e59798a01641f3b to your computer and use it in GitHub Desktop.
Node service responsible for generating and sending the email verification email and for verifying the link
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
const _ = require('lodash'); | |
class EmailVerificationService { | |
constructor(server) { | |
this.server = server; | |
this.logger = server.plugins.core.LoggerService.tagged('EmailVerificationService'); | |
this.jwtKey = server.app.config.get('/jwt/key'); | |
this.MailService = server.plugins.mail.MailService; | |
this.MailTemplateService = server.plugins.mail.MailTemplateService; | |
this.JWTService = server.plugins.core.JWTService; | |
} | |
static init(...args) { | |
if (this.instance) return this.instance; | |
this.instance = new this(...args); | |
return this.instance; | |
} | |
verify(hash) { | |
return Promise.resolve() | |
.then(() => this.JWTService.decode(hash)) | |
.then((email) => { | |
if (!email) { | |
throw new Error(`Unable to retrieve email from hash ${hash}`); | |
} | |
return this.server.plugins.users.User.findOne({ where: { email } }) | |
.then((user) => { | |
if (!user) { | |
throw new Error(`Unable to retrieve user by email ${email}`); | |
} | |
return user; | |
}) | |
}) | |
.catch((err) => { | |
this.logger.error(err); | |
throw new Error('Invalid email verification code'); | |
}); | |
} | |
getVerificationLink(email) { | |
return Promise.resolve() | |
.then(() => { | |
return this.JWTService.encode(email) | |
.then((hash) => { | |
if (!_.isString(hash)) { | |
throw new Error(`getEmailVerificationLink expects String hash, got: ${typeof hash} ${hash}`); | |
} | |
const path = `/verify-email?h=${hash}`; | |
const hostname = this.server.app.config.get('/app/hostname'); | |
return `${hostname}${path}`; | |
}); | |
}); | |
} | |
sendVerificationEmail(email) { | |
return this.getVerificationLink(email) | |
.then((emailVerificationLink) => { | |
const tplParams = { emailVerificationLink }; | |
const html = this.MailTemplateService.getCompiledTemplate('verifyEmail', tplParams); | |
return this.MailService.send({ | |
to: email, | |
subject: 'Verify account email', | |
html | |
}); | |
}) | |
} | |
} | |
module.exports = EmailVerificationService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment