Skip to content

Instantly share code, notes, and snippets.

@alanhoff
Created October 15, 2016 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanhoff/b0d0864ce232dac36914e00b65acd9c0 to your computer and use it in GitHub Desktop.
Save alanhoff/b0d0864ce232dac36914e00b65acd9c0 to your computer and use it in GitHub Desktop.
'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 })
'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