How to use the randomUUID function from crypto

Find comprehensive JavaScript crypto.randomUUID code examples handpicked from public code repositorys.

60
61
62
63
64
65
66
67
68
69
  success = "Users count is limited to 5 users";
} else {
  if (mail == null || typeof mail == "undefined" || mail.match(EMAIL_REGEX)) {
    if (login.match(LOGIN_REGEX) && password.match(PASSWORD_REGEX)) {
      if (typeof users[login] == "undefined") {
        newUserHash = crypto.randomUUID().toString();
        if (permissions[0] == "") {
          permissions = [];
        }
        users[login] = {
fork icon11
star icon20
watch icon3

+ 3 other calls in file

54
55
56
57
58
59
60
61
62
await this.getStateAsync("clientID").then(async storedClientID => {
	if (storedClientID && typeof (storedClientID) != "undefined") {
		clientID = storedClientID.val?.toString() ?? "";
	}
	else {
		clientID = crypto.randomUUID();
		await this.setStateAsync("clientID", { val: clientID, ack: true });
	}
});
fork icon5
star icon11
watch icon5

1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
if (this.debug){
  console.log("Recovered address: ", address);
  console.log("Signed return value: ", sig);
}

let refId = crypto.randomUUID();

let body = {
  "op": "nft-offer-redeem",
  "client_reference_id": refId,
fork icon2
star icon4
watch icon3

22
23
24
25
26
27
28
29
30
31
  res.statusCode = 403;
  res.end(JSON.stringify({ "msg": `The node with name ${name} already exists. Use another name.` }));
  return;
}

const archive_uuid = crypto.randomUUID();
global.logger.info(`Adding new VPN node ${name}`);

//Generate .crt and .key for a new node
//Keep available IPs in ~/.deployed-config.json and take IP from this IP list only
fork icon3
star icon1
watch icon2

943
944
945
946
947
948
949
950
951
952
  }
}
if (channelGuid) {
  return res.status(200).send(channelGuid);
} else {
  channelGuid = crypto.randomUUID();
  if (channelGuid) {
  try {
    await storageManager.storeData("channelguid" + "-" + channel, channelGuid);
  } catch {
fork icon0
star icon5
watch icon4

20
21
22
23
24
25
26
27
28
29
// Get the user by authentication key
const user = login_controller.userByKey(auth_key);
if (!user || !user.isActive()) return undefined; // Not authorized to create a restaurant

// Generate the ID and the timestamp restaurant is created
const id = crypto.randomUUID();
const timestamp = Date.now();

// Create the restaurant object
const restaurant = {
fork icon0
star icon2
watch icon1

178
179
180
181
182
183
184
185
186
187
portal.config = cleanConfig(portal.config || configDefaults)
portal.configDraft = cleanConfig(portal.configDraft || configDefaults)
if (portal._id) return res.status(400).send('You cannot specify the id of the created portal')
if (portal.host) return res.status(400).send('You cannot specify the host of the created portal')
// this is better than nanoid to create an id that will be accepted by data-fair for the images dataset
portal._id = randomUUID()
if (req.user.accountOwnerRole !== 'admin') {
  return res.status(403).send('Vous devez être administrateur de l\'organisation pour modifier le portail.')
}
portal.owner = req.user.accountOwner
fork icon0
star icon0
watch icon3

43
44
45
46
47
48
49
50
51
52
    get_campaign_by_id_procedure_1.getCampaignByIdProcedure.sql,
    mark_donator_as_fraud_procedure_1.markDonatorAsFraudProcedure.sql,
];
const companies = [
    {
        id: crypto.randomUUID(),
        name: "Comp1",
        description: "description",
        goal_amount: 12500,
    },
fork icon0
star icon0
watch icon1

+ 12 other calls in file

185
186
187
188
189
190
191
192
193
194
async function signup(username, password, email) {
    try {
        await client.connect(uri)
        const database = client.db('auth');
        const creds = database.collection('creds');
        var randID = randomUUID()
        const doc = {
            id:randID,
            username: username, 
            email: email, 
fork icon0
star icon0
watch icon1

+ 11 other calls in file

595
596
597
598
599
600
601
602
603
604
  }
  util.runGnGen(options)
},

buildTarget: (target = config.buildTarget, options = config.defaultOptions) => {
  const buildId = crypto.randomUUID()
  console.log('building ' + target + ' (id=' + buildId + ') ...')

  let num_compile_failure = 1
  if (config.ignore_compile_failure)
fork icon0
star icon0
watch icon1

+ 2 other calls in file

70
71
72
73
74
75
76
77
78
    cals: 0,
    carbs: 0,
    protein: 0,
    fat: 0,
}
const filename = crypto.randomUUID()
let total_recipes = 0

const trainer = await Trainer.findOne({ where: { userId } })
fork icon0
star icon0
watch icon1

+ 3 other calls in file

107
108
109
110
111
112
113
114
115
116
    .resolves
    .toBeUndefined();
});

it('should create review to a non-existing product', async () => {
  const nonExistingId = crypto.randomUUID();
  const customer = await User.findOne({ where: { username: 'jane_dao' } });

  await expect(createReview(customer.id, nonExistingId, {
    rate: 4,
fork icon0
star icon0
watch icon1

+ 3 other calls in file

55
56
57
58
59
60
61
62
63
64
65
66
    include: ProductCategory
  });
}


async function bulkCreateTestProducts(sellerId) {
  const idOne = crypto.randomUUID();
  const idTwo = crypto.randomUUID();


  await Product.bulkCreate([
    {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

260
261
262
263
264
265
266
267
268
269
270
    },


    randomUUID: function(options) {
        const { randomUUID } = require('crypto');
        const { v4: uuidv4 } = require('uuid');
        return randomUUID ? randomUUID() : uuidv4();
    },


};
fork icon0
star icon0
watch icon2

340
341
342
343
344
345
346
347
348
349
function parser(expr, scope) {
    let tokens = lexer(expr),
        context = undefined,
        RESERVED = {
            'PI'       : function() { return Math.PI; },
            'UUID'     : function() { return randomUUID ? randomUUID() : uuidv4(); },
            'NOW'      : function() { return date(); },
            'NOW_UTC'  : function() { return utc_date(); },
            'TIMESTAMP': function() { return timestamp(); },
            '$this'    : function() { return scope.data; },
fork icon0
star icon0
watch icon2

21
22
23
24
25
26
27
28
29
30

const saltRounds = 10;
await bcrypt.hash(password, saltRounds, async (err, hash) => {
  console.log(hash)
  const data = await Users.create({
    id: randomUUID(),
    name: name,
    email: email,
    password: hash
  })
fork icon0
star icon0
watch icon1

+ 7 other calls in file

223
224
225
226
227
228
229
230
231
})

socket.on(ReceivedMessageForSendToGroup,async (data)=>{

    // console.log("got the messages ",data);
    let message_id=await crypto.randomUUID();

    console.log("message_id  : ",message_id);
    let user_id='';
fork icon0
star icon0
watch icon1

+ 4 other calls in file

3
4
5
6
7
8
9
10
11
12
13
14


class PasswordToken {
    async create(email) {
        let user = await User.findUserByEmail(email);
        if (user != undefined) {
            const token = crypto.randomUUID();


            try {
                await knex
                    .insert({
fork icon0
star icon0
watch icon1

66
67
68
69
70
71
72
73
74
75
76
  }
};


exports.createNewBackup = (bname, desc, type, sn, ratio, files = null) => {
  date = new Date();
  randuid = crypto.randomUUID().toString();
  date_str = date.getDate().toString().padStart(2, "0") + "_" + (date.getMonth() + 1).toString().padStart(2, "0") + "_" + date.getFullYear().toString().padStart(2, "0") + "-" + date.getHours().toString().padStart(2, "0") + "_" + date.getMinutes().toString().padStart(2, "0") + "_" + date.getSeconds().toString().padStart(2, "0");
  archname = "backup-" + type + "-" + date_str + ".zip";
  jsonf = {
    name: bname,
fork icon0
star icon0
watch icon1

63
64
65
66
67
68
69
70
71
72
73
  parse["lang"] = userLang;
  fs.writeFileSync("config.json", JSON.stringify(parse));
}


exports.writeDefaultUsersConfig = () => {
  newHash = crypto.randomUUID().toString();
  du = JSON.parse(defaultUsersConfig);
  du['zetrox']['hash'] = newHash;
  fs.writeFileSync("users.json", JSON.stringify(du, null, "\t"));
  return du;
fork icon0
star icon0
watch icon1