All files / controllers agents.js

100% Statements 63/63
100% Branches 14/14
100% Functions 13/13
100% Lines 62/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224                        7x 7x       7x   7x 7x       7x       8x   7x 4x         4x   4x       4x   4x 4x       3x 2x                     3x                     3x   1x         3x 3x   2x       2x   1x         2x   2x 2x                 1x         1x   1x         2x 2x   2x           2x 1x   1x         2x 2x   2x         1x   1x         2x 2x   2x         1x   1x         2x   2x 2x   1x         1x   1x         3x 3x 2x           1x     1x         3x 3x 2x           1x     1x                              
import uniqid from 'uniqid';
import path from 'path';
import fs from 'fs';
 
import APIError from '../helpers/error';
 
import AgentCreate from '../source/agents/create';
import AgentDelete from '../source/agents/delete';
import AgentInformation from '../source/agents/information';
import AgentUpdate from '../source/agents/update';
import { PATH_AGENT_FILE, PATH_AGENT_INSTALLER_FILE } from '../../root';
 
export const beestockAgentFileName = 'beestock_agent.js';
export const beestockAgentFilePath = path.join(
  PATH_AGENT_FILE,
  beestockAgentFileName
);
export const beestockAgentFileExists = fs.existsSync(beestockAgentFilePath);
 
export const beestockAgentInstallerFileName = 'install_beestock_agent.sh';
export const beestockAgentInstallerFilePath = path.join(
  PATH_AGENT_INSTALLER_FILE,
  beestockAgentInstallerFileName
);
export const beestockAgentInstallerFileExists = fs.existsSync(
  beestockAgentInstallerFilePath
);
 
export const getRandomStr = () => (Math.random() + 1).toString(36).substring(2);
 
export const getNewToken = () =>
  Buffer.from(
    `${uniqid(getRandomStr())}${uniqid('', getRandomStr())}`
  ).toString('base64');
 
async function get(req, res) {
  const { code, protocol } = req.query;
 
  const fullUrlCalled = `${(protocol || req.protocol).replace(
    ':',
    ''
  )}://${req.get('host')}`;
  let installerCommand = '';
 
  try {
    const agent = await AgentInformation.getAgent({
      code,
    });
 
    if (agent) {
      installerCommand = `
        sudo bash install_beestock_agent.sh -code "${
          agent.code
        }" -url "${fullUrlCalled}" -token "${
        agent.token
      }" -name "beestock_agent_${agent.code
        .replace(/[^a-zA-Z0-9]/g, '_')
        .toLowerCase()}"
      `.trim();
    }
 
    const response = {
      success: true,
      data: agent
        ? {
            ...agent,
            installerRoute: `${fullUrlCalled}${req.baseUrl}/${beestockAgentInstallerFileName}`,
            installerFileName: beestockAgentInstallerFileName,
            installerCommand,
          }
        : null,
    };
    res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function getGrid(req, res) {
  try {
    const agents = await AgentInformation.getAllAgents();
 
    const response = {
      success: true,
      data: agents || [],
    };
    res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err.message);
  }
}
 
async function create(req, res) {
  const { code, name, description } = req.body;
 
  try {
    const newAgent = await AgentCreate.createAgent({
      code,
      name,
      description,
      token: getNewToken(),
      createdUser: req.userId,
      updatedUser: req.userId,
    });
 
    const response = {
      success: true,
      data: newAgent && newAgent.id,
    };
 
    res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function update(req, res) {
  try {
    const { code, name, description } = req.body;
 
    const agentData = {
      name,
      description,
      updatedUser: req.userId,
    };
 
    const updatedAgent = await AgentUpdate.updateAgent(code, agentData);
    return res.json({ success: true, data: updatedAgent });
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function updateToken(req, res) {
  try {
    const { code } = req.body;
 
    const updatedAgent = await AgentUpdate.updateAgent(code, {
      token: getNewToken(),
      updatedUser: req.userId,
    });
 
    return res.json({ success: true, data: updatedAgent });
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function updateActive(req, res) {
  try {
    const { code, active } = req.body;
 
    const updatedAgent = await AgentUpdate.updateAgent(code, {
      active,
      updatedUser: req.userId,
    });
 
    return res.json({ success: true, data: updatedAgent });
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
async function destroy(req, res) {
  const { code } = req.body;
 
  try {
    const dltAgent = await AgentDelete.deleteAgent(code);
 
    const response = {
      success: true,
      data: dltAgent,
    };
 
    res.json(response);
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR', err);
  }
}
 
function download(req, res) {
  try {
    if (beestockAgentFileExists) {
      res.download(
        beestockAgentFilePath,
        beestockAgentFileName,
        async () => {}
      );
    } else {
      res.status(404).send('File not found');
    }
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR');
  }
}
 
function downloadInstaller(req, res) {
  try {
    if (beestockAgentInstallerFileExists) {
      res.download(
        beestockAgentInstallerFilePath,
        beestockAgentInstallerFileName,
        async () => {}
      );
    } else {
      res.status(404).send('File not found');
    }
  } catch (err) {
    throw new APIError('UNKNOWN_ERROR');
  }
}
 
export default {
  getGrid,
  get,
  create,
  update,
  destroy,
  updateToken,
  updateActive,
  download,
  downloadInstaller,
};