0

enter image description here

This is my url when I run nodejs backend.

enter image description here This is my folder structure.

My index.js

// Import packages
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const port = 5000;
const bodyParser = require("body-parser");
const home = require("./pages/api/home");

// Middlewares
app.use(express.json());

// Routes
app.use("/home", home);

app.use(cors());
app.use(bodyParser.json());

// connection
app.listen(port, () => {
  console.log(`Server running in : ${port}`);
});

My home.js

const express = require("express");
const tokenCtrl = require("../../controller/tokenCtrl");
const router = express.Router();

router.get("/userID/:id", tokenCtrl.token);

module.exports = router;

My tokenCtrl.js

const zego = require("../lib/zegoServerAssistant");
const tokenCtrl = {
  token: async (req, res, next) => {
    const appId = process.env.appId;
    const userId = req.params.userId;
    const secret = process.env.secret;

    const effectiveTimeInSeconds = 2 * 60;

    const payloadObject = {
      room_id: userId,

      privilege: {
        1: 1, // loginRoom
        2: 0, // publishStream
      },
      stream_id_list: null,
    };
    try {
      const token = zego.generateToken04(
        appId,
        userId,
        secret,
        effectiveTimeInSeconds,
        JSON.stringify(payloadObject)
      );
      res.json({ token });
    } catch (e) {
      console.log({ e });
      res.json({ e: e?.errorMessage });
    }
  },
};
module.exports = tokenCtrl;



My zegoTokenGenerate.js

"use strict";
exports.__esModule = true;
var crypto_1 = require("crypto");
var ErrorCode;
(function (ErrorCode) {
  ErrorCode[(ErrorCode["success"] = 0)] = "success";
  ErrorCode[(ErrorCode["appIDInvalid"] = 1)] = "appIDInvalid";
  ErrorCode[(ErrorCode["userIDInvalid"] = 3)] = "userIDInvalid";
  ErrorCode[(ErrorCode["secretInvalid"] = 5)] = "secretInvalid";
  ErrorCode[(ErrorCode["effectiveTimeInSecondsInvalid"] = 6)] =
    "effectiveTimeInSecondsInvalid";
})(ErrorCode || (ErrorCode = {}));
function RndNum(a, b) {
  return Math.ceil((a + (b - a)) * Math.random());
}
// 生成 int32 范围的随机数
function makeNonce() {
  return RndNum(-2147483648, 2147483647);
}
function makeRandomIv() {
  var str = "0123456789abcdefghijklmnopqrstuvwxyz";
  var result = [];
  for (var i = 0; i < 16; i++) {
    var r = Math.floor(Math.random() * str.length);
    result.push(str.charAt(r));
  }
  return result.join("");
}

function getAlgorithm(keyBase64) {
  var key = Buffer.from(keyBase64);
  switch (key.length) {
    case 16:
      return "aes-128-cbc";
    case 24:
      return "aes-192-cbc";
    case 32:
      return "aes-256-cbc";
  }
  throw new Error("Invalid key length: " + key.length);
}
function aesEncrypt(plainText, key, iv) {
  var cipher = crypto_1.createCipheriv(getAlgorithm(key), key, iv);
  cipher.setAutoPadding(true);
  var encrypted = cipher.update(plainText);
  var final = cipher.final();
  var out = Buffer.concat([encrypted, final]);
  return Uint8Array.from(out).buffer;
}
function generateToken04(
  appId,
  userId,
  secret,
  effectiveTimeInSeconds,
  payload
) {
  console.log(appId + "appId");
  console.log(userId + "userId");
  console.log(secret + "secret");
  if (!appId || typeof appId !== "number") {
    throw {
      errorCode: ErrorCode.appIDInvalid,
      errorMessage: "appID invalid",
    };
  }
  if (!userId || typeof userId !== "string") {
    throw {
      errorCode: ErrorCode.userIDInvalid,
      errorMessage: "userId invalid",
    };
  }
  if (!secret || typeof secret !== "string" || secret.length !== 32) {
    throw {
      errorCode: ErrorCode.secretInvalid,
      errorMessage: "secret must be a 32 byte string",
    };
  }
  if (!effectiveTimeInSeconds || typeof effectiveTimeInSeconds !== "number") {
    throw {
      errorCode: ErrorCode.effectiveTimeInSecondsInvalid,
      errorMessage: "effectiveTimeInSeconds invalid",
    };
  }
  var createTime = Math.floor(new Date().getTime() / 1000);
  var tokenInfo = {
    app_id: appId,
    user_id: userId,
    nonce: makeNonce(),
    ctime: createTime,
    expire: createTime + effectiveTimeInSeconds,
    payload: payload || "",
  };

  var plaintText = JSON.stringify(tokenInfo);
  console.log("plain text: ", plaintText);

  var iv = makeRandomIv();
  console.log("iv", iv);

  var encryptBuf = aesEncrypt(plaintText, secret, iv);

  var _a = [new Uint8Array(8), new Uint8Array(2), new Uint8Array(2)],
    b1 = _a[0],
    b2 = _a[1],
    b3 = _a[2];
  new DataView(b1.buffer).setBigInt64(0, BigInt(tokenInfo.expire), false);
  new DataView(b2.buffer).setUint16(0, iv.length, false);
  new DataView(b3.buffer).setUint16(0, encryptBuf.byteLength, false);
  var buf = Buffer.concat([
    Buffer.from(b1),
    Buffer.from(b2),
    Buffer.from(iv),
    Buffer.from(b3),
    Buffer.from(encryptBuf),
  ]);
  var dv = new DataView(Uint8Array.from(buf).buffer);

  // console.log('-----------------');
  // console.log('-------getBigInt64----------', dv.getBigInt64(0));
  // console.log('-----------------');
  // console.log('-------getUint16----------', dv.getUint16(8));
  // console.log('-----------------');
  return "04" + Buffer.from(dv.buffer).toString("base64");
}
exports.generateToken04 = generateToken04;

When I log the appID it has value enter image description here

but my generateToken file said appID invalid. I dont know what to do. PLease help me.

This is my github fullfile. https://github.com/phu130201/node-express-vercel-master

0 Answers0