How to generate a random number code to confirm an email

3.1k Views Asked by At

I am a beginner and I cannot find a tutorial on the Internet to send a 5-digit code (for example) by email to a user who has just registered or wants to reset his password.

I am using a Rest API under Node.js and a React.js frontend. So you have to register the user and send him an email containing a code and when the user will try to connect without his account being indicated as "active" in the database, we will ask him for a 5-digit code.

I can not find any tutorials on this practice to know how to do it the right way without security vulnerabilities.

Thank you for your understanding !

4

There are 4 best solutions below

0
On

If you are using Node.js above v12.19.0:

import { randomInt } from 'node:crypto';

// 6 digits, change the random max number and pad length if you need 5 digits
function randomCode() {
  return randomInt(1000_000).toString().padStart(6, '0');
}
0
On

Generating a five digit code from a given set of characters is a quite easy task. Getting rid of security issues is much more difficult and depends on your required level of security.

If you send the code via unencrypted email, the security is not very high (man in the middle attacks). If you use encrypted email (PGP) it can be considered safe.

Code to generate 5 character code from a given set:

const givenSet = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";

let code = "";
for(let i=0; i<5; i++) {
   let pos = Math.floor(Math.random()*givenSet.length);
   code += givenSet[pos];
}
0
On

It would be much easier to use the native crypto package.

const crypto = require('crypto')
const randomEightDigits = crypto.randomBytes(6).toString('base64')
0
On

The simplest way you can use crypto to generate random number

const crypto = require("crypto");

// Asynchronous
crypto.randomInt(0, 1000000, (err, n) => {
  if (err) throw err;
  console.log(n);
});

Happy Coding..!