Skip to content
Snippets Groups Projects
Select Git revision
  • ed1759c91e1a4cd3529edb4e5dcfe59d15abd6e6
  • master default
  • feat/pull_changes
3 results

utils.js

Blame
  • user avatar
    Ayc0 authored
    6318ba50
    History
    utils.js 1.01 KiB
    /* eslint no-param-reassign: off, import/prefer-default-export: off */
    const jwt = require('jsonwebtoken');
    const { cert } = require('./config');
    
    const interval = (fn, initialTTL, output = { id: null, clear: () => undefined }) => {
      const timeoutID = setTimeout(async () => {
        let TTL = fn();
        if (TTL instanceof Promise) {
          TTL = await TTL;
        }
        const nextTTL = parseInt(TTL, 10) || initialTTL;
        interval(fn, nextTTL, output);
      }, initialTTL);
      output.id = timeoutID;
      output.clear = () => clearTimeout(timeoutID);
      return output;
    };
    
    const generateRandomString = (length) => {
      let text = '';
      const possible =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-,;:!?./§ù*^$£%µ&"\'(=';
    
      for (let i = 0; i < length; i += 1) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
    
      return text;
    };
    
    const createSignedJWT = () =>
      jwt.sign({ state: generateRandomString(20) }, cert, { algorithm: 'RS256' });
    
    module.exports = { interval, createSignedJWT };