Notes/services/utils.js

61 lines
1.2 KiB
JavaScript
Raw Normal View History

2017-10-21 21:10:33 -04:00
"use strict";
const crypto = require('crypto');
function newNoteId() {
2017-10-28 12:12:20 -04:00
return randomString(12);
}
2017-10-28 12:12:20 -04:00
const ALPHA_NUMERIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function randomString(length) {
let result = '';
for (let i = length; i > 0; --i) {
2017-10-28 12:12:20 -04:00
result += ALPHA_NUMERIC[Math.floor(Math.random() * ALPHA_NUMERIC.length)];
}
return result;
}
function randomSecureToken(bytes = 32) {
2017-10-29 11:22:41 -04:00
return crypto.randomBytes(bytes).toString('base64');
}
function nowTimestamp() {
2017-10-15 17:07:34 -04:00
return Math.floor(Date.now() / 1000);
}
function toBase64(plainText) {
return Buffer.from(plainText).toString('base64');
}
function fromBase64(encodedText) {
return Buffer.from(encodedText, 'base64');
}
2017-10-29 14:55:48 -04:00
function hmac(secret, value) {
const hmac = crypto.createHmac('sha256', Buffer.from(secret.toString(), 'ASCII'));
hmac.update(value.toString());
return hmac.digest('base64');
}
function browserId(req) {
return req.get('x-browser-id');
}
function isElectron() {
return !!process.versions['electron'];
}
module.exports = {
randomSecureToken,
2017-10-28 12:12:20 -04:00
randomString,
nowTimestamp,
newNoteId,
toBase64,
2017-10-29 14:55:48 -04:00
fromBase64,
hmac,
browserId,
isElectron
};