Created
October 15, 2016 20:57
-
-
Save alanhoff/b0d0864ce232dac36914e00b65acd9c0 to your computer and use it in GitHub Desktop.
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
'use strict' | |
const crypto = require('crypto') | |
const db = require('../lib/db') | |
const email = require('../lib/email') | |
const HMAC_SECRET = 'here_be_dragons' | |
// Cria um link a prova de tampering | |
const nonce = crypto.randomBytes(256).toString('hex') | |
const link = `https://meusistema.com.br/verificar?nonce=${nonce}` | |
const signature = crypto.createHmac('sha256', HMAC_SECRET).update(link).digest('hex') | |
const signesLink = `${link}&sig=${signature}` | |
const expires = new Date().getTime() + (15 * 60 * 1000) // Não deve ser utilizado depois de 15 minutos | |
// Grava o nonce na sua base dados | |
db('nonces').insert({ nonce, user_id: 'alan', expires_at: new }) | |
// O link está pronto para ser enviado | |
email.send('verificacao', { 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
'use strict' | |
const crypto = require('crypto') | |
const db = require('../lib/db') | |
const HMAC_SECRET = 'here_be_dragons' | |
// Verifica a integridade do link | |
const link = `https://meusistema.com.br/verificar?nonce=${request.query.nonce}` | |
const signature = crypto.createHmac('sha256', HMAC_SECRET).update(link).digest('hex') | |
if (signature !== request.query.sig) { | |
throw new Error('Tampering detectado!') | |
} | |
// Pega o nonce no banco de dados | |
const { userId } = db('nonces').findOne({ nonce: request.query.nonce }) | |
.where('expires_at', '<', new Date().getTime()) | |
if (!userId) { | |
throw new Error('Código de verificação inválido, por favor tente novamente') | |
} else { | |
// Faz o update do usuário e remove o nonce do banco para não ser usado novamente | |
db('users').update({ verified: true }).where('user_id', userId) | |
db('nonces').delete().where('nonce', request.query.nonce) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment